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
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int lowercase_ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class A_ ( datasets.BuilderConfig ): '''simple docstring''' __snake_case = None def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ): import pyspark def generate_fn(): __lowerCamelCase : Any = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: __lowerCamelCase : Dict = df_with_partition_id.select('*' ).where(f'part_id = {partition_id}' ).drop('part_id' ) __lowerCamelCase : Any = partition_df.collect() __lowerCamelCase : List[str] = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class A_ ( _BaseExamplesIterable ): '''simple docstring''' def __init__( self: List[Any] , a: "pyspark.sql.DataFrame" , a: List[str]=None , ): __lowerCamelCase : Any = df __lowerCamelCase : Optional[int] = partition_order or range(self.df.rdd.getNumPartitions() ) __lowerCamelCase : str = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self: str ): yield from self.generate_examples_fn() def _snake_case ( self: Tuple , a: np.random.Generator ): __lowerCamelCase : Union[str, Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a ) return SparkExamplesIterable(self.df , partition_order=a ) def _snake_case ( self: List[Any] , a: int , a: int ): __lowerCamelCase : int = self.split_shard_indices_by_worker(a , a ) return SparkExamplesIterable(self.df , partition_order=a ) @property def _snake_case ( self: Any ): return len(self.partition_order ) class A_ ( datasets.DatasetBuilder ): '''simple docstring''' __snake_case = SparkConfig def __init__( self: List[Any] , a: "pyspark.sql.DataFrame" , a: str = None , a: str = None , **a: Optional[int] , ): import pyspark __lowerCamelCase : List[Any] = pyspark.sql.SparkSession.builder.getOrCreate() __lowerCamelCase : Dict = df __lowerCamelCase : Any = working_dir super().__init__( cache_dir=a , config_name=str(self.df.semanticHash() ) , **a , ) def _snake_case ( self: List[Any] ): # Returns the path of the created file. def create_cache_and_write_probe(a: Any ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=a ) __lowerCamelCase : str = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(a , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __lowerCamelCase : Union[str, Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(a ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def _snake_case ( self: List[Any] ): return datasets.DatasetInfo(features=self.config.features ) def _snake_case ( self: str , a: datasets.download.download_manager.DownloadManager ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def _snake_case ( self: Union[str, Any] , a: Dict ): import pyspark def get_arrow_batch_size(a: List[Any] ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) __lowerCamelCase : int = self.df.count() __lowerCamelCase : str = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __lowerCamelCase : List[str] = ( self.df.limit(a ) .repartition(1 ) .mapInArrow(a , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) __lowerCamelCase : Union[str, Any] = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __lowerCamelCase : Tuple = min(a , int(approx_total_size / max_shard_size ) ) __lowerCamelCase : Tuple = self.df.repartition(a ) def _snake_case ( self: Tuple , a: str , a: str , a: int , ): import pyspark __lowerCamelCase : Optional[Any] = ParquetWriter if file_format == 'parquet' else ArrowWriter __lowerCamelCase : List[Any] = os.path.join(self._working_dir , os.path.basename(a ) ) if self._working_dir else fpath __lowerCamelCase : List[Any] = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __lowerCamelCase : List[Any] = self.config.features __lowerCamelCase : Union[str, Any] = self._writer_batch_size __lowerCamelCase : Tuple = self._fs.storage_options def write_arrow(a: Any ): # Within the same SparkContext, no two task attempts will share the same attempt ID. __lowerCamelCase : Optional[int] = pyspark.TaskContext().taskAttemptId() __lowerCamelCase : int = next(a , a ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = writer_class( features=a , path=working_fpath.replace('SSSSS' , F'{shard_id:05d}' ).replace('TTTTT' , F'{task_id:05d}' ) , writer_batch_size=a , storage_options=a , embed_local_files=a , ) __lowerCamelCase : int = pa.Table.from_batches([first_batch] ) writer.write_table(a ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __lowerCamelCase , __lowerCamelCase : Optional[int] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 __lowerCamelCase : int = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , F'{shard_id:05d}' ).replace('TTTTT' , F'{task_id:05d}' ) , writer_batch_size=a , storage_options=a , embed_local_files=a , ) __lowerCamelCase : Tuple = pa.Table.from_batches([batch] ) writer.write_table(a ) if writer._num_bytes > 0: __lowerCamelCase , __lowerCamelCase : Tuple = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(a ) ): __lowerCamelCase : int = os.path.join(os.path.dirname(a ) , os.path.basename(a ) ) shutil.move(a , a ) __lowerCamelCase : Dict = ( self.df.mapInArrow(a , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def _snake_case ( self: Tuple , a: "datasets.SplitGenerator" , a: str = "arrow" , a: Optional[Union[str, int]] = None , a: Optional[int] = None , **a: Dict , ): self._validate_cache_dir() __lowerCamelCase : Dict = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a ) __lowerCamelCase : Tuple = not is_remote_filesystem(self._fs ) __lowerCamelCase : Optional[int] = os.path.join if is_local else posixpath.join __lowerCamelCase : int = '-TTTTT-SSSSS-of-NNNNN' __lowerCamelCase : Any = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' __lowerCamelCase : Union[str, Any] = path_join(self._output_dir , a ) __lowerCamelCase : int = 0 __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Any = [] __lowerCamelCase : Any = [] for task_id, content in self._prepare_split_single(a , a , a ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Any = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(a ) __lowerCamelCase : Dict = total_num_examples __lowerCamelCase : Any = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: __lowerCamelCase : int = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __lowerCamelCase : Tuple = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a: int , a: int , a: int , ): rename( a , fpath.replace('SSSSS' , F'{shard_id:05d}' ).replace('TTTTT' , F'{task_id:05d}' ) , fpath.replace('TTTTT-SSSSS' , F'{global_shard_id:05d}' ).replace('NNNNN' , F'{total_shards:05d}' ) , ) __lowerCamelCase : Any = [] __lowerCamelCase : int = 0 for i in range(len(a ) ): __lowerCamelCase , __lowerCamelCase : Optional[Any] = task_id_and_num_shards[i] for shard_id in range(a ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(a , len(a ) ).map(lambda a : _rename_shard(*a ) ).collect() else: # don't use any pattern __lowerCamelCase : Optional[Any] = 0 __lowerCamelCase : Tuple = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , F'{shard_id:05d}' ).replace('TTTTT' , F'{task_id:05d}' ) , fpath.replace(a , '' ) , ) def _snake_case ( self: Dict , a: "datasets.SplitGenerator" , ): return SparkExamplesIterable(self.df )
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = 42 __snake_case = 42 __snake_case = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
from itertools import product def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = sides_number __lowerCamelCase : Union[str, Any] = max_face_number * dice_number __lowerCamelCase : int = [0] * (max_total + 1) __lowerCamelCase : Dict = 1 __lowerCamelCase : Optional[int] = range(SCREAMING_SNAKE_CASE__ , max_face_number + 1 ) for dice_numbers in product(SCREAMING_SNAKE_CASE__ , repeat=SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = sum(SCREAMING_SNAKE_CASE__ ) totals_frequencies[total] += 1 return totals_frequencies def UpperCamelCase__ ( ): __lowerCamelCase : Any = total_frequency_distribution( sides_number=4 , dice_number=9 ) __lowerCamelCase : List[str] = total_frequency_distribution( sides_number=6 , dice_number=6 ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : Any = 9 __lowerCamelCase : str = 4 * 9 __lowerCamelCase : List[str] = 6 for peter_total in range(SCREAMING_SNAKE_CASE__ , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) __lowerCamelCase : Any = (4**9) * (6**6) __lowerCamelCase : List[str] = peter_wins_count / total_games_number __lowerCamelCase : Any = round(SCREAMING_SNAKE_CASE__ , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(F"""{solution() = }""")
669
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
1
import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class A_ : '''simple docstring''' def __init__( self: Dict , a: Tuple , a: List[str]=13 , a: Optional[int]=7 , a: Any=True , a: Optional[Any]=True , a: Optional[int]=True , a: Optional[Any]=True , a: str=99 , a: Tuple=64 , a: Tuple=32 , a: List[str]=5 , a: str=4 , a: int=37 , a: int="gelu" , a: Dict=0.1 , a: str=0.1 , a: Optional[Any]=512 , a: Tuple=16 , a: str=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=3 , a: List[str]=4 , a: Dict=None , ): __lowerCamelCase : Any = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : List[str] = seq_length __lowerCamelCase : Optional[int] = is_training __lowerCamelCase : Optional[int] = use_input_mask __lowerCamelCase : Dict = use_token_type_ids __lowerCamelCase : Optional[Any] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : Tuple = hidden_size __lowerCamelCase : Dict = embedding_size __lowerCamelCase : str = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = intermediate_size __lowerCamelCase : str = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Tuple = attention_probs_dropout_prob __lowerCamelCase : List[Any] = max_position_embeddings __lowerCamelCase : List[str] = type_vocab_size __lowerCamelCase : Union[str, Any] = type_sequence_label_size __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : List[str] = num_choices __lowerCamelCase : Optional[int] = scope def _snake_case ( self: str ): __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCamelCase : Optional[int] = None __lowerCamelCase : Optional[int] = None __lowerCamelCase : Tuple = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCamelCase : int = ids_tensor([self.batch_size] , self.num_choices ) __lowerCamelCase : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self: str ): return MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , ) def _snake_case ( self: Optional[Any] , a: Any , a: List[str] , a: List[str] , a: Tuple , a: Optional[int] , a: Any , a: List[str] ): __lowerCamelCase : List[Any] = MobileBertModel(config=a ) model.to(a ) model.eval() __lowerCamelCase : Union[str, Any] = model(a , attention_mask=a , token_type_ids=a ) __lowerCamelCase : Any = model(a , token_type_ids=a ) __lowerCamelCase : Optional[Any] = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _snake_case ( self: Dict , a: Union[str, Any] , a: List[Any] , a: str , a: Tuple , a: Any , a: Dict , a: Optional[int] ): __lowerCamelCase : List[Any] = MobileBertForMaskedLM(config=a ) model.to(a ) model.eval() __lowerCamelCase : str = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self: Union[str, Any] , a: Optional[int] , a: Union[str, Any] , a: Dict , a: str , a: str , a: str , a: List[Any] ): __lowerCamelCase : List[str] = MobileBertForNextSentencePrediction(config=a ) model.to(a ) model.eval() __lowerCamelCase : List[Any] = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def _snake_case ( self: Dict , a: Optional[int] , a: Optional[int] , a: Any , a: Union[str, Any] , a: List[str] , a: Optional[Any] , a: Tuple ): __lowerCamelCase : List[Any] = MobileBertForPreTraining(config=a ) model.to(a ) model.eval() __lowerCamelCase : Optional[int] = model( a , attention_mask=a , token_type_ids=a , labels=a , next_sentence_label=a , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def _snake_case ( self: Union[str, Any] , a: str , a: Tuple , a: Union[str, Any] , a: Optional[Any] , a: int , a: List[Any] , a: Dict ): __lowerCamelCase : str = MobileBertForQuestionAnswering(config=a ) model.to(a ) model.eval() __lowerCamelCase : Optional[Any] = model( a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] , a: int , a: List[Any] , a: Dict , a: str , a: Any , a: List[str] , a: Union[str, Any] ): __lowerCamelCase : Tuple = self.num_labels __lowerCamelCase : List[str] = MobileBertForSequenceClassification(a ) model.to(a ) model.eval() __lowerCamelCase : List[str] = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Union[str, Any] , a: List[str] , a: Optional[int] , a: Union[str, Any] , a: List[str] , a: Optional[int] , a: Optional[Any] , a: str ): __lowerCamelCase : Any = self.num_labels __lowerCamelCase : Tuple = MobileBertForTokenClassification(config=a ) model.to(a ) model.eval() __lowerCamelCase : Dict = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self: Tuple , a: Optional[int] , a: Tuple , a: Union[str, Any] , a: Optional[int] , a: Dict , a: Optional[Any] , a: Any ): __lowerCamelCase : Dict = self.num_choices __lowerCamelCase : Any = MobileBertForMultipleChoice(config=a ) model.to(a ) model.eval() __lowerCamelCase : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : Tuple = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : Union[str, Any] = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = config_and_inputs __lowerCamelCase : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) __snake_case = ( { """feature-extraction""": MobileBertModel, """fill-mask""": MobileBertForMaskedLM, """question-answering""": MobileBertForQuestionAnswering, """text-classification""": MobileBertForSequenceClassification, """token-classification""": MobileBertForTokenClassification, """zero-shot""": MobileBertForSequenceClassification, } if is_torch_available() else {} ) __snake_case = True def _snake_case ( self: Tuple , a: Dict , a: str , a: Optional[Any]=False ): __lowerCamelCase : Optional[Any] = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class in get_values(a ): __lowerCamelCase : str = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=a ) __lowerCamelCase : Dict = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def _snake_case ( self: List[Any] ): __lowerCamelCase : str = MobileBertModelTester(self ) __lowerCamelCase : List[str] = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Dict ): self.config_tester.run_common_tests() def _snake_case ( self: List[Any] ): __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*a ) def _snake_case ( self: Dict ): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*a ) def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*a ) def _snake_case ( self: int ): __lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*a ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return torch.tensor( SCREAMING_SNAKE_CASE__ , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) lowercase_ = 1E-3 @require_torch @require_sentencepiece @require_tokenizers class A_ ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = MobileBertModel.from_pretrained('google/mobilebert-uncased' ).to(a ) __lowerCamelCase : Optional[Any] = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] ) with torch.no_grad(): __lowerCamelCase : Union[str, Any] = model(a )[0] __lowerCamelCase : Optional[int] = torch.Size((1, 9, 512) ) self.assertEqual(output.shape , a ) __lowerCamelCase : Dict = torch.tensor( [ [ [-2.473_6526e07, 8.269_1656e04, 1.652_1838e05], [-5.754_1704e-01, 3.905_6022e00, 4.401_1507e00], [2.604_7359e00, 1.567_7652e00, -1.732_4188e-01], ] ] , device=a , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE __lowerCamelCase : Optional[int] = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) __lowerCamelCase : List[Any] = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
669
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
1
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\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.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self: Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/krishnap25/mauve' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/krishnap25/mauve'] , reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] , ) def _snake_case ( self: Optional[Any] , a: int , a: Any , a: Union[str, Any]=None , a: Dict=None , a: List[str]=None , a: str=None , a: List[Any]="auto" , a: Union[str, Any]=-1 , a: int=0.9 , a: List[str]=5 , a: str=500 , a: str="gpt2-large" , a: str=-1 , a: List[Any]=1024 , a: Tuple=25 , a: Optional[int]=5 , a: List[Any]=True , a: Any=25 , ): __lowerCamelCase : Any = compute_mauve( p_text=a , q_text=a , p_features=a , q_features=a , p_tokens=a , q_tokens=a , num_buckets=a , pca_max_data=a , kmeans_explained_var=a , kmeans_num_redo=a , kmeans_max_iter=a , featurize_model_name=a , device_id=a , max_text_length=a , divergence_curve_discretization_size=a , mauve_scaling_factor=a , verbose=a , seed=a , ) return out
669
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return int((input_a, input_a).count(1 ) != 0 ) def UpperCamelCase__ ( ): assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
669
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
1
from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor"""] __snake_case = """SamImageProcessor""" def __init__( self: Any , a: Dict ): super().__init__(a ) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : List[Any] = -10 __lowerCamelCase : List[Any] = self.image_processor.size['longest_edge'] def __call__( self: Optional[int] , a: Any=None , a: Union[str, Any]=None , a: str=None , a: Dict=None , a: Optional[Union[str, TensorType]] = None , **a: Union[str, Any] , ): __lowerCamelCase : Optional[int] = self.image_processor( a , return_tensors=a , **a , ) # pop arguments that are not used in the foward but used nevertheless __lowerCamelCase : str = encoding_image_processor['original_sizes'] if hasattr(a , 'numpy' ): # Checks if Torch or TF tensor __lowerCamelCase : Tuple = original_sizes.numpy() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = self._check_and_preprocess_points( input_points=a , input_labels=a , input_boxes=a , ) __lowerCamelCase : List[Any] = self._normalize_and_convert( a , a , input_points=a , input_labels=a , input_boxes=a , return_tensors=a , ) return encoding_image_processor def _snake_case ( self: Optional[Any] , a: Tuple , a: Dict , a: Union[str, Any]=None , a: int=None , a: str=None , a: List[str]="pt" , ): if input_points is not None: if len(a ) != len(a ): __lowerCamelCase : Union[str, Any] = [ self._normalize_coordinates(self.target_size , a , original_sizes[0] ) for point in input_points ] else: __lowerCamelCase : Dict = [ self._normalize_coordinates(self.target_size , a , a ) for point, original_size in zip(a , a ) ] # check that all arrays have the same shape if not all(point.shape == input_points[0].shape for point in input_points ): if input_labels is not None: __lowerCamelCase , __lowerCamelCase : Optional[int] = self._pad_points_and_labels(a , a ) __lowerCamelCase : List[str] = np.array(a ) if input_labels is not None: __lowerCamelCase : int = np.array(a ) if input_boxes is not None: if len(a ) != len(a ): __lowerCamelCase : List[Any] = [ self._normalize_coordinates(self.target_size , a , original_sizes[0] , is_bounding_box=a ) for box in input_boxes ] else: __lowerCamelCase : Any = [ self._normalize_coordinates(self.target_size , a , a , is_bounding_box=a ) for box, original_size in zip(a , a ) ] __lowerCamelCase : str = np.array(a ) if input_boxes is not None: if return_tensors == "pt": __lowerCamelCase : List[str] = torch.from_numpy(a ) # boxes batch size of 1 by default __lowerCamelCase : Tuple = input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes elif return_tensors == "tf": __lowerCamelCase : str = tf.convert_to_tensor(a ) # boxes batch size of 1 by default __lowerCamelCase : Tuple = tf.expand_dims(a , 1 ) if len(input_boxes.shape ) != 3 else input_boxes encoding_image_processor.update({'input_boxes': input_boxes} ) if input_points is not None: if return_tensors == "pt": __lowerCamelCase : Union[str, Any] = torch.from_numpy(a ) # point batch size of 1 by default __lowerCamelCase : Optional[int] = input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points elif return_tensors == "tf": __lowerCamelCase : int = tf.convert_to_tensor(a ) # point batch size of 1 by default __lowerCamelCase : str = tf.expand_dims(a , 1 ) if len(input_points.shape ) != 4 else input_points encoding_image_processor.update({'input_points': input_points} ) if input_labels is not None: if return_tensors == "pt": __lowerCamelCase : Tuple = torch.from_numpy(a ) # point batch size of 1 by default __lowerCamelCase : Any = input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels elif return_tensors == "tf": __lowerCamelCase : str = tf.convert_to_tensor(a ) # point batch size of 1 by default __lowerCamelCase : Any = tf.expand_dims(a , 1 ) if len(input_labels.shape ) != 3 else input_labels encoding_image_processor.update({'input_labels': input_labels} ) return encoding_image_processor def _snake_case ( self: List[Any] , a: str , a: Optional[int] ): __lowerCamelCase : List[Any] = max([point.shape[0] for point in input_points] ) __lowerCamelCase : int = [] for i, point in enumerate(a ): if point.shape[0] != expected_nb_points: __lowerCamelCase : Optional[int] = np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value] , axis=0 ) __lowerCamelCase : int = np.append(input_labels[i] , [self.point_pad_value] ) processed_input_points.append(a ) __lowerCamelCase : Optional[int] = processed_input_points return input_points, input_labels def _snake_case ( self: Optional[Any] , a: int , a: np.ndarray , a: Optional[Any] , a: Any=False ): __lowerCamelCase , __lowerCamelCase : Dict = original_size __lowerCamelCase , __lowerCamelCase : int = self.image_processor._get_preprocess_shape(a , longest_edge=a ) __lowerCamelCase : Tuple = deepcopy(a ).astype(a ) if is_bounding_box: __lowerCamelCase : Tuple = coords.reshape(-1 , 2 , 2 ) __lowerCamelCase : Union[str, Any] = coords[..., 0] * (new_w / old_w) __lowerCamelCase : Optional[Any] = coords[..., 1] * (new_h / old_h) if is_bounding_box: __lowerCamelCase : int = coords.reshape(-1 , 4 ) return coords def _snake_case ( self: Dict , a: Tuple=None , a: List[str]=None , a: Union[str, Any]=None , ): if input_points is not None: if hasattr(a , 'numpy' ): # Checks for TF or Torch tensor __lowerCamelCase : Optional[int] = input_points.numpy().tolist() if not isinstance(a , a ) or not isinstance(input_points[0] , a ): raise ValueError('Input points must be a list of list of floating points.' ) __lowerCamelCase : Optional[Any] = [np.array(a ) for input_point in input_points] else: __lowerCamelCase : Optional[int] = None if input_labels is not None: if hasattr(a , 'numpy' ): __lowerCamelCase : Optional[Any] = input_labels.numpy().tolist() if not isinstance(a , a ) or not isinstance(input_labels[0] , a ): raise ValueError('Input labels must be a list of list integers.' ) __lowerCamelCase : Tuple = [np.array(a ) for label in input_labels] else: __lowerCamelCase : Union[str, Any] = None if input_boxes is not None: if hasattr(a , 'numpy' ): __lowerCamelCase : Any = input_boxes.numpy().tolist() if ( not isinstance(a , a ) or not isinstance(input_boxes[0] , a ) or not isinstance(input_boxes[0][0] , a ) ): raise ValueError('Input boxes must be a list of list of list of floating points.' ) __lowerCamelCase : str = [np.array(a ).astype(np.floataa ) for box in input_boxes] else: __lowerCamelCase : Dict = None return input_points, input_labels, input_boxes @property def _snake_case ( self: Optional[Any] ): __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(a ) ) def _snake_case ( self: str , *a: Any , **a: Tuple ): return self.image_processor.post_process_masks(*a , **a )
669
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
1
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint lowercase_ = { '169M': 1_2, '430M': 2_4, '1B5': 2_4, '3B': 3_2, '7B': 3_2, '14B': 4_0, } lowercase_ = { '169M': 7_6_8, '430M': 1_0_2_4, '1B5': 2_0_4_8, '3B': 2_5_6_0, '7B': 4_0_9_6, '14B': 5_1_2_0, } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = list(state_dict.keys() ) for name in state_dict_keys: __lowerCamelCase : Tuple = state_dict.pop(SCREAMING_SNAKE_CASE__ ) # emb -> embedding if name.startswith('emb.' ): __lowerCamelCase : List[Any] = name.replace('emb.' , 'embeddings.' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0' ): __lowerCamelCase : Optional[Any] = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln' ) # att -> attention __lowerCamelCase : Tuple = re.sub(r'blocks\.(\d+)\.att' , r'blocks.\1.attention' , SCREAMING_SNAKE_CASE__ ) # ffn -> feed_forward __lowerCamelCase : Union[str, Any] = re.sub(r'blocks\.(\d+)\.ffn' , r'blocks.\1.feed_forward' , SCREAMING_SNAKE_CASE__ ) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k' ): __lowerCamelCase : int = name.replace('.time_mix_k' , '.time_mix_key' ) # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v' ): __lowerCamelCase : List[Any] = name.replace('.time_mix_v' , '.time_mix_value' ) # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r' ): __lowerCamelCase : List[str] = name.replace('.time_mix_r' , '.time_mix_receptance' ) if name != "head.weight": __lowerCamelCase : Dict = 'rwkv.' + name __lowerCamelCase : Optional[Any] = weight return state_dict def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=None ): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.' ) __lowerCamelCase : Optional[int] = 50_277 __lowerCamelCase : int = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b' ) else: __lowerCamelCase : Optional[int] = PreTrainedTokenizerFast(tokenizer_file=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = len(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) # 2. Build the config __lowerCamelCase : Dict = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: __lowerCamelCase : Dict = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.' ) if size not in possible_sizes: raise ValueError(f'`size` should be one of {possible_sizes}, got {size}.' ) __lowerCamelCase : str = RwkvConfig( vocab_size=SCREAMING_SNAKE_CASE__ , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(SCREAMING_SNAKE_CASE__ ) # 3. Download model file then convert state_dict __lowerCamelCase : int = hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = torch.load(SCREAMING_SNAKE_CASE__ , map_location='cpu' ) __lowerCamelCase : Any = convert_state_dict(SCREAMING_SNAKE_CASE__ ) # 4. Split in shards and save __lowerCamelCase , __lowerCamelCase : List[Any] = shard_checkpoint(SCREAMING_SNAKE_CASE__ ) for shard_file, shard in shards.items(): torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if index is not None: __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save the index as well with open(SCREAMING_SNAKE_CASE__ , 'w' , encoding='utf-8' ) as f: __lowerCamelCase : List[Any] = json.dumps(SCREAMING_SNAKE_CASE__ , indent=2 , sort_keys=SCREAMING_SNAKE_CASE__ ) + '\n' f.write(SCREAMING_SNAKE_CASE__ ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.' ) __lowerCamelCase : Dict = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: __lowerCamelCase : List[Any] = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.' ) __lowerCamelCase : List[str] = AutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ ) model.push_to_hub(SCREAMING_SNAKE_CASE__ , max_shard_size='2GB' ) tokenizer.push_to_hub(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) lowercase_ = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
669
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : Any = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(a ) conf_scores.append(a ) return dec_strs, conf_scores def _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
1
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class A_ : '''simple docstring''' __snake_case = 42 __snake_case = None __snake_case = None lowercase_ = namedtuple('CoinsDistribResult', 'moves excess') def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if root is None: return 0 # Validation def count_nodes(SCREAMING_SNAKE_CASE__ ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(SCREAMING_SNAKE_CASE__ ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(SCREAMING_SNAKE_CASE__ ) != count_coins(SCREAMING_SNAKE_CASE__ ): raise ValueError('The nodes number should be same as the number of coins' ) # Main calculation def get_distrib(SCREAMING_SNAKE_CASE__ ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) __lowerCamelCase , __lowerCamelCase : Any = get_distrib(node.left ) __lowerCamelCase , __lowerCamelCase : Any = get_distrib(node.right ) __lowerCamelCase : List[Any] = 1 - left_distrib_excess __lowerCamelCase : Union[str, Any] = 1 - right_distrib_excess __lowerCamelCase : Union[str, Any] = ( left_distrib_moves + right_distrib_moves + abs(SCREAMING_SNAKE_CASE__ ) + abs(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Tuple = node.data - coins_to_left - coins_to_right return CoinsDistribResult(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return get_distrib(SCREAMING_SNAKE_CASE__ )[0] if __name__ == "__main__": import doctest doctest.testmod()
669
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin lowercase_ = False @skip_mps class A_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = StableDiffusionAttendAndExcitePipeline __snake_case = False __snake_case = TEXT_TO_IMAGE_PARAMS __snake_case = TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""} ) __snake_case = TEXT_TO_IMAGE_IMAGE_PARAMS __snake_case = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def _snake_case ( cls: Tuple ): super().setUpClass() torch.use_deterministic_algorithms(a ) @classmethod def _snake_case ( cls: List[Any] ): super().tearDownClass() torch.use_deterministic_algorithms(a ) def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) __lowerCamelCase : str = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) torch.manual_seed(0 ) __lowerCamelCase : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __lowerCamelCase : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __lowerCamelCase : str = CLIPTextModel(a ) __lowerCamelCase : int = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __lowerCamelCase : Tuple = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def _snake_case ( self: Union[str, Any] , a: List[str] , a: str=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : Union[str, Any] = torch.manual_seed(a ) else: __lowerCamelCase : Optional[int] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Union[str, Any] = { 'prompt': 'a cat and a frog', 'token_indices': [2, 5], 'generator': generator, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', 'max_iter_to_alter': 2, 'thresholds': {0: 0.7}, } return inputs def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = 'cpu' __lowerCamelCase : int = self.get_dummy_components() __lowerCamelCase : Optional[int] = self.pipeline_class(**a ) pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : Union[str, Any] = pipe(**a ).images __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 64, 64, 3) ) __lowerCamelCase : str = np.array( [0.6_3_9_0_5_3_6_4, 0.6_2_8_9_7_3_0_7, 0.4_8_5_9_9_0_1_7, 0.5_1_3_3_6_2_4, 0.5_5_5_0_0_4_8, 0.4_5_7_6_9_5_1_6, 0.5_0_3_2_6_9_7_3, 0.5_0_2_3_1_3_9, 0.4_5_3_8_4_4_9_6] ) __lowerCamelCase : Dict = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a , 1e-3 ) def _snake_case ( self: List[Any] ): super().test_cpu_offload_forward_pass(expected_max_diff=5e-4 ) def _snake_case ( self: Any ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def _snake_case ( self: List[str] ): self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4 ) def _snake_case ( self: Tuple ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def _snake_case ( self: Optional[int] ): super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4 ) def _snake_case ( self: Optional[Any] ): super().test_save_load_local(expected_max_difference=5e-4 ) def _snake_case ( self: List[Any] ): super().test_save_load_optional_components(expected_max_difference=4e-4 ) @require_torch_gpu @slow class A_ ( unittest.TestCase ): '''simple docstring''' @classmethod def _snake_case ( cls: str ): super().setUpClass() torch.use_deterministic_algorithms(a ) @classmethod def _snake_case ( cls: List[str] ): super().tearDownClass() torch.use_deterministic_algorithms(a ) def _snake_case ( self: Dict ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: int ): __lowerCamelCase : List[str] = torch.manual_seed(51 ) __lowerCamelCase : int = StableDiffusionAttendAndExcitePipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , safety_checker=a , torch_dtype=torch.floataa ) pipe.to('cuda' ) __lowerCamelCase : Optional[Any] = 'a painting of an elephant with glasses' __lowerCamelCase : Dict = [5, 7] __lowerCamelCase : Tuple = pipe( prompt=a , token_indices=a , guidance_scale=7.5 , generator=a , num_inference_steps=5 , max_iter_to_alter=5 , output_type='numpy' , ).images[0] __lowerCamelCase : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy' ) assert np.abs((expected_image - image).max() ) < 5e-1
669
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = 50_000_000 ): __lowerCamelCase : Dict = set() __lowerCamelCase : Union[str, Any] = int((limit - 24) ** (1 / 2) ) __lowerCamelCase : List[Any] = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , SCREAMING_SNAKE_CASE__ ) ) ) for primea in primes: __lowerCamelCase : Tuple = primea * primea for primea in primes: __lowerCamelCase : Tuple = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: __lowerCamelCase : List[Any] = primea * primea * primea * primea __lowerCamelCase : int = square + cube + tetr if total >= limit: break ret.add(SCREAMING_SNAKE_CASE__ ) return len(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": print(F"""{solution() = }""")
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
1
import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor lowercase_ = logging.get_logger(__name__) class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: Any , *a: Union[str, Any] , **a: Dict ): warnings.warn( 'The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DonutImageProcessor instead.' , a , ) super().__init__(*a , **a )
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
1
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: lowercase_ = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class A_ ( unittest.TestCase ): '''simple docstring''' def __init__( self: Any , a: Optional[int] , a: str=7 , a: Dict=3 , a: str=18 , a: int=30 , a: int=400 , a: int=None , a: Optional[Any]=True , a: Any=True , a: int=None , ): __lowerCamelCase : Any = size if size is not None else {'height': 20, 'width': 20} __lowerCamelCase : Optional[int] = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : int = num_channels __lowerCamelCase : int = image_size __lowerCamelCase : List[Any] = min_resolution __lowerCamelCase : Optional[Any] = max_resolution __lowerCamelCase : List[Any] = size __lowerCamelCase : List[Any] = do_normalize __lowerCamelCase : Optional[Any] = do_convert_rgb __lowerCamelCase : List[str] = [512, 1024, 2048, 4096] __lowerCamelCase : Optional[Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def _snake_case ( self: List[Any] ): return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def _snake_case ( self: Dict ): __lowerCamelCase : Optional[int] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' __lowerCamelCase : Optional[int] = Image.open(requests.get(a , stream=a ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PixaStructImageProcessor if is_vision_available() else None def _snake_case ( self: Dict ): __lowerCamelCase : Tuple = PixaStructImageProcessingTester(self ) @property def _snake_case ( self: Tuple ): return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self: Optional[Any] ): __lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , 'do_normalize' ) ) self.assertTrue(hasattr(a , 'do_convert_rgb' ) ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Tuple = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase : Optional[int] = 2048 __lowerCamelCase : int = image_processor(a , return_tensors='pt' , max_patches=a ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0_6_0_6 ) , atol=1e-3 , rtol=1e-3 ) ) def _snake_case ( self: Any ): # Initialize image_processor __lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input __lowerCamelCase : int = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase : str = image_processor( a , return_tensors='pt' , max_patches=a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _snake_case ( self: int ): # Initialize image_processor __lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input __lowerCamelCase : Optional[int] = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase : List[Any] = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a ): __lowerCamelCase : Tuple = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a ).flattened_patches __lowerCamelCase : Optional[Any] = 'Hello' __lowerCamelCase : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a , header_text=a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase : Dict = image_processor( a , return_tensors='pt' , max_patches=a , header_text=a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _snake_case ( self: List[str] ): # Initialize image_processor __lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) __lowerCamelCase : Optional[int] = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase : Tuple = image_processor( a , return_tensors='pt' , max_patches=a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _snake_case ( self: List[Any] ): # Initialize image_processor __lowerCamelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input __lowerCamelCase : List[Any] = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase : int = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase : Any = image_processor( a , return_tensors='pt' , max_patches=a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PixaStructImageProcessor if is_vision_available() else None def _snake_case ( self: Dict ): __lowerCamelCase : Any = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase : Any = 3 @property def _snake_case ( self: Dict ): return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , 'do_normalize' ) ) self.assertTrue(hasattr(a , 'do_convert_rgb' ) ) def _snake_case ( self: int ): # Initialize image_processor __lowerCamelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input __lowerCamelCase : Optional[Any] = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase : List[str] = image_processor( a , return_tensors='pt' , max_patches=a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
669
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
1
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
1
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_video_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VivitImageProcessor class A_ ( unittest.TestCase ): '''simple docstring''' def __init__( self: Tuple , a: Dict , a: Any=7 , a: Optional[Any]=3 , a: Dict=10 , a: Optional[Any]=18 , a: List[Any]=30 , a: str=400 , a: Tuple=True , a: Union[str, Any]=None , a: Any=True , a: Union[str, Any]=[0.5, 0.5, 0.5] , a: Dict=[0.5, 0.5, 0.5] , a: Optional[int]=None , ): __lowerCamelCase : Dict = size if size is not None else {'shortest_edge': 18} __lowerCamelCase : Any = crop_size if crop_size is not None else {'height': 18, 'width': 18} __lowerCamelCase : int = parent __lowerCamelCase : str = batch_size __lowerCamelCase : Any = num_channels __lowerCamelCase : Optional[Any] = num_frames __lowerCamelCase : List[Any] = image_size __lowerCamelCase : Any = min_resolution __lowerCamelCase : Optional[Any] = max_resolution __lowerCamelCase : List[str] = do_resize __lowerCamelCase : List[str] = size __lowerCamelCase : Dict = do_normalize __lowerCamelCase : List[Any] = image_mean __lowerCamelCase : Dict = image_std __lowerCamelCase : List[Any] = crop_size def _snake_case ( self: Union[str, Any] ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = VivitImageProcessor if is_vision_available() else None def _snake_case ( self: List[str] ): __lowerCamelCase : str = VivitImageProcessingTester(self ) @property def _snake_case ( self: Any ): return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self: Optional[int] ): __lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , 'image_mean' ) ) self.assertTrue(hasattr(a , 'image_std' ) ) self.assertTrue(hasattr(a , 'do_normalize' ) ) self.assertTrue(hasattr(a , 'do_resize' ) ) self.assertTrue(hasattr(a , 'do_center_crop' ) ) self.assertTrue(hasattr(a , 'size' ) ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : List[str] = 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} ) __lowerCamelCase : List[Any] = 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 _snake_case ( self: int ): # Initialize image_processing __lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL videos __lowerCamelCase : Optional[int] = prepare_video_inputs(self.image_processor_tester , equal_resolution=a ) for video in video_inputs: self.assertIsInstance(a , a ) self.assertIsInstance(video[0] , Image.Image ) # Test not batched input __lowerCamelCase : int = image_processing(video_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __lowerCamelCase : Optional[int] = image_processing(a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def _snake_case ( self: Dict ): # Initialize image_processing __lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase : str = prepare_video_inputs(self.image_processor_tester , equal_resolution=a , numpify=a ) for video in video_inputs: self.assertIsInstance(a , a ) self.assertIsInstance(video[0] , np.ndarray ) # Test not batched input __lowerCamelCase : Optional[Any] = image_processing(video_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __lowerCamelCase : str = image_processing(a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def _snake_case ( self: List[str] ): # Initialize image_processing __lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase : Optional[int] = prepare_video_inputs(self.image_processor_tester , equal_resolution=a , torchify=a ) for video in video_inputs: self.assertIsInstance(a , a ) self.assertIsInstance(video[0] , torch.Tensor ) # Test not batched input __lowerCamelCase : Dict = image_processing(video_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __lowerCamelCase : List[Any] = image_processing(a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
669
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class A_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
1
from functools import lru_cache @lru_cache def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if num < 0: raise ValueError('Number should not be negative.' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if height >= 1: move_tower(height - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) move_disk(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) move_tower(height - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): print('moving disk from' , SCREAMING_SNAKE_CASE__ , 'to' , SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( ): __lowerCamelCase : Optional[int] = int(input('Height of hanoi: ' ).strip() ) move_tower(SCREAMING_SNAKE_CASE__ , 'A' , 'B' , 'C' ) if __name__ == "__main__": main()
669
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = 3 , SCREAMING_SNAKE_CASE__ = 7 , SCREAMING_SNAKE_CASE__ = 1_000_000 ): __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Union[str, Any] = 1 for current_denominator in range(1 , limit + 1 ): __lowerCamelCase : Any = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: __lowerCamelCase : List[Any] = current_numerator __lowerCamelCase : Optional[Any] = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_0_0_0_0_0_0))
669
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( 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 , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
1
from __future__ import annotations from typing import Generic, TypeVar lowercase_ = TypeVar('T') class A_ ( Generic[T] ): '''simple docstring''' def __init__( self: Tuple , a: T ): __lowerCamelCase : List[str] = data __lowerCamelCase : Dict = self __lowerCamelCase : Any = 0 class A_ ( Generic[T] ): '''simple docstring''' def __init__( self: int ): # map from node name to the node object __lowerCamelCase : dict[T, DisjointSetTreeNode[T]] = {} def _snake_case ( self: Union[str, Any] , a: T ): # create a new set with x as its member __lowerCamelCase : Union[str, Any] = DisjointSetTreeNode(a ) def _snake_case ( self: Dict , a: T ): # find the set x belongs to (with path-compression) __lowerCamelCase : Tuple = self.map[data] if elem_ref != elem_ref.parent: __lowerCamelCase : Tuple = self.find_set(elem_ref.parent.data ) return elem_ref.parent def _snake_case ( self: List[str] , a: DisjointSetTreeNode[T] , a: DisjointSetTreeNode[T] ): # helper function for union operation if nodea.rank > nodea.rank: __lowerCamelCase : List[str] = nodea else: __lowerCamelCase : List[str] = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def _snake_case ( self: List[Any] , a: T , a: T ): # merge 2 disjoint sets self.link(self.find_set(a ) , self.find_set(a ) ) class A_ ( Generic[T] ): '''simple docstring''' def __init__( self: Optional[int] ): # connections: map from the node to the neighbouring nodes (with weights) __lowerCamelCase : dict[T, dict[T, int]] = {} def _snake_case ( self: Optional[int] , a: T ): # add a node ONLY if its not present in the graph if node not in self.connections: __lowerCamelCase : List[str] = {} def _snake_case ( self: Tuple , a: T , a: T , a: int ): # add an edge with the given weight self.add_node(a ) self.add_node(a ) __lowerCamelCase : Dict = weight __lowerCamelCase : Tuple = weight def _snake_case ( self: str ): __lowerCamelCase : Tuple = [] __lowerCamelCase : int = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda a : x[2] ) # creating the disjoint set __lowerCamelCase : Dict = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(a ) # MST generation __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 __lowerCamelCase : Union[str, Any] = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : int = edges[index] index += 1 __lowerCamelCase : Dict = disjoint_set.find_set(a ) __lowerCamelCase : List[Any] = disjoint_set.find_set(a ) if parent_u != parent_v: num_edges += 1 graph.add_edge(a , a , a ) disjoint_set.union(a , a ) return graph
669
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
1
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A_ : '''simple docstring''' def __init__( self: Any , a: Optional[Any] , a: str=3 , a: List[str]=32 , a: List[Any]=3 , a: int=10 , a: Any=[10, 20, 30, 40] , a: Union[str, Any]=[1, 1, 2, 1] , a: List[str]=True , a: str=True , a: List[Any]="relu" , a: Tuple=3 , a: Dict=None , ): __lowerCamelCase : Any = parent __lowerCamelCase : List[Any] = batch_size __lowerCamelCase : Union[str, Any] = image_size __lowerCamelCase : List[Any] = num_channels __lowerCamelCase : Tuple = embeddings_size __lowerCamelCase : Dict = hidden_sizes __lowerCamelCase : int = depths __lowerCamelCase : str = is_training __lowerCamelCase : Dict = use_labels __lowerCamelCase : Union[str, Any] = hidden_act __lowerCamelCase : Tuple = num_labels __lowerCamelCase : str = scope __lowerCamelCase : Union[str, Any] = len(a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Optional[Any] = None if self.use_labels: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) __lowerCamelCase : Dict = self.get_config() return config, pixel_values, labels def _snake_case ( self: Optional[Any] ): return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _snake_case ( self: Optional[Any] , a: List[str] , a: Optional[int] , a: str ): __lowerCamelCase : Union[str, Any] = TFResNetModel(config=a ) __lowerCamelCase : str = 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: Any , a: str , a: Optional[Any] , a: Tuple ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : List[str] = TFResNetForImageClassification(a ) __lowerCamelCase : str = model(a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Any ): __lowerCamelCase : List[Any] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Union[str, Any] = config_and_inputs __lowerCamelCase : Tuple = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () __snake_case = ( {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: Dict ): __lowerCamelCase : str = TFResNetModelTester(self ) __lowerCamelCase : Tuple = ConfigTester(self , config_class=a , has_text_modality=a ) def _snake_case ( self: List[Any] ): 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[int] ): return @unittest.skip(reason='ResNet does not use inputs_embeds' ) def _snake_case ( self: str ): pass @unittest.skip(reason='ResNet does not support input and output embeddings' ) def _snake_case ( self: Union[str, Any] ): pass def _snake_case ( self: str ): __lowerCamelCase , __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Dict = model_class(a ) __lowerCamelCase : Dict = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase : Union[str, Any] = [*signature.parameters.keys()] __lowerCamelCase : List[str] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a ) def _snake_case ( self: Dict ): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _snake_case ( self: List[str] ): def check_hidden_states_output(a: Dict , a: int , a: Union[str, Any] ): __lowerCamelCase : List[Any] = model_class(a ) __lowerCamelCase : Dict = model(**self._prepare_for_class(a , a ) ) __lowerCamelCase : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __lowerCamelCase : List[Any] = self.model_tester.num_stages self.assertEqual(len(a ) , expected_num_stages + 1 ) # ResNet'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] , ) __lowerCamelCase , __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() __lowerCamelCase : Union[str, Any] = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: __lowerCamelCase : List[str] = layer_type __lowerCamelCase : Tuple = True check_hidden_states_output(a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCamelCase : Tuple = True check_hidden_states_output(a , a , a ) def _snake_case ( self: str ): __lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a ) @slow def _snake_case ( self: Optional[Any] ): for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : List[str] = TFResNetModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[Any] ): return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _snake_case ( self: Any ): __lowerCamelCase : Optional[int] = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __lowerCamelCase : int = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : Tuple = image_processor(images=a , return_tensors='tf' ) # forward pass __lowerCamelCase : List[Any] = model(**a ) # verify the logits __lowerCamelCase : Tuple = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a ) __lowerCamelCase : List[str] = tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1e-4 ) )
669
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
from __future__ import annotations class A_ : '''simple docstring''' def __init__( self: int , a: str , a: str ): __lowerCamelCase , __lowerCamelCase : Optional[int] = text, pattern __lowerCamelCase , __lowerCamelCase : Tuple = len(a ), len(a ) def _snake_case ( self: List[Any] , a: str ): for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def _snake_case ( self: List[str] , a: int ): for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def _snake_case ( self: str ): # searches pattern in text and returns index positions __lowerCamelCase : List[str] = [] for i in range(self.textLen - self.patLen + 1 ): __lowerCamelCase : List[str] = self.mismatch_in_text(a ) if mismatch_index == -1: positions.append(a ) else: __lowerCamelCase : List[str] = self.match_in_pattern(self.text[mismatch_index] ) __lowerCamelCase : List[str] = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions lowercase_ = 'ABAABA' lowercase_ = 'AB' lowercase_ = BoyerMooreSearch(text, pattern) lowercase_ = bms.bad_character_heuristic() if len(positions) == 0: print('No match found') else: print('Pattern found in following positions: ') print(positions)
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
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 lowercase_ = logging.get_logger(__name__) @dataclass class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self: Optional[int] , **a: List[Any] ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCamelCase : Optional[int] = 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 : List[str] = kwargs.pop('torchscript' , self.torchscript ) __lowerCamelCase : Any = kwargs.pop('torch_xla_tpu_print_metrics' , self.torch_xla_tpu_print_metrics ) __lowerCamelCase : Union[str, Any] = kwargs.pop('fp16_opt_level' , self.fpaa_opt_level ) super().__init__(**a ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """Trace the models using torchscript"""} ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """Print Xla/PyTorch tpu metrics"""} ) __snake_case = 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 _snake_case ( self: List[str] ): requires_backends(self , ['torch'] ) logger.info('PyTorch: setting up devices' ) if not self.cuda: __lowerCamelCase : int = torch.device('cpu' ) __lowerCamelCase : List[str] = 0 elif is_torch_tpu_available(): __lowerCamelCase : Dict = xm.xla_device() __lowerCamelCase : int = 0 else: __lowerCamelCase : str = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __lowerCamelCase : str = torch.cuda.device_count() return device, n_gpu @property def _snake_case ( self: Optional[int] ): return is_torch_tpu_available() and self.tpu @property def _snake_case ( self: Any ): requires_backends(self , ['torch'] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def _snake_case ( self: int ): requires_backends(self , ['torch'] ) return self._setup_devices[0] @property def _snake_case ( self: Dict ): requires_backends(self , ['torch'] ) return self._setup_devices[1] @property def _snake_case ( self: Tuple ): return self.n_gpu > 0
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: Optional[Any] , a: List[Any] , a: Union[str, Any]=None , a: Tuple=True , a: Optional[Any]=None , **a: List[str] ): __lowerCamelCase : Tuple = parent __lowerCamelCase : List[str] = config_class __lowerCamelCase : Tuple = has_text_modality __lowerCamelCase : Tuple = kwargs __lowerCamelCase : int = common_properties def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = self.config_class(**self.inputs_dict ) __lowerCamelCase : List[Any] = ( ['hidden_size', 'num_attention_heads', 'num_hidden_layers'] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(['vocab_size'] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(a , a ) , msg=F'`{prop}` does not exist' ) # Test that config has the common properties as setter for idx, name in enumerate(a ): try: setattr(a , a , a ) self.parent.assertEqual( getattr(a , a ) , a , msg=F'`{name} value {idx} expected, but was {getattr(a , a )}' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(a ): try: __lowerCamelCase : Dict = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(a , a ) , a , msg=F'`{name} value {idx} expected, but was {getattr(a , a )}' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _snake_case ( self: Any ): __lowerCamelCase : List[Any] = self.config_class(**self.inputs_dict ) __lowerCamelCase : int = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , a ) def _snake_case ( self: Any ): __lowerCamelCase : Tuple = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCamelCase : List[str] = os.path.join(a , 'config.json' ) config_first.to_json_file(a ) __lowerCamelCase : Tuple = self.config_class.from_json_file(a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _snake_case ( self: Tuple ): __lowerCamelCase : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(a ) __lowerCamelCase : Tuple = self.config_class.from_pretrained(a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _snake_case ( self: List[str] ): __lowerCamelCase : Any = self.config_class(**self.inputs_dict ) __lowerCamelCase : Any = 'test' with tempfile.TemporaryDirectory() as tmpdirname: __lowerCamelCase : List[str] = os.path.join(a , a ) config_first.save_pretrained(a ) __lowerCamelCase : List[Any] = self.config_class.from_pretrained(a , subfolder=a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _snake_case ( self: Optional[int] ): __lowerCamelCase : List[Any] = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) __lowerCamelCase : List[str] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _snake_case ( self: Optional[int] ): if self.config_class.is_composition: return __lowerCamelCase : Optional[Any] = self.config_class() self.parent.assertIsNotNone(a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : str = copy.deepcopy(a ) __lowerCamelCase : str = self.config_class(**a ) __lowerCamelCase : Union[str, Any] = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa) ) elif getattr(a , a ) != value: wrong_values.append((key, getattr(a , a ), value) ) if len(a ) > 0: __lowerCamelCase : str = '\n'.join([F'- {v[0]}: got {v[1]} instead of {v[2]}' for v in wrong_values] ) raise ValueError(F'The following keys were not properly set in the config:\n{errors}' ) def _snake_case ( self: str ): self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
669
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
from __future__ import annotations def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = [] __lowerCamelCase , __lowerCamelCase : int = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) __lowerCamelCase : Optional[int] = result + left + right return input_list def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if len(SCREAMING_SNAKE_CASE__ ) <= 1: return input_list __lowerCamelCase : Dict = list(SCREAMING_SNAKE_CASE__ ) # iteration for two-way merging __lowerCamelCase : Any = 2 while p <= len(SCREAMING_SNAKE_CASE__ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = i __lowerCamelCase : Optional[Any] = i + p - 1 __lowerCamelCase : List[Any] = (low + high + 1) // 2 __lowerCamelCase : List[str] = merge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # final merge of last two parts if p * 2 >= len(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = i __lowerCamelCase : Union[str, Any] = merge(SCREAMING_SNAKE_CASE__ , 0 , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": lowercase_ = input('Enter numbers separated by a comma:\n').strip() if user_input == "": lowercase_ = [] else: lowercase_ = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
669
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
1
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets lowercase_ = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n' lowercase_ = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n' lowercase_ = R'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self: Tuple ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' ), 'references': datasets.Value('string' ), } ) , homepage='https://github.com/hendrycks/math' , codebase_urls=['https://github.com/hendrycks/math'] , ) def _snake_case ( self: str , a: Optional[int] , a: Dict ): __lowerCamelCase : List[Any] = 0.0 for i, j in zip(a , a ): n_correct += 1.0 if math_equivalence.is_equiv(a , a ) else 0.0 __lowerCamelCase : str = n_correct / len(a ) return { "accuracy": accuracy, }
669
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
1
# Function to print upper half of diamond (pyramid) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i in range(0 , SCREAMING_SNAKE_CASE__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i in range(SCREAMING_SNAKE_CASE__ , 0 , -1 ): for _ in range(SCREAMING_SNAKE_CASE__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if n <= 0: print(' ... .... nothing printing :(' ) return floyd(SCREAMING_SNAKE_CASE__ ) # upper half reverse_floyd(SCREAMING_SNAKE_CASE__ ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') lowercase_ = 1 while K: lowercase_ = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) lowercase_ = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
669
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
1
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A_ : '''simple docstring''' def __init__( self: Any , a: Union[str, Any] , a: Any=13 , a: str=32 , a: int=3 , a: List[Any]=4 , a: Optional[Any]=[10, 20, 30, 40] , a: Any=[2, 2, 3, 2] , a: Dict=True , a: int=True , a: Any=37 , a: Any="gelu" , a: int=10 , a: List[str]=0.0_2 , a: Dict=["stage2", "stage3", "stage4"] , a: Optional[Any]=3 , a: Optional[int]=None , ): __lowerCamelCase : Optional[Any] = parent __lowerCamelCase : List[str] = batch_size __lowerCamelCase : str = image_size __lowerCamelCase : str = num_channels __lowerCamelCase : Optional[Any] = num_stages __lowerCamelCase : Any = hidden_sizes __lowerCamelCase : List[str] = depths __lowerCamelCase : Optional[Any] = is_training __lowerCamelCase : Any = use_labels __lowerCamelCase : Optional[int] = intermediate_size __lowerCamelCase : Optional[Any] = hidden_act __lowerCamelCase : Any = type_sequence_label_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Dict = out_features __lowerCamelCase : int = num_labels __lowerCamelCase : Dict = scope __lowerCamelCase : List[str] = num_stages def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Optional[int] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Tuple = self.get_config() return config, pixel_values, labels def _snake_case ( self: List[Any] ): return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def _snake_case ( self: List[Any] ): return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=a , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=a , loss_ignore_index=255 , num_labels=self.num_labels , ) def _snake_case ( self: Optional[int] , a: List[Any] , a: Optional[Any] , a: int ): __lowerCamelCase : Optional[int] = UperNetForSemanticSegmentation(config=a ) model.to(a ) model.eval() __lowerCamelCase : str = model(a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = config_and_inputs __lowerCamelCase : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = (UperNetForSemanticSegmentation,) if is_torch_available() else () __snake_case = {"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {} __snake_case = False __snake_case = False __snake_case = False __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: Any ): __lowerCamelCase : List[str] = UperNetModelTester(self ) __lowerCamelCase : Optional[Any] = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37 ) def _snake_case ( self: List[str] ): 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: Union[str, Any] ): return def _snake_case ( self: Optional[Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : List[Any] = model_class(a ) __lowerCamelCase : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase : int = [*signature.parameters.keys()] __lowerCamelCase : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*a ) @unittest.skip(reason='UperNet does not use inputs_embeds' ) def _snake_case ( self: List[Any] ): pass @unittest.skip(reason='UperNet does not support input and output embeddings' ) def _snake_case ( self: Tuple ): pass @unittest.skip(reason='UperNet does not have a base model' ) def _snake_case ( self: Optional[Any] ): pass @unittest.skip(reason='UperNet does not have a base model' ) def _snake_case ( self: str ): pass @require_torch_multi_gpu @unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _snake_case ( self: Tuple ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _snake_case ( self: List[str] ): pass def _snake_case ( self: List[Any] ): def check_hidden_states_output(a: Optional[Any] , a: int , a: Optional[Any] ): __lowerCamelCase : Optional[int] = model_class(a ) model.to(a ) model.eval() with torch.no_grad(): __lowerCamelCase : int = model(**self._prepare_for_class(a , a ) ) __lowerCamelCase : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __lowerCamelCase : List[Any] = self.model_tester.num_stages self.assertEqual(len(a ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __lowerCamelCase , __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = True check_hidden_states_output(a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCamelCase : int = True check_hidden_states_output(a , a , a ) def _snake_case ( self: Any ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCamelCase : List[Any] = _config_zero_init(a ) __lowerCamelCase : Dict = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: __lowerCamelCase : Any = model_class(config=a ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip(reason='UperNet does not have tied weights' ) def _snake_case ( self: List[Any] ): pass @slow def _snake_case ( self: Dict ): for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Optional[Any] = UperNetForSemanticSegmentation.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : Any = hf_hub_download( repo_id='hf-internal-testing/fixtures_ade20k' , repo_type='dataset' , filename='ADE_val_00000001.jpg' ) __lowerCamelCase : Dict = Image.open(SCREAMING_SNAKE_CASE__ ).convert('RGB' ) return image @require_torch @require_vision @slow class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: str ): __lowerCamelCase : str = AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny' ) __lowerCamelCase : Tuple = UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny' ).to(a ) __lowerCamelCase : Union[str, Any] = prepare_img() __lowerCamelCase : int = processor(images=a , return_tensors='pt' ).to(a ) with torch.no_grad(): __lowerCamelCase : List[str] = model(**a ) __lowerCamelCase : str = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , a ) __lowerCamelCase : Any = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(a ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , a , atol=1e-4 ) ) def _snake_case ( self: Dict ): __lowerCamelCase : str = AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny' ) __lowerCamelCase : Optional[int] = UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny' ).to(a ) __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : List[Any] = processor(images=a , return_tensors='pt' ).to(a ) with torch.no_grad(): __lowerCamelCase : List[Any] = model(**a ) __lowerCamelCase : Tuple = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , a ) __lowerCamelCase : Tuple = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(a ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , a , atol=1e-4 ) )
669
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
1
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 A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = 42 class A_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' @register_to_config def __init__( self: Any , a: int = 3 , a: int = 3 , a: Tuple[str] = ("DownEncoderBlock2D",) , a: Tuple[str] = ("UpDecoderBlock2D",) , a: Tuple[int] = (64,) , a: int = 1 , a: str = "silu" , a: int = 3 , a: int = 32 , a: int = 256 , a: int = 32 , a: Optional[int] = None , a: float = 0.1_8_2_1_5 , a: str = "group" , ): super().__init__() # pass init params to Encoder __lowerCamelCase : List[str] = Encoder( in_channels=a , out_channels=a , down_block_types=a , block_out_channels=a , layers_per_block=a , act_fn=a , norm_num_groups=a , double_z=a , ) __lowerCamelCase : Any = vq_embed_dim if vq_embed_dim is not None else latent_channels __lowerCamelCase : Tuple = nn.Convad(a , a , 1 ) __lowerCamelCase : int = VectorQuantizer(a , a , beta=0.2_5 , remap=a , sane_index_shape=a ) __lowerCamelCase : Any = nn.Convad(a , a , 1 ) # pass init params to Decoder __lowerCamelCase : List[Any] = Decoder( in_channels=a , out_channels=a , up_block_types=a , block_out_channels=a , layers_per_block=a , act_fn=a , norm_num_groups=a , norm_type=a , ) @apply_forward_hook def _snake_case ( self: Tuple , a: torch.FloatTensor , a: bool = True ): __lowerCamelCase : int = self.encoder(a ) __lowerCamelCase : Optional[Any] = self.quant_conv(a ) if not return_dict: return (h,) return VQEncoderOutput(latents=a ) @apply_forward_hook def _snake_case ( self: List[str] , a: torch.FloatTensor , a: bool = False , a: bool = True ): # also go through quantization layer if not force_not_quantize: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = self.quantize(a ) else: __lowerCamelCase : str = h __lowerCamelCase : Any = self.post_quant_conv(a ) __lowerCamelCase : Any = self.decoder(a , quant if self.config.norm_type == 'spatial' else None ) if not return_dict: return (dec,) return DecoderOutput(sample=a ) def _snake_case ( self: Optional[int] , a: torch.FloatTensor , a: bool = True ): __lowerCamelCase : Dict = sample __lowerCamelCase : Union[str, Any] = self.encode(a ).latents __lowerCamelCase : Dict = self.decode(a ).sample if not return_dict: return (dec,) return DecoderOutput(sample=a )
669
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
1
import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/spiece.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = AlbertTokenizer __snake_case = AlbertTokenizerFast __snake_case = True __snake_case = True __snake_case = True def _snake_case ( self: Dict ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[Any] = AlbertTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self: Any , a: Optional[Any] ): __lowerCamelCase : int = 'this is a test' __lowerCamelCase : str = 'this is a test' return input_text, output_text def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = '<pad>' __lowerCamelCase : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '▁eloquent' ) self.assertEqual(len(a ) , 3_0000 ) def _snake_case ( self: str ): self.assertEqual(self.get_tokenizer().vocab_size , 3_0000 ) def _snake_case ( self: List[Any] ): if not self.test_rust_tokenizer: return __lowerCamelCase : List[Any] = self.get_tokenizer() __lowerCamelCase : Dict = self.get_rust_tokenizer() __lowerCamelCase : List[str] = 'I was born in 92000, and this is falsé.' __lowerCamelCase : Optional[Any] = tokenizer.tokenize(a ) __lowerCamelCase : List[str] = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : str = tokenizer.encode(a , add_special_tokens=a ) __lowerCamelCase : List[Any] = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) __lowerCamelCase : Any = self.get_rust_tokenizer() __lowerCamelCase : Optional[Any] = tokenizer.encode(a ) __lowerCamelCase : List[Any] = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = AlbertTokenizer(a , keep_accents=a ) __lowerCamelCase : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(a , ['▁this', '▁is', '▁a', '▁test'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , [48, 25, 21, 1289] ) __lowerCamelCase : Any = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( a , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.'] ) __lowerCamelCase : List[Any] = tokenizer.convert_tokens_to_ids(a ) self.assertListEqual(a , [31, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] ) __lowerCamelCase : Any = tokenizer.convert_ids_to_tokens(a ) self.assertListEqual( a , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.'] , ) def _snake_case ( self: Any ): __lowerCamelCase : int = AlbertTokenizer(a ) __lowerCamelCase : Union[str, Any] = tokenizer.encode('sequence builders' ) __lowerCamelCase : List[Any] = tokenizer.encode('multi-sequence build' ) __lowerCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(a ) __lowerCamelCase : Optional[Any] = tokenizer.build_inputs_with_special_tokens(a , a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def _snake_case ( self: str ): # fmt: off __lowerCamelCase : Tuple = {'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'input_ids': [[2, 2_1970, 13, 5, 6092, 167, 28, 7103, 2153, 673, 8, 7028, 1_2051, 18, 17, 7103, 2153, 673, 8, 3515, 1_8684, 8, 4461, 6, 1927, 297, 8, 1_2060, 2607, 18, 13, 5, 4461, 15, 1_0538, 38, 8, 135, 15, 822, 58, 15, 993, 1_0363, 15, 1460, 8005, 4461, 15, 993, 255, 2328, 9, 9, 9, 6, 26, 1112, 816, 3260, 13, 5, 103, 2377, 6, 17, 1112, 816, 2782, 13, 5, 103, 1_0641, 6, 29, 84, 2512, 2430, 782, 1_8684, 2761, 19, 808, 2430, 2556, 17, 855, 1480, 9477, 4091, 128, 1_1712, 15, 7103, 2153, 673, 17, 2_4883, 9990, 9, 3], [2, 1_1502, 25, 1006, 20, 782, 8, 1_1809, 855, 1732, 1_9393, 1_8667, 37, 367, 2_1018, 69, 1854, 34, 1_1860, 1_9124, 27, 156, 225, 17, 193, 4141, 19, 65, 9124, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 2231, 886, 2385, 1_7659, 84, 14, 1_6792, 1952, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='albert-base-v2' , revision='6b6560eaf5ff2e250b00c50f380c5389a9c2d82e' , )
669
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : Any = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(a ) conf_scores.append(a ) return dec_strs, conf_scores def _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer lowercase_ = logging.get_logger(__name__) lowercase_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} lowercase_ = { 'vocab_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt' ), 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt' ), 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json' ), 'bert-base-multilingual-cased': ( 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json' ), 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-cased': ( 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json' ), }, } lowercase_ = { 'bert-base-uncased': 5_1_2, 'bert-large-uncased': 5_1_2, 'bert-base-cased': 5_1_2, 'bert-large-cased': 5_1_2, 'bert-base-multilingual-uncased': 5_1_2, 'bert-base-multilingual-cased': 5_1_2, 'bert-base-chinese': 5_1_2, 'bert-base-german-cased': 5_1_2, 'bert-large-uncased-whole-word-masking': 5_1_2, 'bert-large-cased-whole-word-masking': 5_1_2, 'bert-large-uncased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-large-cased-whole-word-masking-finetuned-squad': 5_1_2, 'bert-base-cased-finetuned-mrpc': 5_1_2, 'bert-base-german-dbmdz-cased': 5_1_2, 'bert-base-german-dbmdz-uncased': 5_1_2, 'TurkuNLP/bert-base-finnish-cased-v1': 5_1_2, 'TurkuNLP/bert-base-finnish-uncased-v1': 5_1_2, 'wietsedv/bert-base-dutch-cased': 5_1_2, } lowercase_ = { 'bert-base-uncased': {'do_lower_case': True}, 'bert-large-uncased': {'do_lower_case': True}, 'bert-base-cased': {'do_lower_case': False}, 'bert-large-cased': {'do_lower_case': False}, 'bert-base-multilingual-uncased': {'do_lower_case': True}, 'bert-base-multilingual-cased': {'do_lower_case': False}, 'bert-base-chinese': {'do_lower_case': False}, 'bert-base-german-cased': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False}, 'bert-base-cased-finetuned-mrpc': {'do_lower_case': False}, 'bert-base-german-dbmdz-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-uncased': {'do_lower_case': True}, 'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False}, 'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True}, 'wietsedv/bert-base-dutch-cased': {'do_lower_case': False}, } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = BertTokenizer def __init__( self: int , a: str=None , a: List[str]=None , a: Tuple=True , a: int="[UNK]" , a: str="[SEP]" , a: int="[PAD]" , a: List[str]="[CLS]" , a: Optional[Any]="[MASK]" , a: Optional[int]=True , a: List[str]=None , **a: int , ): super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) __lowerCamelCase : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , a ) != do_lower_case or normalizer_state.get('strip_accents' , a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , a ) != tokenize_chinese_chars ): __lowerCamelCase : List[str] = getattr(a , normalizer_state.pop('type' ) ) __lowerCamelCase : Union[str, Any] = do_lower_case __lowerCamelCase : List[Any] = strip_accents __lowerCamelCase : int = tokenize_chinese_chars __lowerCamelCase : Any = normalizer_class(**a ) __lowerCamelCase : str = do_lower_case def _snake_case ( self: Optional[Any] , a: Dict , a: List[Any]=None ): __lowerCamelCase : Optional[int] = [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 _snake_case ( self: Tuple , a: List[int] , a: Optional[List[int]] = None ): __lowerCamelCase : List[Any] = [self.sep_token_id] __lowerCamelCase : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self: Dict , a: str , a: Optional[str] = None ): __lowerCamelCase : List[str] = self._tokenizer.model.save(a , name=a ) return tuple(a )
669
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
1
from __future__ import annotations def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if not nums: raise ValueError('List is empty' ) return sum(SCREAMING_SNAKE_CASE__ ) / len(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
669
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
1
from ..utils import DummyObject, requires_backends class A_ ( metaclass=__UpperCamelCase ): '''simple docstring''' __snake_case = ["""torch""", """transformers""", """onnx"""] def __init__( self: str , *a: int , **a: List[Any] ): requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: int , *a: Tuple , **a: Any ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: List[Any] , *a: Optional[int] , **a: Any ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class A_ ( metaclass=__UpperCamelCase ): '''simple docstring''' __snake_case = ["""torch""", """transformers""", """onnx"""] def __init__( self: Union[str, Any] , *a: Any , **a: Optional[int] ): requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: Tuple , *a: Dict , **a: Dict ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: Union[str, Any] , *a: str , **a: str ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class A_ ( metaclass=__UpperCamelCase ): '''simple docstring''' __snake_case = ["""torch""", """transformers""", """onnx"""] def __init__( self: str , *a: Union[str, Any] , **a: Union[str, Any] ): requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: Union[str, Any] , *a: Union[str, Any] , **a: Optional[Any] ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: Optional[int] , *a: Dict , **a: Union[str, Any] ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class A_ ( metaclass=__UpperCamelCase ): '''simple docstring''' __snake_case = ["""torch""", """transformers""", """onnx"""] def __init__( self: str , *a: int , **a: Tuple ): requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: List[str] , *a: Any , **a: str ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: List[Any] , *a: int , **a: Union[str, Any] ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class A_ ( metaclass=__UpperCamelCase ): '''simple docstring''' __snake_case = ["""torch""", """transformers""", """onnx"""] def __init__( self: Union[str, Any] , *a: int , **a: int ): requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: Optional[int] , *a: Tuple , **a: Tuple ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: Tuple , *a: List[Any] , **a: int ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class A_ ( metaclass=__UpperCamelCase ): '''simple docstring''' __snake_case = ["""torch""", """transformers""", """onnx"""] def __init__( self: Union[str, Any] , *a: Union[str, Any] , **a: Optional[Any] ): requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: Tuple , *a: List[Any] , **a: Tuple ): requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def _snake_case ( cls: int , *a: Optional[int] , **a: Union[str, Any] ): requires_backends(cls , ['torch', 'transformers', 'onnx'] )
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
1
from collections.abc import Generator def UpperCamelCase__ ( ): __lowerCamelCase , __lowerCamelCase : Dict = 0, 1 while True: __lowerCamelCase , __lowerCamelCase : List[str] = b, a + b yield b def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = 1_000 ): __lowerCamelCase : List[str] = 1 __lowerCamelCase : Tuple = fibonacci_generator() while len(str(next(SCREAMING_SNAKE_CASE__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
1
from __future__ import annotations lowercase_ = 'Muhammad Umer Farooq' lowercase_ = 'MIT' lowercase_ = '1.0.0' lowercase_ = 'Muhammad Umer Farooq' lowercase_ = 'contact@muhammadumerfarooq.me' lowercase_ = 'Alpha' import re from html.parser import HTMLParser from urllib import parse import requests class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: Optional[Any] , a: str ): super().__init__() __lowerCamelCase : list[str] = [] __lowerCamelCase : Any = domain def _snake_case ( self: Optional[Any] , a: str , a: list[tuple[str, str | None]] ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __lowerCamelCase : int = parse.urljoin(self.domain , a ) self.urls.append(a ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return ".".join(get_sub_domain_name(SCREAMING_SNAKE_CASE__ ).split('.' )[-2:] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return parse.urlparse(SCREAMING_SNAKE_CASE__ ).netloc def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = "https://github.com" ): __lowerCamelCase : Optional[int] = get_domain_name(SCREAMING_SNAKE_CASE__ ) # Initialize the parser __lowerCamelCase : str = Parser(SCREAMING_SNAKE_CASE__ ) try: # Open URL __lowerCamelCase : List[Any] = requests.get(SCREAMING_SNAKE_CASE__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __lowerCamelCase : str = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __lowerCamelCase : str = requests.get(SCREAMING_SNAKE_CASE__ ) # Get the valid email. __lowerCamelCase : str = re.findall('[a-zA-Z0-9]+@' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(SCREAMING_SNAKE_CASE__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = emails_from_url('https://github.com') print(F"""{len(emails)} emails found:""") print('\n'.join(sorted(emails)))
669
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
1
# 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 lowercase_ = 'Create a default config file for Accelerate with only a few flags set.' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__="no" , SCREAMING_SNAKE_CASE__ = default_json_config_file , SCREAMING_SNAKE_CASE__ = False ): __lowerCamelCase : Dict = Path(SCREAMING_SNAKE_CASE__ ) path.parent.mkdir(parents=SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) 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 __lowerCamelCase : Optional[Any] = 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}' ) __lowerCamelCase : Optional[int] = { 'compute_environment': 'LOCAL_MACHINE', 'mixed_precision': mixed_precision, } if torch.cuda.is_available(): __lowerCamelCase : Union[str, Any] = torch.cuda.device_count() __lowerCamelCase : Optional[Any] = num_gpus __lowerCamelCase : List[str] = False if num_gpus > 1: __lowerCamelCase : List[str] = 'MULTI_GPU' else: __lowerCamelCase : List[Any] = 'NO' elif is_xpu_available() and use_xpu: __lowerCamelCase : int = torch.xpu.device_count() __lowerCamelCase : Dict = num_xpus __lowerCamelCase : Optional[int] = False if num_xpus > 1: __lowerCamelCase : Dict = 'MULTI_XPU' else: __lowerCamelCase : Tuple = 'NO' elif is_npu_available(): __lowerCamelCase : Tuple = torch.npu.device_count() __lowerCamelCase : List[Any] = num_npus __lowerCamelCase : Optional[Any] = False if num_npus > 1: __lowerCamelCase : Any = 'MULTI_NPU' else: __lowerCamelCase : List[Any] = 'NO' else: __lowerCamelCase : Optional[Any] = 0 __lowerCamelCase : Optional[Any] = True __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : str = 'NO' __lowerCamelCase : int = ClusterConfig(**SCREAMING_SNAKE_CASE__ ) config.to_json_file(SCREAMING_SNAKE_CASE__ ) return path def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = parser.add_parser('default' , parents=SCREAMING_SNAKE_CASE__ , help=SCREAMING_SNAKE_CASE__ , formatter_class=SCREAMING_SNAKE_CASE__ ) parser.add_argument( '--config_file' , default=SCREAMING_SNAKE_CASE__ , 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=SCREAMING_SNAKE_CASE__ , 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=SCREAMING_SNAKE_CASE__ ) return parser def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f'accelerate configuration saved at {config_file}' )
669
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
1
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 A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = 42 __snake_case = 42 def __init__( self: Any , a: UNetaDModel , a: ScoreSdeVeScheduler ): super().__init__() self.register_modules(unet=a , scheduler=a ) @torch.no_grad() def __call__( self: Optional[int] , a: int = 1 , a: int = 2000 , a: Optional[Union[torch.Generator, List[torch.Generator]]] = None , a: Optional[str] = "pil" , a: bool = True , **a: Any , ): __lowerCamelCase : int = self.unet.config.sample_size __lowerCamelCase : int = (batch_size, 3, img_size, img_size) __lowerCamelCase : List[Any] = self.unet __lowerCamelCase : int = randn_tensor(a , generator=a ) * self.scheduler.init_noise_sigma __lowerCamelCase : int = 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 ) ): __lowerCamelCase : Dict = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): __lowerCamelCase : Union[str, Any] = self.unet(a , a ).sample __lowerCamelCase : Optional[int] = self.scheduler.step_correct(a , a , generator=a ).prev_sample # prediction step __lowerCamelCase : List[str] = model(a , a ).sample __lowerCamelCase : List[Any] = self.scheduler.step_pred(a , a , a , generator=a ) __lowerCamelCase , __lowerCamelCase : List[Any] = output.prev_sample, output.prev_sample_mean __lowerCamelCase : int = sample_mean.clamp(0 , 1 ) __lowerCamelCase : Union[str, Any] = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __lowerCamelCase : Union[str, Any] = self.numpy_to_pil(a ) if not return_dict: return (sample,) return ImagePipelineOutput(images=a )
669
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class A_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
1
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: Any , a: AutoencoderKL , a: CLIPTextModel , a: CLIPTokenizer , a: UNetaDConditionModel , a: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , a: StableDiffusionSafetyChecker , a: CLIPImageProcessor , ): super().__init__() self.register_modules( vae=a , text_encoder=a , tokenizer=a , unet=a , scheduler=a , safety_checker=a , feature_extractor=a , ) def _snake_case ( self: List[str] , a: Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __lowerCamelCase : List[str] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(a ) def _snake_case ( self: Optional[int] ): self.enable_attention_slicing(a ) @torch.no_grad() def __call__( self: Any , a: Union[str, List[str]] , a: int = 512 , a: int = 512 , a: int = 50 , a: float = 7.5 , a: Optional[Union[str, List[str]]] = None , a: Optional[int] = 1 , a: float = 0.0 , a: Optional[torch.Generator] = None , a: Optional[torch.FloatTensor] = None , a: Optional[str] = "pil" , a: bool = True , a: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , a: int = 1 , a: Optional[torch.FloatTensor] = None , **a: Union[str, Any] , ): if isinstance(a , a ): __lowerCamelCase : str = 1 elif isinstance(a , a ): __lowerCamelCase : Union[str, Any] = len(a ) else: raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(a )}' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(a , a ) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(a )}.' ) # get prompt text embeddings __lowerCamelCase : Any = self.tokenizer( a , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) __lowerCamelCase : Optional[int] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __lowerCamelCase : List[str] = 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 : Optional[int] = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: __lowerCamelCase : Optional[Any] = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : int = text_embeddings.shape __lowerCamelCase : Optional[Any] = text_embeddings.repeat(1 , a , 1 ) __lowerCamelCase : Dict = text_embeddings.view(bs_embed * num_images_per_prompt , a , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __lowerCamelCase : Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __lowerCamelCase : List[str] if negative_prompt is None: __lowerCamelCase : Optional[int] = [''] elif type(a ) is not type(a ): raise TypeError( F'`negative_prompt` should be the same type to `prompt`, but got {type(a )} !=' F' {type(a )}.' ) elif isinstance(a , a ): __lowerCamelCase : List[str] = [negative_prompt] elif batch_size != len(a ): raise ValueError( F'`negative_prompt`: {negative_prompt} has batch size {len(a )}, but `prompt`:' F' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' ' the batch size of `prompt`.' ) else: __lowerCamelCase : Optional[Any] = negative_prompt __lowerCamelCase : Union[str, Any] = text_input_ids.shape[-1] __lowerCamelCase : List[Any] = self.tokenizer( a , padding='max_length' , max_length=a , truncation=a , return_tensors='pt' , ) __lowerCamelCase : str = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __lowerCamelCase : Optional[int] = uncond_embeddings.shape[1] __lowerCamelCase : List[str] = uncond_embeddings.repeat(a , a , 1 ) __lowerCamelCase : List[Any] = uncond_embeddings.view(batch_size * num_images_per_prompt , a , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __lowerCamelCase : Tuple = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. __lowerCamelCase : int = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) __lowerCamelCase : Tuple = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) __lowerCamelCase : List[Any] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps __lowerCamelCase : List[str] = torch.randn( a , generator=a , device='cpu' , dtype=a ).to(self.device ) __lowerCamelCase : Any = torch.randn(a , generator=a , device='cpu' , dtype=a ).to( self.device ) else: __lowerCamelCase : Union[str, Any] = torch.randn( a , generator=a , device=self.device , dtype=a ) __lowerCamelCase : Tuple = torch.randn(a , generator=a , device=self.device , dtype=a ) else: if latents_reference.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) __lowerCamelCase : Tuple = latents_reference.to(self.device ) __lowerCamelCase : str = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images __lowerCamelCase : Any = (latents_shape[3] - latents_shape_reference[3]) // 2 __lowerCamelCase : Optional[Any] = (latents_shape[2] - latents_shape_reference[2]) // 2 __lowerCamelCase : str = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx __lowerCamelCase : Dict = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy __lowerCamelCase : Any = 0 if dx < 0 else dx __lowerCamelCase : Optional[Any] = 0 if dy < 0 else dy __lowerCamelCase : Union[str, Any] = max(-dx , 0 ) __lowerCamelCase : Optional[int] = max(-dy , 0 ) # import pdb # pdb.set_trace() __lowerCamelCase : Any = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(a ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand __lowerCamelCase : Optional[int] = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __lowerCamelCase : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __lowerCamelCase : Union[str, Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __lowerCamelCase : Union[str, Any] = {} if accepts_eta: __lowerCamelCase : List[str] = eta for i, t in enumerate(self.progress_bar(a ) ): # expand the latents if we are doing classifier free guidance __lowerCamelCase : Optional[Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowerCamelCase : List[Any] = self.scheduler.scale_model_input(a , a ) # predict the noise residual __lowerCamelCase : Dict = self.unet(a , a , encoder_hidden_states=a ).sample # perform guidance if do_classifier_free_guidance: __lowerCamelCase , __lowerCamelCase : List[Any] = noise_pred.chunk(2 ) __lowerCamelCase : Any = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 __lowerCamelCase : Any = self.scheduler.step(a , a , a , **a ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(a , a , a ) __lowerCamelCase : Optional[Any] = 1 / 0.1_8_2_1_5 * latents __lowerCamelCase : List[Any] = self.vae.decode(a ).sample __lowerCamelCase : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __lowerCamelCase : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: __lowerCamelCase : List[Any] = self.feature_extractor(self.numpy_to_pil(a ) , return_tensors='pt' ).to( self.device ) __lowerCamelCase , __lowerCamelCase : str = self.safety_checker( images=a , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: __lowerCamelCase : Optional[int] = None if output_type == "pil": __lowerCamelCase : List[Any] = self.numpy_to_pil(a ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=a , nsfw_content_detected=a )
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = f'Input value of [number={number}] must be an integer' raise TypeError(SCREAMING_SNAKE_CASE__ ) if number < 1: __lowerCamelCase : Dict = f'Input value of [number={number}] must be > 0' raise ValueError(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = 1 for i in range(1 , SCREAMING_SNAKE_CASE__ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
669
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
1
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate lowercase_ = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('', '|', '|'), datarow=DataRow('', '|', '|'), padding=1, with_header_hide=None, ) lowercase_ = [] lowercase_ = [] lowercase_ = {'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}} lowercase_ = [ { 'type': 'header', 'text': { 'type': 'plain_text', 'text': F"""🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results""", 'emoji': True, }, } ] lowercase_ = 0 for log in Path().glob('*.log'): lowercase_ = 0 with open(log, 'r') as f: for line in f: lowercase_ = json.loads(line) if line.get('nodeid', '') != "": lowercase_ = line['nodeid'] if line.get('duration', None) is not None: lowercase_ = F"""{line['duration']:.4f}""" if line.get('outcome', '') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('_')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) lowercase_ = [] log.unlink() lowercase_ = '' lowercase_ = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += F"*{name[1:]}: {num_failed} failed test*\n" else: message += F"*{name[1:]}: {num_failed} failed tests*\n" lowercase_ = [] lowercase_ = {} for test in failed_tests: lowercase_ = test[0].split('::') lowercase_ = data[0].split('/')[-1] if data[0] not in filesafailed: lowercase_ = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) lowercase_ = [test[0] for test in failed_table] lowercase_ = list(set(files)) # Count number of instances in failed_tests lowercase_ = [] for file in individual_files: table.append([file, len(filesafailed[file])]) lowercase_ = tabulate( table, headers=['Test Location', 'Num Failed'], tablefmt=hf_table_format, stralign='right', ) message += F"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3_0_0_0: lowercase_ = 'Too many failed tests, please see the full report in the Action results.' lowercase_ = len(err) + 1_0 lowercase_ = message[: 3_0_0_0 - offset] + F"""\n...\n```\n{err}""" print(F"""### {message}""") else: lowercase_ = 'No failed tests! 🤗' print(F"""## {message}""") payload.append(no_error_payload) if os.environ.get('TEST_TYPE', '') != "": from slack_sdk import WebClient lowercase_ = WebClient(token=os.environ['SLACK_API_TOKEN']) if message != "No failed tests! 🤗": lowercase_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message, }, } payload.append(md_report) lowercase_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*For more details:*', }, 'accessory': { 'type': 'button', 'text': { 'type': 'plain_text', 'text': 'Check Action results', 'emoji': True, }, 'url': F"""https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}""", }, } payload.append(action_button) lowercase_ = { 'type': 'context', 'elements': [ { 'type': 'plain_text', 'text': F"""Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}""", } ], } payload.append(date_report) lowercase_ = client.chat_postMessage(channel='#accelerate-ci-daily', text=message, blocks=payload) lowercase_ = response.data['ts'] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name lowercase_ = '' for i, row in enumerate(test_failures): if row[0] != test_class: lowercase_ = row[0] else: lowercase_ = '' lowercase_ = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': F"""Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```""", }, } client.chat_postMessage( channel='#accelerate-ci-daily', thread_ts=ts, blocks=[payload], )
669
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( 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 , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
1
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : Any = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(a ) conf_scores.append(a ) return dec_strs, conf_scores def _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
1
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Dict , a: Tuple=99 , a: Any=13 , a: Tuple=7 , a: Optional[Any]=9 , a: Dict=True , a: List[Any]=True , a: Any=False , a: Optional[int]=32 , a: Optional[int]=5 , a: List[Any]=4 , a: int=37 , a: Union[str, Any]=8 , a: List[str]=0.1 , a: str=0.0_0_2 , a: str=1 , a: Union[str, Any]=0 , a: List[str]=0 , a: Optional[Any]=None , a: str=None , ): __lowerCamelCase : Optional[int] = parent __lowerCamelCase : int = batch_size __lowerCamelCase : Optional[Any] = encoder_seq_length __lowerCamelCase : List[Any] = decoder_seq_length # For common tests __lowerCamelCase : int = self.decoder_seq_length __lowerCamelCase : Union[str, Any] = is_training __lowerCamelCase : Optional[Any] = use_attention_mask __lowerCamelCase : Union[str, Any] = use_labels __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : str = hidden_size __lowerCamelCase : Any = num_hidden_layers __lowerCamelCase : Optional[int] = num_attention_heads __lowerCamelCase : List[str] = d_ff __lowerCamelCase : Any = relative_attention_num_buckets __lowerCamelCase : Any = dropout_rate __lowerCamelCase : List[str] = initializer_factor __lowerCamelCase : List[str] = eos_token_id __lowerCamelCase : List[Any] = pad_token_id __lowerCamelCase : Dict = decoder_start_token_id __lowerCamelCase : int = None __lowerCamelCase : Union[str, Any] = decoder_layers def _snake_case ( self: List[str] ): return TaConfig.from_pretrained('google/umt5-base' ) def _snake_case ( self: Dict , a: List[str] , a: int , a: List[Any] , a: Any=None , a: Dict=None , a: int=None , a: Tuple=None , a: int=None , ): if attention_mask is None: __lowerCamelCase : List[str] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __lowerCamelCase : Dict = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __lowerCamelCase : Optional[int] = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=a ) if decoder_head_mask is None: __lowerCamelCase : Optional[int] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=a ) if cross_attn_head_mask is None: __lowerCamelCase : Optional[Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=a ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def _snake_case ( self: Dict ): __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __lowerCamelCase : Optional[int] = input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase : str = decoder_input_ids.clamp(self.pad_token_id + 1 ) __lowerCamelCase : Optional[int] = self.get_config() __lowerCamelCase : Dict = config.num_attention_heads __lowerCamelCase : Union[str, Any] = self.prepare_inputs_dict(a , a , a ) return config, input_dict def _snake_case ( self: Any ): __lowerCamelCase , __lowerCamelCase : List[Any] = self.prepare_config_and_inputs() return config, inputs_dict def _snake_case ( self: List[Any] ): return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _snake_case ( self: Any ): return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _snake_case ( self: List[str] , a: List[Any] , a: List[Any] , a: Tuple , a: Tuple , a: str , a: int , ): __lowerCamelCase : List[Any] = UMTaModel(config=a ) model.to(a ) model.eval() __lowerCamelCase : int = model( input_ids=a , decoder_input_ids=a , attention_mask=a , decoder_attention_mask=a , ) __lowerCamelCase : Tuple = model(input_ids=a , decoder_input_ids=a ) __lowerCamelCase : Dict = result.last_hidden_state __lowerCamelCase : List[str] = result.past_key_values __lowerCamelCase : Union[str, Any] = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(a ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def _snake_case ( self: Optional[Any] , a: int , a: List[Any] , a: Dict , a: Optional[Any] , a: Any , a: int , ): __lowerCamelCase : str = UMTaModel(config=a ).get_decoder().to(a ).eval() # first forward pass __lowerCamelCase : Dict = model(a , use_cache=a ) __lowerCamelCase : int = model(a ) __lowerCamelCase : Optional[int] = model(a , use_cache=a ) self.parent.assertTrue(len(a ) == len(a ) ) self.parent.assertTrue(len(a ) == len(a ) + 1 ) __lowerCamelCase , __lowerCamelCase : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __lowerCamelCase : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __lowerCamelCase : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCamelCase : str = model(a )['last_hidden_state'] __lowerCamelCase : int = model(a , past_key_values=a )['last_hidden_state'] # select random slice __lowerCamelCase : Dict = ids_tensor((1,) , output_from_past.shape[-1] ).item() __lowerCamelCase : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() __lowerCamelCase : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1e-3 ) ) def _snake_case ( self: List[Any] , a: List[Any] , a: Dict , ): __lowerCamelCase : List[Any] = UMTaModel(config=a ).to(a ).half().eval() __lowerCamelCase : Optional[int] = model(**a )['last_hidden_state'] self.parent.assertFalse(torch.isnan(a ).any().item() ) @require_torch class A_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) __snake_case = (UMTaForConditionalGeneration,) if is_torch_available() else () __snake_case = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) __snake_case = True __snake_case = False __snake_case = False __snake_case = True __snake_case = True # The small UMT5 model needs higher percentages for CPU/MP tests __snake_case = [0.8, 0.9] def _snake_case ( self: int ): __lowerCamelCase : Optional[int] = UMTaModelTester(self ) @unittest.skip('Test has a segmentation fault on torch 1.8.0' ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() __lowerCamelCase : Union[str, Any] = UMTaModel(config_and_inputs[0] ).to(a ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F'{tmpdirname}/t5_test.onnx' , export_params=a , opset_version=9 , input_names=['input_ids', 'decoder_input_ids'] , ) @unittest.skipIf(torch_device == 'cpu' , 'Cant do half precision' ) def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*a ) def _snake_case ( self: str ): __lowerCamelCase : Any = ['encoder_attentions', 'decoder_attentions', 'cross_attentions'] __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() __lowerCamelCase : Any = config_and_inputs[0] __lowerCamelCase : List[Any] = UMTaForConditionalGeneration(a ).eval() model.to(a ) __lowerCamelCase : Tuple = { 'head_mask': torch.zeros(config.num_layers , config.num_heads , device=a ), 'decoder_head_mask': torch.zeros(config.num_decoder_layers , config.num_heads , device=a ), 'cross_attn_head_mask': torch.zeros(config.num_decoder_layers , config.num_heads , device=a ), } for attn_name, (name, mask) in zip(a , head_masking.items() ): __lowerCamelCase : Dict = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __lowerCamelCase : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_heads , device=a ) __lowerCamelCase : str = model.generate( config_and_inputs[1]['input_ids'] , num_beams=1 , max_length=3 , output_attentions=a , return_dict_in_generate=a , **a , ) # We check the state of decoder_attentions and cross_attentions just from the last step __lowerCamelCase : Dict = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('Does not work on the tiny model as we keep hitting edge cases.' ) def _snake_case ( self: Union[str, Any] ): pass @require_torch @require_sentencepiece @require_tokenizers class A_ ( unittest.TestCase ): '''simple docstring''' @slow @unittest.skip( 'Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged' ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : str = UMTaForConditionalGeneration.from_pretrained('google/umt5-small' , return_dict=a ).to(a ) __lowerCamelCase : Any = AutoTokenizer.from_pretrained('google/umt5-small' , use_fast=a , legacy=a ) __lowerCamelCase : Union[str, Any] = [ 'Bonjour monsieur <extra_id_0> bien <extra_id_1>.', 'No se como puedo <extra_id_0>.', 'This is the reason why we <extra_id_0> them.', 'The <extra_id_0> walks in <extra_id_1>, seats', 'A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.', ] __lowerCamelCase : List[Any] = tokenizer(a , return_tensors='pt' , padding=a ).input_ids # fmt: off __lowerCamelCase : Dict = torch.tensor( [ [ 3_8530, 21_0703, 25_6299, 1410, 25_6298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 2_5922, 25_6299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 1_9014, 1_0620, 758, 25_6299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 25_6299, 1_4869, 281, 301, 25_6298, 275, 11_9983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 25_6299, 1_4869, 281, 2234, 289, 2275, 333,6_1391, 289, 25_6298, 543, 25_6297, 16_8714, 329, 25_6296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(a , a ) __lowerCamelCase : Optional[Any] = model.generate(input_ids.to(a ) ) __lowerCamelCase : Any = [ '<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>', '<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', '<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>', ] __lowerCamelCase : Tuple = tokenizer.batch_decode(a ) self.assertEqual(a , a )
669
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
1
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor lowercase_ = logging.get_logger(__name__) class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: Union[str, Any] , *a: Optional[int] , **a: Tuple ): warnings.warn( 'The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DeiTImageProcessor instead.' , a , ) super().__init__(*a , **a )
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
from __future__ import annotations import math def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = u for i in range(1 , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = temp * (u - i) return temp def UpperCamelCase__ ( ): __lowerCamelCase : Optional[int] = int(input('enter the numbers of values: ' ) ) __lowerCamelCase : list[list[float]] = [] for _ in range(SCREAMING_SNAKE_CASE__ ): y.append([] ) for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): y[i].append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = 0 print('enter the values of parameters in a list: ' ) __lowerCamelCase : str = list(map(SCREAMING_SNAKE_CASE__ , input().split() ) ) print('enter the values of corresponding parameters: ' ) for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = float(input() ) __lowerCamelCase : List[str] = int(input('enter the value to interpolate: ' ) ) __lowerCamelCase : Tuple = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , SCREAMING_SNAKE_CASE__ ): for j in range(n - i ): __lowerCamelCase : List[Any] = y[j + 1][i - 1] - y[j][i - 1] __lowerCamelCase : str = y[0][0] for i in range(1 , SCREAMING_SNAKE_CASE__ ): summ += (ucal(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) * y[0][i]) / math.factorial(SCREAMING_SNAKE_CASE__ ) print(f'the value at {value} is {summ}' ) if __name__ == "__main__": main()
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """roformer""" def __init__( self: Dict , a: Optional[Any]=5_0000 , a: Tuple=None , a: Any=768 , a: List[Any]=12 , a: Union[str, Any]=12 , a: int=3072 , a: List[str]="gelu" , a: str=0.1 , a: Any=0.1 , a: Optional[Any]=1536 , a: str=2 , a: List[Any]=0.0_2 , a: List[str]=1e-12 , a: Dict=0 , a: Optional[int]=False , a: Any=True , **a: Tuple , ): super().__init__(pad_token_id=a , **a ) __lowerCamelCase : str = vocab_size __lowerCamelCase : Union[str, Any] = hidden_size if embedding_size is None else embedding_size __lowerCamelCase : str = hidden_size __lowerCamelCase : Union[str, Any] = num_hidden_layers __lowerCamelCase : int = num_attention_heads __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : Tuple = attention_probs_dropout_prob __lowerCamelCase : List[Any] = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : int = layer_norm_eps __lowerCamelCase : Union[str, Any] = rotary_value __lowerCamelCase : Dict = use_cache class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Any ): if self.task == "multiple-choice": __lowerCamelCase : str = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : str = {0: 'batch', 1: 'sequence'} __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'andreasmadsen/efficient_mlm_m0.40': ( 'https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """roberta-prelayernorm""" def __init__( self: List[Any] , a: Union[str, Any]=5_0265 , a: str=768 , a: int=12 , a: Union[str, Any]=12 , a: Dict=3072 , a: int="gelu" , a: List[str]=0.1 , a: str=0.1 , a: str=512 , a: Union[str, Any]=2 , a: Tuple=0.0_2 , a: Optional[Any]=1e-12 , a: Any=1 , a: Any=0 , a: int=2 , a: List[str]="absolute" , a: List[str]=True , a: Union[str, Any]=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : str = num_attention_heads __lowerCamelCase : Union[str, Any] = hidden_act __lowerCamelCase : str = intermediate_size __lowerCamelCase : Union[str, Any] = hidden_dropout_prob __lowerCamelCase : Union[str, Any] = attention_probs_dropout_prob __lowerCamelCase : List[str] = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : Dict = initializer_range __lowerCamelCase : Dict = layer_norm_eps __lowerCamelCase : List[str] = position_embedding_type __lowerCamelCase : List[Any] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
# 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 argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input lowercase_ = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def UpperCamelCase__ ( ): __lowerCamelCase : Any = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __lowerCamelCase : int = get_sagemaker_input() else: __lowerCamelCase : Optional[int] = get_cluster_input() return config def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__=None ): if subparsers is not None: __lowerCamelCase : int = subparsers.add_parser('config' , description=SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : Tuple = argparse.ArgumentParser('Accelerate config command' , description=SCREAMING_SNAKE_CASE__ ) parser.add_argument( '--config_file' , default=SCREAMING_SNAKE_CASE__ , 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\'.' ) , ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) return parser def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = get_user_input() if args.config_file is not None: __lowerCamelCase : List[Any] = args.config_file else: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): os.makedirs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(SCREAMING_SNAKE_CASE__ ) else: config.to_yaml_file(SCREAMING_SNAKE_CASE__ ) print(f'accelerate configuration saved at {config_file}' ) def UpperCamelCase__ ( ): __lowerCamelCase : Optional[Any] = config_command_parser() __lowerCamelCase : List[Any] = parser.parse_args() config_command(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
669
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
1
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class A_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
1
from __future__ import annotations from random import random class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: int | None = None ): __lowerCamelCase : Tuple = value __lowerCamelCase : Optional[int] = random() __lowerCamelCase : Node | None = None __lowerCamelCase : Node | None = None def __repr__( self: Any ): from pprint import pformat if self.left is None and self.right is None: return F'\'{self.value}: {self.prior:.5}\'' else: return pformat( {F'{self.value}: {self.prior:.5}': (self.left, self.right)} , indent=1 ) def __str__( self: int ): __lowerCamelCase : Tuple = str(self.value ) + ' ' __lowerCamelCase : Union[str, Any] = str(self.left or '' ) __lowerCamelCase : str = str(self.right or '' ) return value + left + right def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: __lowerCamelCase , __lowerCamelCase : List[Any] = split(root.left , SCREAMING_SNAKE_CASE__ ) return left, root else: __lowerCamelCase , __lowerCamelCase : Tuple = split(root.right , SCREAMING_SNAKE_CASE__ ) return root, right def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: __lowerCamelCase : List[str] = merge(left.right , SCREAMING_SNAKE_CASE__ ) return left else: __lowerCamelCase : Union[str, Any] = merge(SCREAMING_SNAKE_CASE__ , right.left ) return right def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = Node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase : Optional[int] = split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return merge(merge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase , __lowerCamelCase : Optional[Any] = split(SCREAMING_SNAKE_CASE__ , value - 1 ) __lowerCamelCase , __lowerCamelCase : Any = split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return merge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if not root: # None return else: inorder(root.left ) print(root.value , end=',' ) inorder(root.right ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for arg in args.split(): if arg[0] == "+": __lowerCamelCase : Any = insert(SCREAMING_SNAKE_CASE__ , int(arg[1:] ) ) elif arg[0] == "-": __lowerCamelCase : Tuple = erase(SCREAMING_SNAKE_CASE__ , int(arg[1:] ) ) else: print('Unknown command' ) return root def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = None print( 'enter numbers to create a tree, + value to add value into treap, ' '- value to erase all nodes with value. \'q\' to quit. ' ) __lowerCamelCase : Any = input() while args != "q": __lowerCamelCase : Dict = interact_treap(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = input() print('good by!' ) if __name__ == "__main__": import doctest doctest.testmod() main()
669
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
1
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
1
lowercase_ = { 'Pillow': 'Pillow', 'accelerate': 'accelerate>=0.11.0', 'compel': 'compel==0.1.8', 'black': 'black~=23.1', 'datasets': 'datasets', 'filelock': 'filelock', 'flax': 'flax>=0.4.1', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.13.2', 'requests-mock': 'requests-mock==1.10.0', 'importlib_metadata': 'importlib_metadata', 'invisible-watermark': 'invisible-watermark', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2', 'jaxlib': 'jaxlib>=0.1.65', 'Jinja2': 'Jinja2', 'k-diffusion': 'k-diffusion>=0.0.12', 'torchsde': 'torchsde', 'note_seq': 'note_seq', 'librosa': 'librosa', 'numpy': 'numpy', 'omegaconf': 'omegaconf', 'parameterized': 'parameterized', 'protobuf': 'protobuf>=3.20.3,<4', 'pytest': 'pytest', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'ruff': 'ruff>=0.0.241', 'safetensors': 'safetensors', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'scipy': 'scipy', 'onnx': 'onnx', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'tensorboard': 'tensorboard', 'torch': 'torch>=1.4', 'torchvision': 'torchvision', 'transformers': 'transformers>=4.25.1', 'urllib3': 'urllib3<=2.0.0', }
669
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : Any = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(a ) conf_scores.append(a ) return dec_strs, conf_scores def _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
1
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig lowercase_ = logging.get_logger(__name__) lowercase_ = 'T5Config' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = jnp.zeros_like(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) __lowerCamelCase : Optional[Any] = shifted_input_ids.at[:, 0].set(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[Any] = jnp.where(shifted_input_ids == -100 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return shifted_input_ids class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """mt5""" __snake_case = MTaConfig class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """mt5""" __snake_case = MTaConfig class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """mt5""" __snake_case = MTaConfig
669
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
1
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__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , ): __lowerCamelCase : List[str] = {} if train_file is not None: __lowerCamelCase : Any = [train_file] if eval_file is not None: __lowerCamelCase : Optional[int] = [eval_file] if test_file is not None: __lowerCamelCase : Optional[int] = [test_file] __lowerCamelCase : List[Any] = datasets.load_dataset('csv' , data_files=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = list(ds[list(files.keys() )[0]].features.keys() ) __lowerCamelCase : Union[str, Any] = features_name.pop(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = list(set(ds[list(files.keys() )[0]][label_name] ) ) __lowerCamelCase : Optional[int] = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase : Optional[Any] = tokenizer.model_input_names __lowerCamelCase : str = {} if len(SCREAMING_SNAKE_CASE__ ) == 1: for k in files.keys(): __lowerCamelCase : Optional[Any] = ds[k].map( lambda SCREAMING_SNAKE_CASE__ : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding='max_length' ) , batched=SCREAMING_SNAKE_CASE__ , ) elif len(SCREAMING_SNAKE_CASE__ ) == 2: for k in files.keys(): __lowerCamelCase : Tuple = ds[k].map( lambda SCREAMING_SNAKE_CASE__ : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding='max_length' , ) , batched=SCREAMING_SNAKE_CASE__ , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: __lowerCamelCase : List[str] = {k: v for k, v in ex.items() if k in input_names} __lowerCamelCase : Union[str, Any] = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: __lowerCamelCase : int = {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[Any] = {k: v for k, v in ex.items() if k in input_names} __lowerCamelCase : Optional[Any] = labelaid[ex[label_name]] yield (d, label) __lowerCamelCase : Dict = ( tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({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 : Optional[Any] = ( tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({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 : Tuple = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) __lowerCamelCase : Dict = ( tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({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 : Optional[int] = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid lowercase_ = logging.getLogger(__name__) @dataclass class A_ : '''simple docstring''' __snake_case = field(metadata={"""help""": """Which column contains the label"""} ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """The path of the training file"""} ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """The path of the development file"""} ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """The path of the test file"""} ) __snake_case = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) @dataclass class A_ : '''simple docstring''' __snake_case = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) def UpperCamelCase__ ( ): # 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 : Optional[Any] = get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=SCREAMING_SNAKE_CASE__ , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) __lowerCamelCase : Optional[int] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(SCREAMING_SNAKE_CASE__ ) , labelaid=SCREAMING_SNAKE_CASE__ , 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 : Union[str, Any] = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool('.bin' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE__ , cache_dir=model_args.cache_dir , ) def compute_metrics(SCREAMING_SNAKE_CASE__ ) -> Dict: __lowerCamelCase : Optional[Any] = np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer __lowerCamelCase : str = TFTrainer( model=SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , compute_metrics=SCREAMING_SNAKE_CASE__ , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __lowerCamelCase : str = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __lowerCamelCase : Tuple = trainer.evaluate() __lowerCamelCase : Optional[Any] = os.path.join(training_args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , '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(SCREAMING_SNAKE_CASE__ ) return results if __name__ == "__main__": main()
669
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
1
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch lowercase_ = logging.get_logger(__name__) @add_end_docstrings( __UpperCamelCase , R""" top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). """ , ) class A_ ( __UpperCamelCase ): '''simple docstring''' def _snake_case ( self: Optional[int] , a: GenericTensor ): if self.framework == "tf": __lowerCamelCase : Optional[Any] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": __lowerCamelCase : Optional[int] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=a ) else: raise ValueError('Unsupported framework' ) return masked_index def _snake_case ( self: Tuple , a: GenericTensor ): __lowerCamelCase : Dict = self.get_masked_index(a ) __lowerCamelCase : Any = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( 'fill-mask' , self.model.base_model_prefix , F'No mask_token ({self.tokenizer.mask_token}) found on the input' , ) def _snake_case ( self: Optional[int] , a: GenericTensor ): if isinstance(a , a ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input['input_ids'][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(a ) def _snake_case ( self: Tuple , a: Any , a: Optional[int]=None , **a: Dict ): if return_tensors is None: __lowerCamelCase : Union[str, Any] = self.framework __lowerCamelCase : List[str] = self.tokenizer(a , return_tensors=a ) self.ensure_exactly_one_mask_token(a ) return model_inputs def _snake_case ( self: Optional[Any] , a: int ): __lowerCamelCase : Optional[Any] = self.model(**a ) __lowerCamelCase : Union[str, Any] = model_inputs['input_ids'] return model_outputs def _snake_case ( self: Union[str, Any] , a: int , a: List[Any]=5 , a: Dict=None ): # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: __lowerCamelCase : str = target_ids.shape[0] __lowerCamelCase : Any = model_outputs['input_ids'][0] __lowerCamelCase : int = model_outputs['logits'] if self.framework == "tf": __lowerCamelCase : Optional[int] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] __lowerCamelCase : Dict = outputs.numpy() __lowerCamelCase : Tuple = outputs[0, masked_index, :] __lowerCamelCase : List[Any] = stable_softmax(a , axis=-1 ) if target_ids is not None: __lowerCamelCase : int = tf.gather_nd(tf.squeeze(a , 0 ) , target_ids.reshape(-1 , 1 ) ) __lowerCamelCase : Optional[Any] = tf.expand_dims(a , 0 ) __lowerCamelCase : Union[str, Any] = tf.math.top_k(a , k=a ) __lowerCamelCase , __lowerCamelCase : Dict = topk.values.numpy(), topk.indices.numpy() else: __lowerCamelCase : Union[str, Any] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=a ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample __lowerCamelCase : List[Any] = outputs[0, masked_index, :] __lowerCamelCase : Dict = logits.softmax(dim=-1 ) if target_ids is not None: __lowerCamelCase : Optional[Any] = probs[..., target_ids] __lowerCamelCase , __lowerCamelCase : Dict = probs.topk(a ) __lowerCamelCase : str = [] __lowerCamelCase : Tuple = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): __lowerCamelCase : Optional[Any] = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place __lowerCamelCase : Any = input_ids.numpy().copy() if target_ids is not None: __lowerCamelCase : Any = target_ids[p].tolist() __lowerCamelCase : Union[str, Any] = p # Filter padding out: __lowerCamelCase : Tuple = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back __lowerCamelCase : Optional[Any] = self.tokenizer.decode(a , skip_special_tokens=a ) __lowerCamelCase : Union[str, Any] = {'score': v, 'token': p, 'token_str': self.tokenizer.decode([p] ), 'sequence': sequence} row.append(a ) result.append(a ) if single_mask: return result[0] return result def _snake_case ( self: Optional[int] , a: int , a: Optional[Any]=None ): if isinstance(a , a ): __lowerCamelCase : List[Any] = [targets] try: __lowerCamelCase : List[Any] = self.tokenizer.get_vocab() except Exception: __lowerCamelCase : Dict = {} __lowerCamelCase : List[str] = [] for target in targets: __lowerCamelCase : Any = vocab.get(a , a ) if id_ is None: __lowerCamelCase : Union[str, Any] = self.tokenizer( a , add_special_tokens=a , return_attention_mask=a , return_token_type_ids=a , max_length=1 , truncation=a , )['input_ids'] if len(a ) == 0: logger.warning( F'The specified target token `{target}` does not exist in the model vocabulary. ' 'We cannot replace it with anything meaningful, ignoring it' ) continue __lowerCamelCase : List[str] = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( F'The specified target token `{target}` does not exist in the model vocabulary. ' F'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' ) target_ids.append(id_ ) __lowerCamelCase : Tuple = list(set(a ) ) if len(a ) == 0: raise ValueError('At least one target must be provided when passed.' ) __lowerCamelCase : Union[str, Any] = np.array(a ) return target_ids def _snake_case ( self: Any , a: Any=None , a: int=None ): __lowerCamelCase : int = {} if targets is not None: __lowerCamelCase : Dict = self.get_target_ids(a , a ) __lowerCamelCase : Any = target_ids if top_k is not None: __lowerCamelCase : str = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( 'fill-mask' , self.model.base_model_prefix , 'The tokenizer does not define a `mask_token`.' ) return {}, {}, postprocess_params def __call__( self: str , a: Tuple , *a: List[str] , **a: Tuple ): __lowerCamelCase : Optional[int] = super().__call__(a , **a ) if isinstance(a , a ) and len(a ) == 1: return outputs[0] return outputs
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { 'configuration_mobilebert': [ 'MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileBertConfig', 'MobileBertOnnxConfig', ], 'tokenization_mobilebert': ['MobileBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['MobileBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileBertForMaskedLM', 'MobileBertForMultipleChoice', 'MobileBertForNextSentencePrediction', 'MobileBertForPreTraining', 'MobileBertForQuestionAnswering', 'MobileBertForSequenceClassification', 'MobileBertForTokenClassification', 'MobileBertLayer', 'MobileBertModel', 'MobileBertPreTrainedModel', 'load_tf_weights_in_mobilebert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFMobileBertForMaskedLM', 'TFMobileBertForMultipleChoice', 'TFMobileBertForNextSentencePrediction', 'TFMobileBertForPreTraining', 'TFMobileBertForQuestionAnswering', 'TFMobileBertForSequenceClassification', 'TFMobileBertForTokenClassification', 'TFMobileBertMainLayer', 'TFMobileBertModel', 'TFMobileBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
1
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort lowercase_ = logging.get_logger(__name__) lowercase_ = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class A_ : '''simple docstring''' def __init__( self: Optional[Any] , a: List[Any]=None , **a: Dict ): logger.info('`diffusers.OnnxRuntimeModel` is experimental and might change in the future.' ) __lowerCamelCase : List[str] = model __lowerCamelCase : Optional[int] = kwargs.get('model_save_dir' , a ) __lowerCamelCase : Optional[Any] = kwargs.get('latest_model_name' , a ) def __call__( self: Union[str, Any] , **a: str ): __lowerCamelCase : Optional[Any] = {k: np.array(a ) for k, v in kwargs.items()} return self.model.run(a , a ) @staticmethod def _snake_case ( a: Union[str, Path] , a: Any=None , a: int=None ): if provider is None: logger.info('No onnxruntime provider specified, using CPUExecutionProvider' ) __lowerCamelCase : List[str] = 'CPUExecutionProvider' return ort.InferenceSession(a , providers=[provider] , sess_options=a ) def _snake_case ( self: Optional[int] , a: Union[str, Path] , a: Optional[str] = None , **a: Dict ): __lowerCamelCase : Tuple = file_name if file_name is not None else ONNX_WEIGHTS_NAME __lowerCamelCase : Any = self.model_save_dir.joinpath(self.latest_model_name ) __lowerCamelCase : int = Path(a ).joinpath(a ) try: shutil.copyfile(a , a ) except shutil.SameFileError: pass # copy external weights (for models >2GB) __lowerCamelCase : List[str] = self.model_save_dir.joinpath(a ) if src_path.exists(): __lowerCamelCase : Optional[Any] = Path(a ).joinpath(a ) try: shutil.copyfile(a , a ) except shutil.SameFileError: pass def _snake_case ( self: List[str] , a: Union[str, os.PathLike] , **a: List[Any] , ): if os.path.isfile(a ): logger.error(F'Provided path ({save_directory}) should be a directory, not a file' ) return os.makedirs(a , exist_ok=a ) # saving model weights/files self._save_pretrained(a , **a ) @classmethod def _snake_case ( cls: Dict , a: Union[str, Path] , a: Optional[Union[bool, str, None]] = None , a: Optional[Union[str, None]] = None , a: bool = False , a: Optional[str] = None , a: Optional[str] = None , a: Optional[str] = None , a: Optional["ort.SessionOptions"] = None , **a: Optional[Any] , ): __lowerCamelCase : List[Any] = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(a ): __lowerCamelCase : Optional[Any] = OnnxRuntimeModel.load_model( os.path.join(a , a ) , provider=a , sess_options=a ) __lowerCamelCase : Union[str, Any] = Path(a ) # load model from hub else: # download model __lowerCamelCase : List[str] = hf_hub_download( repo_id=a , filename=a , use_auth_token=a , revision=a , cache_dir=a , force_download=a , ) __lowerCamelCase : Union[str, Any] = Path(a ).parent __lowerCamelCase : int = Path(a ).name __lowerCamelCase : Tuple = OnnxRuntimeModel.load_model(a , provider=a , sess_options=a ) return cls(model=a , **a ) @classmethod def _snake_case ( cls: Union[str, Any] , a: Union[str, Path] , a: bool = True , a: Optional[str] = None , a: Optional[str] = None , **a: List[Any] , ): __lowerCamelCase : Any = None if len(str(a ).split('@' ) ) == 2: __lowerCamelCase , __lowerCamelCase : Optional[Any] = model_id.split('@' ) return cls._from_pretrained( model_id=a , revision=a , cache_dir=a , force_download=a , use_auth_token=a , **a , )
669
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
1
from graphs.minimum_spanning_tree_kruskal import kruskal def UpperCamelCase__ ( ): __lowerCamelCase : Any = 9 __lowerCamelCase : List[str] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] __lowerCamelCase : List[str] = kruskal(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(SCREAMING_SNAKE_CASE__ ) == sorted(SCREAMING_SNAKE_CASE__ )
669
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
1
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class A_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=__UpperCamelCase ) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = field(default="""audio-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) __snake_case = Features({"""audio""": Audio()} ) __snake_case = Features({"""labels""": ClassLabel} ) __snake_case = "audio" __snake_case = "labels" def _snake_case ( self: Tuple , a: int ): 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.' ) __lowerCamelCase : int = copy.deepcopy(self ) __lowerCamelCase : List[Any] = self.label_schema.copy() __lowerCamelCase : Tuple = features[self.label_column] __lowerCamelCase : Dict = label_schema return task_template @property def _snake_case ( self: List[Any] ): return { self.audio_column: "audio", self.label_column: "labels", }
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
1
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch lowercase_ = True except ImportError: lowercase_ = False try: from torch.hub import _get_torch_home lowercase_ = _get_torch_home() except ImportError: lowercase_ = os.path.expanduser( os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')) ) lowercase_ = os.path.join(torch_cache_home, 'transformers') lowercase_ = 'https://cdn.huggingface.co' lowercase_ = 'https://s3.amazonaws.com/models.huggingface.co/bert' lowercase_ = '/'.join(str(Path(__file__).resolve()).split('/')[:-1]) lowercase_ = os.path.join(PATH, 'config.yaml') lowercase_ = os.path.join(PATH, 'attributes.txt') lowercase_ = os.path.join(PATH, 'objects.txt') lowercase_ = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path) lowercase_ = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE) lowercase_ = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE) lowercase_ = 'pytorch_model.bin' lowercase_ = 'config.yaml' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__=OBJECTS , SCREAMING_SNAKE_CASE__=ATTRIBUTES ): __lowerCamelCase : Optional[int] = [] with open(SCREAMING_SNAKE_CASE__ ) as f: for object in f.readlines(): vg_classes.append(object.split(',' )[0].lower().strip() ) __lowerCamelCase : Optional[int] = [] with open(SCREAMING_SNAKE_CASE__ ) as f: for object in f.readlines(): vg_attrs.append(object.split(',' )[0].lower().strip() ) return vg_classes, vg_attrs def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = OrderedDict() with open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __lowerCamelCase : Dict = pkl.load(SCREAMING_SNAKE_CASE__ )['model'] for k in copy.deepcopy(list(ckp.keys() ) ): __lowerCamelCase : List[Any] = ckp.pop(SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): __lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) else: assert isinstance(SCREAMING_SNAKE_CASE__ , torch.tensor ), type(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = v return r class A_ : '''simple docstring''' __snake_case = {} def __init__( self: Union[str, Any] , a: dict , a: str = "root" , a: Union[str, Any]=0 ): __lowerCamelCase : int = name __lowerCamelCase : str = level __lowerCamelCase : str = {} for k, v in dictionary.items(): if v is None: raise ValueError() __lowerCamelCase : str = copy.deepcopy(a ) __lowerCamelCase : List[str] = copy.deepcopy(a ) if isinstance(a , a ): __lowerCamelCase : Dict = Config(a , name=a , level=level + 1 ) __lowerCamelCase : Optional[int] = v setattr(self , a , a ) __lowerCamelCase : Union[str, Any] = d def __repr__( self: Optional[int] ): return str(list((self._pointer.keys()) ) ) def __setattr__( self: int , a: Tuple , a: Tuple ): __lowerCamelCase : Optional[Any] = val __lowerCamelCase : List[Any] = val __lowerCamelCase : int = key.split('.' ) __lowerCamelCase : str = len(a ) - 1 __lowerCamelCase : Tuple = self._pointer if len(a ) > 1: for i, l in enumerate(a ): if hasattr(self , a ) and isinstance(getattr(self , a ) , a ): setattr(getattr(self , a ) , '.'.join(levels[i:] ) , a ) if l == last_level: __lowerCamelCase : List[Any] = val else: __lowerCamelCase : Any = pointer[l] def _snake_case ( self: str ): return self._pointer def _snake_case ( self: Optional[int] , a: List[Any] , a: List[Any] ): with open(F'{file_name}' , 'w' ) as stream: dump(a , a ) def _snake_case ( self: str , a: List[str] , a: Optional[int] ): with open(F'{file_name}' , 'w' ) as stream: json.dump(a , a ) @staticmethod def _snake_case ( a: Optional[int] ): with open(a ) as stream: __lowerCamelCase : Optional[int] = load(a , Loader=a ) return data def __str__( self: int ): __lowerCamelCase : List[str] = ' ' if self._name != "root": __lowerCamelCase : List[str] = F'{t * (self._level-1)}{self._name}:\n' else: __lowerCamelCase : List[str] = '' __lowerCamelCase : Union[str, Any] = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(a , a ): r += F'{t * (self._level)}{v}\n' self._level += 1 else: r += F'{t * (self._level)}{k}: {v} ({type(a ).__name__})\n' __lowerCamelCase : Dict = level return r[:-1] @classmethod def _snake_case ( cls: Union[str, Any] , a: str , **a: Optional[Any] ): __lowerCamelCase , __lowerCamelCase : Optional[int] = cls.get_config_dict(a , **a ) return cls(a ) @classmethod def _snake_case ( cls: Dict , a: str , **a: Union[str, Any] ): __lowerCamelCase : Any = kwargs.pop('cache_dir' , a ) __lowerCamelCase : List[Any] = kwargs.pop('force_download' , a ) __lowerCamelCase : str = kwargs.pop('resume_download' , a ) __lowerCamelCase : str = kwargs.pop('proxies' , a ) __lowerCamelCase : Any = kwargs.pop('local_files_only' , a ) if os.path.isdir(a ): __lowerCamelCase : List[str] = os.path.join(a , a ) elif os.path.isfile(a ) or is_remote_url(a ): __lowerCamelCase : str = pretrained_model_name_or_path else: __lowerCamelCase : int = hf_bucket_url(a , filename=a , use_cdn=a ) try: # Load from URL or cache if already cached __lowerCamelCase : Any = cached_path( a , cache_dir=a , force_download=a , proxies=a , resume_download=a , local_files_only=a , ) # Load config dict if resolved_config_file is None: raise EnvironmentError __lowerCamelCase : str = Config.load_yaml(a ) except EnvironmentError: __lowerCamelCase : List[Any] = 'Can\'t load config for' raise EnvironmentError(a ) if resolved_config_file == config_file: print('loading configuration file from path' ) else: print('loading configuration file cache' ) return Config.load_yaml(a ), kwargs def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = torch.load('dump.pt' , map_location=in_tensor.device ) __lowerCamelCase : str = in_tensor.numpy() __lowerCamelCase : Tuple = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , rtol=0.01 , atol=0.1 ), ( f'{sum([1 for x in np.isclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %' " element-wise mismatch" ) raise Exception('tensors are all good' ) # Hugging face functions below def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = urlparse(SCREAMING_SNAKE_CASE__ ) return parsed.scheme in ("http", "https") def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=True ): __lowerCamelCase : List[Any] = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX __lowerCamelCase : Any = '/' not in model_id if legacy_format: return f'{endpoint}/{model_id}-{filename}' else: return f'{endpoint}/{model_id}/{filename}' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=None , ): __lowerCamelCase : Any = 'python/{}'.format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): ua += "; " + "; ".join('{}/{}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for k, v in user_agent.items() ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): ua += "; " + user_agent __lowerCamelCase : Dict = {'user-agent': ua} if resume_size > 0: __lowerCamelCase : Any = 'bytes=%d-' % (resume_size,) __lowerCamelCase : Any = requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ , proxies=SCREAMING_SNAKE_CASE__ , headers=SCREAMING_SNAKE_CASE__ ) if response.status_code == 416: # Range not satisfiable return __lowerCamelCase : Optional[Any] = response.headers.get('Content-Length' ) __lowerCamelCase : str = resume_size + int(SCREAMING_SNAKE_CASE__ ) if content_length is not None else None __lowerCamelCase : Dict = tqdm( unit='B' , unit_scale=SCREAMING_SNAKE_CASE__ , total=SCREAMING_SNAKE_CASE__ , initial=SCREAMING_SNAKE_CASE__ , desc='Downloading' , ) for chunk in response.iter_content(chunk_size=1_024 ): if chunk: # filter out keep-alive new chunks progress.update(len(SCREAMING_SNAKE_CASE__ ) ) temp_file.write(SCREAMING_SNAKE_CASE__ ) progress.close() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , ): if cache_dir is None: __lowerCamelCase : List[Any] = TRANSFORMERS_CACHE if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = str(SCREAMING_SNAKE_CASE__ ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None if not local_files_only: try: __lowerCamelCase : List[Any] = requests.head(SCREAMING_SNAKE_CASE__ , allow_redirects=SCREAMING_SNAKE_CASE__ , proxies=SCREAMING_SNAKE_CASE__ , timeout=SCREAMING_SNAKE_CASE__ ) if response.status_code == 200: __lowerCamelCase : Tuple = response.headers.get('ETag' ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass __lowerCamelCase : Dict = url_to_filename(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # get cache path to put the file __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(SCREAMING_SNAKE_CASE__ ): return cache_path else: __lowerCamelCase : List[str] = [ file for file in fnmatch.filter(os.listdir(SCREAMING_SNAKE_CASE__ ) , filename + '.*' ) if not file.endswith('.json' ) and not file.endswith('.lock' ) ] if len(SCREAMING_SNAKE_CASE__ ) > 0: return os.path.join(SCREAMING_SNAKE_CASE__ , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( 'Cannot find the requested files in the cached path and outgoing traffic has been' ' disabled. To enable model look-ups and downloads online, set \'local_files_only\'' ' to False.' ) return None # From now on, etag is not None. if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. __lowerCamelCase : Any = cache_path + '.lock' with FileLock(SCREAMING_SNAKE_CASE__ ): # If the download just completed while the lock was activated. if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: __lowerCamelCase : Any = cache_path + '.incomplete' @contextmanager def _resumable_file_manager(): with open(SCREAMING_SNAKE_CASE__ , 'a+b' ) as f: yield f __lowerCamelCase : int = _resumable_file_manager if os.path.exists(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = os.stat(SCREAMING_SNAKE_CASE__ ).st_size else: __lowerCamelCase : Any = 0 else: __lowerCamelCase : Any = partial(tempfile.NamedTemporaryFile , dir=SCREAMING_SNAKE_CASE__ , delete=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( '%s not found in cache or force_download set to True, downloading to %s' , SCREAMING_SNAKE_CASE__ , temp_file.name , ) http_get( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , proxies=SCREAMING_SNAKE_CASE__ , resume_size=SCREAMING_SNAKE_CASE__ , user_agent=SCREAMING_SNAKE_CASE__ , ) os.replace(temp_file.name , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = {'url': url, 'etag': etag} __lowerCamelCase : Optional[Any] = cache_path + '.json' with open(SCREAMING_SNAKE_CASE__ , 'w' ) as meta_file: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return cache_path def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): __lowerCamelCase : Optional[int] = url.encode('utf-8' ) __lowerCamelCase : Tuple = shaaaa(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = url_hash.hexdigest() if etag: __lowerCamelCase : Union[str, Any] = etag.encode('utf-8' ) __lowerCamelCase : Optional[Any] = shaaaa(SCREAMING_SNAKE_CASE__ ) filename += "." + etag_hash.hexdigest() if url.endswith('.h5' ): filename += ".h5" return filename def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , ): if cache_dir is None: __lowerCamelCase : Optional[int] = TRANSFORMERS_CACHE if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = str(SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = str(SCREAMING_SNAKE_CASE__ ) if is_remote_url(SCREAMING_SNAKE_CASE__ ): # URL, so get it from the cache (downloading if necessary) __lowerCamelCase : Tuple = get_from_cache( SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ , proxies=SCREAMING_SNAKE_CASE__ , resume_download=SCREAMING_SNAKE_CASE__ , user_agent=SCREAMING_SNAKE_CASE__ , local_files_only=SCREAMING_SNAKE_CASE__ , ) elif os.path.exists(SCREAMING_SNAKE_CASE__ ): # File, and it exists. __lowerCamelCase : int = url_or_filename elif urlparse(SCREAMING_SNAKE_CASE__ ).scheme == "": # File, but it doesn't exist. raise EnvironmentError('file {} not found'.format(SCREAMING_SNAKE_CASE__ ) ) else: # Something unknown raise ValueError('unable to parse {} as a URL or as a local path'.format(SCREAMING_SNAKE_CASE__ ) ) if extract_compressed_file: if not is_zipfile(SCREAMING_SNAKE_CASE__ ) and not tarfile.is_tarfile(SCREAMING_SNAKE_CASE__ ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" __lowerCamelCase , __lowerCamelCase : List[Any] = os.path.split(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = output_file.replace('.' , '-' ) + '-extracted' __lowerCamelCase : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if os.path.isdir(SCREAMING_SNAKE_CASE__ ) and os.listdir(SCREAMING_SNAKE_CASE__ ) and not force_extract: return output_path_extracted # Prevent parallel extractions __lowerCamelCase : Tuple = output_path + '.lock' with FileLock(SCREAMING_SNAKE_CASE__ ): shutil.rmtree(SCREAMING_SNAKE_CASE__ , ignore_errors=SCREAMING_SNAKE_CASE__ ) os.makedirs(SCREAMING_SNAKE_CASE__ ) if is_zipfile(SCREAMING_SNAKE_CASE__ ): with ZipFile(SCREAMING_SNAKE_CASE__ , 'r' ) as zip_file: zip_file.extractall(SCREAMING_SNAKE_CASE__ ) zip_file.close() elif tarfile.is_tarfile(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = tarfile.open(SCREAMING_SNAKE_CASE__ ) tar_file.extractall(SCREAMING_SNAKE_CASE__ ) tar_file.close() else: raise EnvironmentError('Archive format of {} could not be identified'.format(SCREAMING_SNAKE_CASE__ ) ) return output_path_extracted return output_path def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="," ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if os.path.isfile(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ ) as f: __lowerCamelCase : Optional[Any] = eval(f.read() ) else: __lowerCamelCase : Tuple = requests.get(SCREAMING_SNAKE_CASE__ ) try: __lowerCamelCase : Tuple = requests.json() except Exception: __lowerCamelCase : str = req.content.decode() assert data is not None, "could not connect" try: __lowerCamelCase : List[Any] = eval(SCREAMING_SNAKE_CASE__ ) except Exception: __lowerCamelCase : Optional[Any] = data.split('\n' ) req.close() return data def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = requests.get(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = np.array(Image.open(BytesIO(response.content ) ) ) return img def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = url.split('/' )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , 'rb' ) as stream: __lowerCamelCase : Dict = pkl.load(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = weights.pop('model' ) __lowerCamelCase : Union[str, Any] = {} for k, v in model.items(): __lowerCamelCase : Union[str, Any] = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) if "running_var" in k: __lowerCamelCase : Optional[Any] = torch.tensor([0] ) __lowerCamelCase : Any = k.replace('running_var' , 'num_batches_tracked' ) __lowerCamelCase : Any = zero return new def UpperCamelCase__ ( ): print(f'{os.path.abspath(os.path.join(SCREAMING_SNAKE_CASE__ , os.pardir ) )}/demo.ipynb' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="RGB" ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if os.path.isfile(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = cva.imread(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : Optional[Any] = get_image_from_url(SCREAMING_SNAKE_CASE__ ) assert img is not None, f'could not connect to: {im}' __lowerCamelCase : Optional[Any] = cva.cvtColor(SCREAMING_SNAKE_CASE__ , cva.COLOR_BGR2RGB ) if input_format == "RGB": __lowerCamelCase : List[str] = img[:, :, ::-1] return img def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=1 ): return (images[i : i + batch] for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ))
669
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
1
import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = [] if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for v in tree.values(): shapes.extend(_fetch_dims(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError('Not supported' ) return shapes @torch.jit.ignore def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = [] for d in reversed(SCREAMING_SNAKE_CASE__ ): idx.append(flat_idx % d ) __lowerCamelCase : Any = flat_idx // d return tuple(reversed(SCREAMING_SNAKE_CASE__ ) ) @torch.jit.ignore def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): # start_edges and end_edges both indicate whether, starting from any given # dimension, the start/end index is at the top/bottom edge of the # corresponding tensor, modeled as a tree def reduce_edge_list(SCREAMING_SNAKE_CASE__ ) -> None: __lowerCamelCase : Any = True for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __lowerCamelCase : Optional[Any] = -1 * (i + 1) l[reversed_idx] &= tally __lowerCamelCase : Any = l[reversed_idx] if start_edges is None: __lowerCamelCase : List[Any] = [s == 0 for s in start] reduce_edge_list(SCREAMING_SNAKE_CASE__ ) if end_edges is None: __lowerCamelCase : str = [e == (d - 1) for e, d in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] reduce_edge_list(SCREAMING_SNAKE_CASE__ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(SCREAMING_SNAKE_CASE__ ) == 0: return [()] elif len(SCREAMING_SNAKE_CASE__ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] __lowerCamelCase : List[Tuple[slice, ...]] = [] __lowerCamelCase : List[slice] = [] # Dimensions common to start and end can be selected directly for s, e in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if s == e: path_list.append(slice(SCREAMING_SNAKE_CASE__ , s + 1 ) ) else: break __lowerCamelCase : Tuple[slice, ...] = tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__ ) # start == end, and we're done if divergence_idx == len(SCREAMING_SNAKE_CASE__ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None __lowerCamelCase : Union[str, Any] = start[divergence_idx] return tuple( path + (slice(SCREAMING_SNAKE_CASE__ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None __lowerCamelCase : List[str] = end[divergence_idx] return tuple( path + (slice(SCREAMING_SNAKE_CASE__ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) __lowerCamelCase : Optional[int] = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = t.shape[:no_batch_dims] __lowerCamelCase : Tuple = list(_flat_idx_to_idx(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # _get_minimal_slice_set is inclusive __lowerCamelCase : Dict = list(_flat_idx_to_idx(flat_end - 1 , SCREAMING_SNAKE_CASE__ ) ) # Get an ordered list of slices to perform __lowerCamelCase : Tuple = _get_minimal_slice_set( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase : List[str] = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , ): if not (len(SCREAMING_SNAKE_CASE__ ) > 0): raise ValueError('Must provide at least one input' ) __lowerCamelCase : Any = [shape[:no_batch_dims] for shape in _fetch_dims(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase : str = tuple([max(SCREAMING_SNAKE_CASE__ ) for s in zip(*SCREAMING_SNAKE_CASE__ )] ) def _prep_inputs(SCREAMING_SNAKE_CASE__ ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: __lowerCamelCase : str = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) __lowerCamelCase : List[str] = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: __lowerCamelCase : int = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t __lowerCamelCase : Dict[str, Any] = tensor_tree_map(_prep_inputs , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = None if _out is not None: __lowerCamelCase : Union[str, Any] = tensor_tree_map(lambda SCREAMING_SNAKE_CASE__ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) __lowerCamelCase : int = 1 for d in orig_batch_dims: flat_batch_dim *= d __lowerCamelCase : Optional[Any] = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(SCREAMING_SNAKE_CASE__ ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : int = prepped_outputs for _ in range(SCREAMING_SNAKE_CASE__ ): # Chunk the input if not low_mem: __lowerCamelCase : Optional[int] = _select_chunk else: __lowerCamelCase : Optional[int] = partial( _chunk_slice , flat_start=SCREAMING_SNAKE_CASE__ , flat_end=min(SCREAMING_SNAKE_CASE__ , i + chunk_size ) , no_batch_dims=len(SCREAMING_SNAKE_CASE__ ) , ) __lowerCamelCase : Dict[str, Any] = tensor_tree_map(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Run the layer on the chunk __lowerCamelCase : Tuple = layer(**SCREAMING_SNAKE_CASE__ ) # Allocate space for the output if out is None: __lowerCamelCase : Tuple = tensor_tree_map(lambda SCREAMING_SNAKE_CASE__ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , SCREAMING_SNAKE_CASE__ ) # Put the chunk in its pre-allocated space if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> None: for k, v in da.items(): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assign(SCREAMING_SNAKE_CASE__ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: __lowerCamelCase : Any = da[k] assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for xa, xa in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if _add_into_out: xa[i : i + chunk_size] += xa else: __lowerCamelCase : Union[str, Any] = xa elif isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: __lowerCamelCase : List[str] = output_chunk else: raise ValueError('Not supported' ) i += chunk_size __lowerCamelCase : Union[str, Any] = tensor_tree_map(lambda SCREAMING_SNAKE_CASE__ : t.view(orig_batch_dims + t.shape[1:] ) , SCREAMING_SNAKE_CASE__ ) return out class A_ : '''simple docstring''' def __init__( self: List[Any] , a: int = 512 , ): __lowerCamelCase : Dict = max_chunk_size __lowerCamelCase : Optional[int] = None __lowerCamelCase : Optional[tuple] = None def _snake_case ( self: Optional[Any] , a: Callable , a: tuple , a: int ): logging.info('Tuning chunk size...' ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size __lowerCamelCase : List[int] = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] __lowerCamelCase : Dict = [c for c in candidates if c > min_chunk_size] __lowerCamelCase : Dict = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(a: int ) -> bool: try: with torch.no_grad(): fn(*a , chunk_size=a ) return True except RuntimeError: return False __lowerCamelCase : Union[str, Any] = 0 __lowerCamelCase : Optional[Any] = len(a ) - 1 while i > min_viable_chunk_size_index: __lowerCamelCase : List[str] = test_chunk_size(candidates[i] ) if not viable: __lowerCamelCase : Optional[Any] = (min_viable_chunk_size_index + i) // 2 else: __lowerCamelCase : Tuple = i __lowerCamelCase : str = (i + len(a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _snake_case ( self: Optional[int] , a: Iterable , a: Iterable ): __lowerCamelCase : Optional[int] = True for aa, aa in zip(a , a ): assert type(a ) == type(a ) if isinstance(a , (list, tuple) ): consistent &= self._compare_arg_caches(a , a ) elif isinstance(a , a ): __lowerCamelCase : List[str] = [v for _, v in sorted(aa.items() , key=lambda a : x[0] )] __lowerCamelCase : List[str] = [v for _, v in sorted(aa.items() , key=lambda a : x[0] )] consistent &= self._compare_arg_caches(a , a ) else: consistent &= aa == aa return consistent def _snake_case ( self: Optional[Any] , a: Callable , a: tuple , a: int , ): __lowerCamelCase : Union[str, Any] = True __lowerCamelCase : tuple = tree_map(lambda a : a.shape if isinstance(a , torch.Tensor ) else a , a , a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(a ) __lowerCamelCase : List[Any] = self._compare_arg_caches(self.cached_arg_data , a ) else: # Otherwise, we can reuse the precomputed value __lowerCamelCase : Optional[int] = False if not consistent: __lowerCamelCase : str = self._determine_favorable_chunk_size( a , a , a , ) __lowerCamelCase : int = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
669
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( 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 , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
1
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): __lowerCamelCase : Tuple = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'blocks.{i}.norm1.weight', f'deit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'deit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'deit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'deit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'deit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'deit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'deit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'deit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'deit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'deit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ('cls_token', 'deit.embeddings.cls_token'), ('dist_token', 'deit.embeddings.distillation_token'), ('patch_embed.proj.weight', 'deit.embeddings.patch_embeddings.projection.weight'), ('patch_embed.proj.bias', 'deit.embeddings.patch_embeddings.projection.bias'), ('pos_embed', 'deit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" __lowerCamelCase : int = [(pair[0], pair[1][4:]) if pair[1].startswith('deit' ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ('norm.weight', 'deit.layernorm.weight'), ('norm.bias', 'deit.layernorm.bias'), ('head.weight', 'cls_classifier.weight'), ('head.bias', 'cls_classifier.bias'), ('head_dist.weight', 'distillation_classifier.weight'), ('head_dist.bias', 'distillation_classifier.bias'), ] ) return rename_keys def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): for i in range(config.num_hidden_layers ): if base_model: __lowerCamelCase : Any = '' else: __lowerCamelCase : List[str] = 'deit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __lowerCamelCase : Optional[Any] = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) __lowerCamelCase : Union[str, Any] = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict __lowerCamelCase : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] __lowerCamelCase : Any = in_proj_bias[: config.hidden_size] __lowerCamelCase : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __lowerCamelCase : Union[str, Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __lowerCamelCase : str = in_proj_weight[ -config.hidden_size :, : ] __lowerCamelCase : List[Any] = in_proj_bias[-config.hidden_size :] def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = dct.pop(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = val def UpperCamelCase__ ( ): __lowerCamelCase : List[Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' __lowerCamelCase : Optional[int] = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return im @torch.no_grad() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = DeiTConfig() # all deit models have fine-tuned heads __lowerCamelCase : Optional[int] = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size __lowerCamelCase : int = 1_000 __lowerCamelCase : str = 'huggingface/label-files' __lowerCamelCase : Any = 'imagenet-1k-id2label.json' __lowerCamelCase : int = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) , 'r' ) ) __lowerCamelCase : List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} __lowerCamelCase : Tuple = idalabel __lowerCamelCase : Optional[Any] = {v: k for k, v in idalabel.items()} __lowerCamelCase : Union[str, Any] = int(deit_name[-6:-4] ) __lowerCamelCase : List[str] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith('tiny' ): __lowerCamelCase : str = 192 __lowerCamelCase : List[Any] = 768 __lowerCamelCase : str = 12 __lowerCamelCase : Optional[int] = 3 elif deit_name[9:].startswith('small' ): __lowerCamelCase : Optional[Any] = 384 __lowerCamelCase : Any = 1_536 __lowerCamelCase : Any = 12 __lowerCamelCase : Dict = 6 if deit_name[9:].startswith('base' ): pass elif deit_name[4:].startswith('large' ): __lowerCamelCase : Optional[Any] = 1_024 __lowerCamelCase : Any = 4_096 __lowerCamelCase : str = 24 __lowerCamelCase : Tuple = 16 # load original model from timm __lowerCamelCase : int = timm.create_model(SCREAMING_SNAKE_CASE__ , pretrained=SCREAMING_SNAKE_CASE__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys __lowerCamelCase : Optional[Any] = timm_model.state_dict() __lowerCamelCase : Dict = create_rename_keys(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) read_in_q_k_v(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load HuggingFace model __lowerCamelCase : str = DeiTForImageClassificationWithTeacher(SCREAMING_SNAKE_CASE__ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # Check outputs on an image, prepared by DeiTImageProcessor __lowerCamelCase : List[Any] = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 __lowerCamelCase : Any = DeiTImageProcessor(size=SCREAMING_SNAKE_CASE__ , crop_size=config.image_size ) __lowerCamelCase : Any = image_processor(images=prepare_img() , return_tensors='pt' ) __lowerCamelCase : int = encoding['pixel_values'] __lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = timm_model(SCREAMING_SNAKE_CASE__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(SCREAMING_SNAKE_CASE__ , outputs.logits , atol=1e-3 ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(f'Saving model {deit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--deit_name', default='vit_deit_base_distilled_patch16_224', type=str, help='Name of the DeiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowercase_ = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
669
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
1
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
1
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = filter(lambda SCREAMING_SNAKE_CASE__ : p.requires_grad , model.parameters() ) __lowerCamelCase : Optional[int] = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowercase_ = logging.getLogger(__name__) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if metric == "rouge2": __lowerCamelCase : str = '{val_avg_rouge2:.4f}-{step_count}' elif metric == "bleu": __lowerCamelCase : Tuple = '{val_avg_bleu:.4f}-{step_count}' elif metric == "em": __lowerCamelCase : Dict = '{val_avg_em:.4f}-{step_count}' else: raise NotImplementedError( f'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' ' function.' ) __lowerCamelCase : List[Any] = ModelCheckpoint( dirpath=SCREAMING_SNAKE_CASE__ , filename=SCREAMING_SNAKE_CASE__ , monitor=f'val_{metric}' , mode='max' , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return EarlyStopping( monitor=f'val_{metric}' , mode='min' if 'loss' in metric else 'max' , patience=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , ) class A_ ( pl.Callback ): '''simple docstring''' def _snake_case ( self: List[Any] , a: Optional[int] , a: Union[str, Any] ): __lowerCamelCase : Any = {F'lr_group_{i}': param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(a ) @rank_zero_only def _snake_case ( self: Optional[Any] , a: pl.Trainer , a: pl.LightningModule , a: str , a: Union[str, Any]=True ): logger.info(F'***** {type_path} results at step {trainer.global_step:05d} *****' ) __lowerCamelCase : Union[str, Any] = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']} ) # Log results __lowerCamelCase : Optional[int] = Path(pl_module.hparams.output_dir ) if type_path == "test": __lowerCamelCase : str = od / 'test_results.txt' __lowerCamelCase : str = od / 'test_generations.txt' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __lowerCamelCase : Any = od / F'{type_path}_results/{trainer.global_step:05d}.txt' __lowerCamelCase : int = od / F'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=a ) generations_file.parent.mkdir(exist_ok=a ) with open(a , 'a+' ) as writer: for key in sorted(a ): if key in ["log", "progress_bar", "preds"]: continue __lowerCamelCase : int = metrics[key] if isinstance(a , torch.Tensor ): __lowerCamelCase : Tuple = val.item() __lowerCamelCase : Tuple = F'{key}: {val:.6f}\n' writer.write(a ) if not save_generations: return if "preds" in metrics: __lowerCamelCase : Optional[int] = '\n'.join(metrics['preds'] ) generations_file.open('w+' ).write(a ) @rank_zero_only def _snake_case ( self: List[str] , a: int , a: int ): try: __lowerCamelCase : Any = pl_module.model.model.num_parameters() except AttributeError: __lowerCamelCase : Dict = pl_module.model.num_parameters() __lowerCamelCase : str = count_trainable_parameters(a ) # mp stands for million parameters trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1e6, 'grad_mp': n_trainable_pars / 1e6} ) @rank_zero_only def _snake_case ( self: Tuple , a: pl.Trainer , a: pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(a , a , 'test' ) @rank_zero_only def _snake_case ( self: Optional[int] , a: pl.Trainer , a: Optional[int] ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
import numpy as np def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return np.where(vector > 0 , SCREAMING_SNAKE_CASE__ , (alpha * (np.exp(SCREAMING_SNAKE_CASE__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
import qiskit def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : Union[str, Any] = qiskit.QuantumCircuit(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0 ) circuit.x(1 ) # Map the quantum measurement to the classical bits circuit.measure([0, 1] , [0, 1] ) # Execute the circuit on the qasm simulator __lowerCamelCase : Any = qiskit.execute(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , shots=1_000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = single_qubit_measure(2, 2) print(F"""Total count for various states are: {counts}""")
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowercase_ = random.Random() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=1.0 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None ): if rng is None: __lowerCamelCase : Any = global_rng __lowerCamelCase : Optional[int] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class A_ ( unittest.TestCase ): '''simple docstring''' def __init__( self: int , a: List[Any] , a: List[Any]=7 , a: Tuple=400 , a: List[Any]=2000 , a: Dict=10 , a: Dict=160 , a: Optional[int]=8 , a: Tuple=0.0 , a: List[Any]=4000 , a: Optional[int]=False , a: str=True , ): __lowerCamelCase : Union[str, Any] = parent __lowerCamelCase : List[Any] = batch_size __lowerCamelCase : Optional[Any] = min_seq_length __lowerCamelCase : str = max_seq_length __lowerCamelCase : List[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __lowerCamelCase : List[str] = padding_value __lowerCamelCase : int = sampling_rate __lowerCamelCase : Union[str, Any] = return_attention_mask __lowerCamelCase : str = do_normalize __lowerCamelCase : Optional[Any] = feature_size __lowerCamelCase : Any = chunk_length __lowerCamelCase : List[Any] = hop_length def _snake_case ( self: str ): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _snake_case ( self: List[Any] , a: int=False , a: Tuple=False ): def _flatten(a: Any ): return list(itertools.chain(*a ) ) if equal_length: __lowerCamelCase : int = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __lowerCamelCase : Union[str, Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __lowerCamelCase : str = [np.asarray(a ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = WhisperFeatureExtractor if is_speech_available() else None def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Optional[Any] = WhisperFeatureExtractionTester(self ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCamelCase : Tuple = feat_extract_first.save_pretrained(a )[0] check_json_file_has_correct_format(a ) __lowerCamelCase : Optional[Any] = self.feature_extraction_class.from_pretrained(a ) __lowerCamelCase : List[Any] = feat_extract_first.to_dict() __lowerCamelCase : Any = feat_extract_second.to_dict() __lowerCamelCase : Dict = feat_extract_first.mel_filters __lowerCamelCase : str = feat_extract_second.mel_filters self.assertTrue(np.allclose(a , a ) ) self.assertEqual(a , a ) def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCamelCase : Tuple = os.path.join(a , 'feat_extract.json' ) feat_extract_first.to_json_file(a ) __lowerCamelCase : str = self.feature_extraction_class.from_json_file(a ) __lowerCamelCase : Union[str, Any] = feat_extract_first.to_dict() __lowerCamelCase : List[Any] = feat_extract_second.to_dict() __lowerCamelCase : Optional[Any] = feat_extract_first.mel_filters __lowerCamelCase : Optional[Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(a , a ) ) self.assertEqual(a , a ) def _snake_case ( self: Optional[Any] ): # Tests that all call wrap to encode_plus and batch_encode_plus __lowerCamelCase : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __lowerCamelCase : int = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __lowerCamelCase : str = [np.asarray(a ) for speech_input in speech_inputs] # Test feature size __lowerCamelCase : Union[str, Any] = feature_extractor(a , padding='max_length' , return_tensors='np' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __lowerCamelCase : Any = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_features __lowerCamelCase : Optional[Any] = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_features self.assertTrue(np.allclose(a , a , atol=1e-3 ) ) # Test batched __lowerCamelCase : str = feature_extractor(a , return_tensors='np' ).input_features __lowerCamelCase : List[Any] = feature_extractor(a , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(a , a ): self.assertTrue(np.allclose(a , a , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __lowerCamelCase : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] __lowerCamelCase : Tuple = np.asarray(a ) __lowerCamelCase : Any = feature_extractor(a , return_tensors='np' ).input_features __lowerCamelCase : Optional[Any] = feature_extractor(a , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(a , a ): self.assertTrue(np.allclose(a , a , atol=1e-3 ) ) # Test truncation required __lowerCamelCase : int = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __lowerCamelCase : Optional[Any] = [np.asarray(a ) for speech_input in speech_inputs] __lowerCamelCase : List[str] = [x[: feature_extractor.n_samples] for x in speech_inputs] __lowerCamelCase : str = [np.asarray(a ) for speech_input in speech_inputs_truncated] __lowerCamelCase : int = feature_extractor(a , return_tensors='np' ).input_features __lowerCamelCase : List[Any] = feature_extractor(a , return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(a , a ): self.assertTrue(np.allclose(a , a , atol=1e-3 ) ) def _snake_case ( self: Optional[int] ): import torch __lowerCamelCase : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCamelCase : Optional[int] = np.random.rand(100 , 32 ).astype(np.floataa ) __lowerCamelCase : Optional[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __lowerCamelCase : Optional[Any] = feature_extractor.pad([{'input_features': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __lowerCamelCase : Dict = feature_extractor.pad([{'input_features': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _snake_case ( self: Tuple , a: List[str] ): __lowerCamelCase : Dict = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech __lowerCamelCase : List[Any] = ds.sort('id' ).select(range(a ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def _snake_case ( self: Dict ): # fmt: off __lowerCamelCase : List[str] = torch.tensor( [ 0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1, 0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8, 0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4, -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4 ] ) # fmt: on __lowerCamelCase : Union[str, Any] = self._load_datasamples(1 ) __lowerCamelCase : str = WhisperFeatureExtractor() __lowerCamelCase : Dict = feature_extractor(a , return_tensors='pt' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , a , atol=1e-4 ) ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowerCamelCase : Optional[Any] = self._load_datasamples(1 )[0] __lowerCamelCase : Optional[Any] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue __lowerCamelCase : Optional[int] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=a )[0] self.assertTrue(np.all(np.mean(a ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a ) - 1 ) < 1e-3 ) )
669
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
1
import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument lowercase_ = { '/attention/': '/0/SelfAttention/', '/self_attention/': '/0/SelfAttention/', '/encoder_decoder_attention/': '/1/EncDecAttention/', 'value': 'v', 'query': 'q', 'key': 'k', 'out': 'o', 'pre_self_attention_layer_norm': '0/layer_norm', 'pre_cross_attention_layer_norm': '1/layer_norm', 'pre_attention_layer_norm': '0/layer_norm', # previously 1, but seems wrong 'token_embedder': 'shared', 'encoder_norm': 'final_layer_norm', 'decoder_norm': 'final_layer_norm', 'relpos_bias/rel_embedding': 'block/0/layer/0/SelfAttention/relative_attention_bias/weight', 'router/router_weights/w/': 'router/classifier/', 'roer/roer_weights/w/': 'router/classifier/', 'logits_dense': 'lm_head', } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): # 1. in HF T5, we have block.{x}.layer.{y}. which corresponds to layer.{x} in # the original model __lowerCamelCase : Union[str, Any] = list(s_dict.keys() ) for key in keys: __lowerCamelCase : List[Any] = r'.*/layers_(\d+)' __lowerCamelCase : Optional[int] = key if re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = re.sub(r'layers_(\d+)' , r'block/\1/layer' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = r'(encoder|decoder)\/' if re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).groups() if groups[0] == "encoder": __lowerCamelCase : Union[str, Any] = re.sub(r'/mlp/' , r'/1/mlp/' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = re.sub(r'/pre_mlp_layer_norm/' , r'/1/layer_norm/' , SCREAMING_SNAKE_CASE__ ) elif groups[0] == "decoder": __lowerCamelCase : List[str] = re.sub(r'/mlp/' , r'/2/mlp/' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = re.sub(r'/pre_mlp_layer_norm/' , r'/2/layer_norm/' , SCREAMING_SNAKE_CASE__ ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: __lowerCamelCase : Union[str, Any] = new_key.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'{key} -> {new_key}' ) __lowerCamelCase : str = s_dict.pop(SCREAMING_SNAKE_CASE__ ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: __lowerCamelCase : str = s_dict[ 'encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight' ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: __lowerCamelCase : Union[str, Any] = s_dict[ 'decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight' ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: __lowerCamelCase : Optional[int] = s_dict[key].shape[0] __lowerCamelCase : Any = s_dict[key] for idx in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = expert_weihts[idx] print(f'{key} -> {key.replace("expert/" , "nested fstring" )}' ) s_dict.pop(SCREAMING_SNAKE_CASE__ ) return s_dict lowercase_ = { 'NUM_ENCODER_LAYERS': 'num_layers', 'NUM_DECODER_LAYERS': 'num_decoder_layers', 'NUM_HEADS': 'num_heads', 'HEAD_DIM': 'd_kv', 'EMBED_DIM': 'd_model', 'MLP_DIM': 'd_ff', 'NUM_SELECTED_EXPERTS': 'num_selected_experts', 'NUM_ENCODER_SPARSE_LAYERS': 'num_sparse_encoder_layers', 'NUM_DECODER_SPARSE_LAYERS': 'num_sparse_decoder_layers', 'dense.MlpBlock.activations': 'feed_forward_proj', } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Convert a google style config to the hugging face fromat import regex as re with open(SCREAMING_SNAKE_CASE__ , 'r' ) as f: __lowerCamelCase : Any = f.read() __lowerCamelCase : str = re.findall(r'(.*) = ([0-9.]*)' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = {} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": __lowerCamelCase : List[str] = float(SCREAMING_SNAKE_CASE__ ) if '.' in value else int(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = re.findall(r'(.*activations) = \(\'(.*)\',\)' , SCREAMING_SNAKE_CASE__ )[0] __lowerCamelCase : int = str(activation[1] ) __lowerCamelCase : List[str] = num_experts __lowerCamelCase : Optional[Any] = SwitchTransformersConfig(**SCREAMING_SNAKE_CASE__ ) return config def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="./" , SCREAMING_SNAKE_CASE__=8 ): # Initialise PyTorch model print(f'Loading flax weights from : {flax_checkpoint_path}' ) __lowerCamelCase : Tuple = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE__ ) if gin_file is not None: __lowerCamelCase : Any = convert_gin_to_config(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : Any = SwitchTransformersConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = SwitchTransformersForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = flax_params['target'] __lowerCamelCase : Optional[int] = flatten_dict(SCREAMING_SNAKE_CASE__ , sep='/' ) __lowerCamelCase : List[str] = rename_keys(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = unflatten_dict(SCREAMING_SNAKE_CASE__ , sep='/' ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(f'Save PyTorch model to {pytorch_dump_path}' ) pt_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the' ' model architecture. If not provided, a `gin_file` has to be provided.' ), ) parser.add_argument( '--gin_file', default=None, type=str, required=False, help='Path to the gin config file. If not provided, a `config_file` has to be passed ', ) parser.add_argument( '--config_name', default=None, type=str, required=False, help='Config name of SwitchTransformers model.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output pytorch model.' ) parser.add_argument('--num_experts', default=8, type=int, required=False, help='Number of experts') lowercase_ = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
669
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
1
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowercase_ = logging.getLogger(__name__) @dataclass class A_ : '''simple docstring''' __snake_case = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) __snake_case = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) __snake_case = field(default=__UpperCamelCase , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class A_ : '''simple docstring''' __snake_case = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) __snake_case = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def UpperCamelCase__ ( ): # 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 : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : int = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ' --overwrite_output_dir to overcome.' ) __lowerCamelCase : List[Any] = import_module('tasks' ) try: __lowerCamelCase : Union[str, Any] = getattr(SCREAMING_SNAKE_CASE__ , model_args.task_type ) __lowerCamelCase : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' f'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , SCREAMING_SNAKE_CASE__ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __lowerCamelCase : Optional[int] = token_classification_task.get_labels(data_args.labels ) __lowerCamelCase : Dict[int, str] = dict(enumerate(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCamelCase : Tuple = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=SCREAMING_SNAKE_CASE__ , idalabel=SCREAMING_SNAKE_CASE__ , labelaid={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} , cache_dir=model_args.cache_dir , ) __lowerCamelCase : List[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 , use_fast=model_args.use_fast , ) __lowerCamelCase : List[Any] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE__ , cache_dir=model_args.cache_dir , ) # Get datasets __lowerCamelCase : str = ( TokenClassificationDataset( token_classification_task=SCREAMING_SNAKE_CASE__ , data_dir=data_args.data_dir , tokenizer=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __lowerCamelCase : Optional[int] = ( TokenClassificationDataset( token_classification_task=SCREAMING_SNAKE_CASE__ , data_dir=data_args.data_dir , tokenizer=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Tuple[List[int], List[int]]: __lowerCamelCase : Union[str, Any] = np.argmax(SCREAMING_SNAKE_CASE__ , axis=2 ) __lowerCamelCase , __lowerCamelCase : List[Any] = preds.shape __lowerCamelCase : int = [[] for _ in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase : Union[str, Any] = [[] for _ in range(SCREAMING_SNAKE_CASE__ )] for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(SCREAMING_SNAKE_CASE__ ) -> Dict: __lowerCamelCase , __lowerCamelCase : Optional[int] = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ), "precision": precision_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ), "recall": recall_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ), "f1": fa_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ), } # Data collator __lowerCamelCase : Optional[int] = DataCollatorWithPadding(SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __lowerCamelCase : List[Any] = Trainer( model=SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , compute_metrics=SCREAMING_SNAKE_CASE__ , data_collator=SCREAMING_SNAKE_CASE__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __lowerCamelCase : int = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __lowerCamelCase : Dict = trainer.evaluate() __lowerCamelCase : str = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) writer.write('%s = %s\n' % (key, value) ) results.update(SCREAMING_SNAKE_CASE__ ) # Predict if training_args.do_predict: __lowerCamelCase : Dict = TokenClassificationDataset( token_classification_task=SCREAMING_SNAKE_CASE__ , data_dir=data_args.data_dir , tokenizer=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = trainer.predict(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = align_predictions(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) writer.write('%s = %s\n' % (key, value) ) # Save predictions __lowerCamelCase : str = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return results def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
669
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Any = tempfile.mkdtemp() # fmt: off __lowerCamelCase : str = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __lowerCamelCase : Optional[Any] = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : Dict = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __lowerCamelCase : List[str] = {'unk_token': '<unk>'} __lowerCamelCase : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) __lowerCamelCase : Tuple = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __lowerCamelCase : Tuple = os.path.join(self.tmpdirname , a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(a , a ) def _snake_case ( self: int , **a: Optional[Any] ): return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[Any] , **a: List[str] ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Any , **a: Optional[int] ): return CLIPImageProcessor.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: int ): shutil.rmtree(self.tmpdirname ) def _snake_case ( self: Dict ): __lowerCamelCase : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __lowerCamelCase : Union[str, Any] = [Image.fromarray(np.moveaxis(a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.get_tokenizer() __lowerCamelCase : Optional[int] = self.get_rust_tokenizer() __lowerCamelCase : Optional[Any] = self.get_image_processor() __lowerCamelCase : Optional[int] = CLIPProcessor(tokenizer=a , image_processor=a ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[int] = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=a ) __lowerCamelCase : int = CLIPProcessor(tokenizer=a , image_processor=a ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCamelCase : Union[str, Any] = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , a ) self.assertIsInstance(processor_fast.tokenizer , a ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , a ) self.assertIsInstance(processor_fast.image_processor , a ) def _snake_case ( self: int ): __lowerCamelCase : Any = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase : List[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __lowerCamelCase : str = self.get_image_processor(do_normalize=a , padding_value=1.0 ) __lowerCamelCase : Optional[int] = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , a ) def _snake_case ( self: Any ): __lowerCamelCase : str = self.get_image_processor() __lowerCamelCase : str = self.get_tokenizer() __lowerCamelCase : Optional[int] = CLIPProcessor(tokenizer=a , image_processor=a ) __lowerCamelCase : str = self.prepare_image_inputs() __lowerCamelCase : Dict = image_processor(a , return_tensors='np' ) __lowerCamelCase : Optional[Any] = processor(images=a , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.get_image_processor() __lowerCamelCase : str = self.get_tokenizer() __lowerCamelCase : int = CLIPProcessor(tokenizer=a , image_processor=a ) __lowerCamelCase : Any = 'lower newer' __lowerCamelCase : List[str] = processor(text=a ) __lowerCamelCase : int = tokenizer(a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self: int ): __lowerCamelCase : int = self.get_image_processor() __lowerCamelCase : Any = self.get_tokenizer() __lowerCamelCase : List[str] = CLIPProcessor(tokenizer=a , image_processor=a ) __lowerCamelCase : int = 'lower newer' __lowerCamelCase : int = self.prepare_image_inputs() __lowerCamelCase : Any = processor(text=a , images=a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(a ): processor() def _snake_case ( self: List[Any] ): __lowerCamelCase : List[Any] = self.get_image_processor() __lowerCamelCase : int = self.get_tokenizer() __lowerCamelCase : Dict = CLIPProcessor(tokenizer=a , image_processor=a ) __lowerCamelCase : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCamelCase : Optional[int] = processor.batch_decode(a ) __lowerCamelCase : List[Any] = tokenizer.batch_decode(a ) self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : List[str] = self.get_image_processor() __lowerCamelCase : Any = self.get_tokenizer() __lowerCamelCase : Tuple = CLIPProcessor(tokenizer=a , image_processor=a ) __lowerCamelCase : List[str] = 'lower newer' __lowerCamelCase : List[Any] = self.prepare_image_inputs() __lowerCamelCase : Tuple = processor(text=a , images=a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
669
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
1
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor lowercase_ = logging.get_logger(__name__) class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: Any , *a: Union[str, Any] , **a: int ): warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.' , a , ) super().__init__(*a , **a )
669
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
1
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller lowercase_ = 3 def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): print('Generating primitive root of p' ) while True: __lowerCamelCase : Optional[int] = random.randrange(3 , SCREAMING_SNAKE_CASE__ ) if pow(SCREAMING_SNAKE_CASE__ , 2 , SCREAMING_SNAKE_CASE__ ) == 1: continue if pow(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) == 1: continue return g def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): print('Generating prime p...' ) __lowerCamelCase : Optional[Any] = rabin_miller.generate_large_prime(SCREAMING_SNAKE_CASE__ ) # select large prime number. __lowerCamelCase : Tuple = primitive_root(SCREAMING_SNAKE_CASE__ ) # one primitive root on modulo p. __lowerCamelCase : List[str] = random.randrange(3 , SCREAMING_SNAKE_CASE__ ) # private_key -> have to be greater than 2 for safety. __lowerCamelCase : Optional[Any] = cryptomath.find_mod_inverse(pow(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = (key_size, e_a, e_a, p) __lowerCamelCase : Optional[int] = (key_size, d) return public_key, private_key def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if os.path.exists(f'{name}_pubkey.txt' ) or os.path.exists(f'{name}_privkey.txt' ): print('\nWARNING:' ) print( f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' 'Use a different name or delete these files and re-run this program.' ) sys.exit() __lowerCamelCase , __lowerCamelCase : int = generate_key(SCREAMING_SNAKE_CASE__ ) print(f'\nWriting public key to file {name}_pubkey.txt...' ) with open(f'{name}_pubkey.txt' , 'w' ) as fo: fo.write(f'{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}' ) print(f'Writing private key to file {name}_privkey.txt...' ) with open(f'{name}_privkey.txt' , 'w' ) as fo: fo.write(f'{private_key[0]},{private_key[1]}' ) def UpperCamelCase__ ( ): print('Making key files...' ) make_key_files('elgamal' , 2_048 ) print('Key files generation successful' ) if __name__ == "__main__": main()
669
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : Any = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(a ) conf_scores.append(a ) return dec_strs, conf_scores def _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
1
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=1e-12 ): __lowerCamelCase : Dict = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(SCREAMING_SNAKE_CASE__ , axis=1 ) , a_min=SCREAMING_SNAKE_CASE__ ) ).T __lowerCamelCase : Dict = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(SCREAMING_SNAKE_CASE__ , axis=1 ) , a_min=SCREAMING_SNAKE_CASE__ ) ).T return jnp.matmul(SCREAMING_SNAKE_CASE__ , norm_emb_a.T ) class A_ ( nn.Module ): '''simple docstring''' __snake_case = 42 __snake_case = jnp.floataa def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[int] = FlaxCLIPVisionModule(self.config.vision_config ) __lowerCamelCase : str = nn.Dense(self.config.projection_dim , use_bias=a , dtype=self.dtype ) __lowerCamelCase : str = self.param('concept_embeds' , jax.nn.initializers.ones , (17, self.config.projection_dim) ) __lowerCamelCase : Tuple = self.param( 'special_care_embeds' , jax.nn.initializers.ones , (3, self.config.projection_dim) ) __lowerCamelCase : Optional[Any] = self.param('concept_embeds_weights' , jax.nn.initializers.ones , (17,) ) __lowerCamelCase : Any = self.param('special_care_embeds_weights' , jax.nn.initializers.ones , (3,) ) def __call__( self: str , a: Optional[Any] ): __lowerCamelCase : Tuple = self.vision_model(a )[1] __lowerCamelCase : Union[str, Any] = self.visual_projection(a ) __lowerCamelCase : List[str] = jax_cosine_distance(a , self.special_care_embeds ) __lowerCamelCase : Optional[int] = jax_cosine_distance(a , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs __lowerCamelCase : Any = 0.0 __lowerCamelCase : Tuple = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment __lowerCamelCase : Tuple = jnp.round(a , 3 ) __lowerCamelCase : Dict = jnp.any(special_scores > 0 , axis=1 , keepdims=a ) # Use a lower threshold if an image has any special care concept __lowerCamelCase : Tuple = is_special_care * 0.0_1 __lowerCamelCase : Any = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment __lowerCamelCase : Dict = jnp.round(a , 3 ) __lowerCamelCase : Tuple = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = CLIPConfig __snake_case = """clip_input""" __snake_case = FlaxStableDiffusionSafetyCheckerModule def __init__( self: Optional[Any] , a: CLIPConfig , a: Optional[Tuple] = None , a: int = 0 , a: jnp.dtype = jnp.floataa , a: bool = True , **a: List[str] , ): if input_shape is None: __lowerCamelCase : int = (1, 224, 224, 3) __lowerCamelCase : Optional[Any] = self.module_class(config=a , dtype=a , **a ) super().__init__(a , a , input_shape=a , seed=a , dtype=a , _do_init=_do_init ) def _snake_case ( self: List[str] , a: jax.random.KeyArray , a: Tuple , a: FrozenDict = None ): # init input tensor __lowerCamelCase : Optional[Any] = jax.random.normal(a , a ) __lowerCamelCase , __lowerCamelCase : Union[str, Any] = jax.random.split(a ) __lowerCamelCase : Dict = {'params': params_rng, 'dropout': dropout_rng} __lowerCamelCase : Optional[int] = self.module.init(a , a )['params'] return random_params def __call__( self: int , a: int , a: dict = None , ): __lowerCamelCase : Any = jnp.transpose(a , (0, 2, 3, 1) ) return self.module.apply( {'params': params or self.params} , jnp.array(a , dtype=jnp.floataa ) , rngs={} , )
669
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
1
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker lowercase_ = 'CompVis/stable-diffusion-v1-1' lowercase_ = 'CompVis/stable-diffusion-v1-2' lowercase_ = 'CompVis/stable-diffusion-v1-3' lowercase_ = 'CompVis/stable-diffusion-v1-4' class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: List[str] , a: AutoencoderKL , a: CLIPTextModel , a: CLIPTokenizer , a: UNetaDConditionModel , a: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , a: StableDiffusionSafetyChecker , a: CLIPImageProcessor , a: bool = True , ): super()._init_() __lowerCamelCase : Dict = StableDiffusionPipeline.from_pretrained(a ) __lowerCamelCase : List[Any] = StableDiffusionPipeline.from_pretrained(a ) __lowerCamelCase : Optional[Any] = StableDiffusionPipeline.from_pretrained(a ) __lowerCamelCase : str = StableDiffusionPipeline( vae=a , text_encoder=a , tokenizer=a , unet=a , scheduler=a , safety_checker=a , feature_extractor=a , requires_safety_checker=a , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def _snake_case ( self: Dict ): return {k: getattr(self , a ) for k in self.config.keys() if not k.startswith('_' )} def _snake_case ( self: int , a: Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __lowerCamelCase : List[str] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(a ) def _snake_case ( self: str ): self.enable_attention_slicing(a ) @torch.no_grad() def _snake_case ( self: Dict , a: Union[str, List[str]] , a: int = 512 , a: int = 512 , a: int = 50 , a: float = 7.5 , a: Optional[Union[str, List[str]]] = None , a: Optional[int] = 1 , a: float = 0.0 , a: Optional[torch.Generator] = None , a: Optional[torch.FloatTensor] = None , a: Optional[str] = "pil" , a: bool = True , a: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , a: int = 1 , **a: str , ): return self.pipea( prompt=a , height=a , width=a , num_inference_steps=a , guidance_scale=a , negative_prompt=a , num_images_per_prompt=a , eta=a , generator=a , latents=a , output_type=a , return_dict=a , callback=a , callback_steps=a , **a , ) @torch.no_grad() def _snake_case ( self: Union[str, Any] , a: Union[str, List[str]] , a: int = 512 , a: int = 512 , a: int = 50 , a: float = 7.5 , a: Optional[Union[str, List[str]]] = None , a: Optional[int] = 1 , a: float = 0.0 , a: Optional[torch.Generator] = None , a: Optional[torch.FloatTensor] = None , a: Optional[str] = "pil" , a: bool = True , a: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , a: int = 1 , **a: int , ): return self.pipea( prompt=a , height=a , width=a , num_inference_steps=a , guidance_scale=a , negative_prompt=a , num_images_per_prompt=a , eta=a , generator=a , latents=a , output_type=a , return_dict=a , callback=a , callback_steps=a , **a , ) @torch.no_grad() def _snake_case ( self: str , a: Union[str, List[str]] , a: int = 512 , a: int = 512 , a: int = 50 , a: float = 7.5 , a: Optional[Union[str, List[str]]] = None , a: Optional[int] = 1 , a: float = 0.0 , a: Optional[torch.Generator] = None , a: Optional[torch.FloatTensor] = None , a: Optional[str] = "pil" , a: bool = True , a: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , a: int = 1 , **a: List[Any] , ): return self.pipea( prompt=a , height=a , width=a , num_inference_steps=a , guidance_scale=a , negative_prompt=a , num_images_per_prompt=a , eta=a , generator=a , latents=a , output_type=a , return_dict=a , callback=a , callback_steps=a , **a , ) @torch.no_grad() def _snake_case ( self: List[str] , a: Union[str, List[str]] , a: int = 512 , a: int = 512 , a: int = 50 , a: float = 7.5 , a: Optional[Union[str, List[str]]] = None , a: Optional[int] = 1 , a: float = 0.0 , a: Optional[torch.Generator] = None , a: Optional[torch.FloatTensor] = None , a: Optional[str] = "pil" , a: bool = True , a: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , a: int = 1 , **a: int , ): return self.pipea( prompt=a , height=a , width=a , num_inference_steps=a , guidance_scale=a , negative_prompt=a , num_images_per_prompt=a , eta=a , generator=a , latents=a , output_type=a , return_dict=a , callback=a , callback_steps=a , **a , ) @torch.no_grad() def _snake_case ( self: Optional[Any] , a: Union[str, List[str]] , a: int = 512 , a: int = 512 , a: int = 50 , a: float = 7.5 , a: Optional[Union[str, List[str]]] = None , a: Optional[int] = 1 , a: float = 0.0 , a: Optional[torch.Generator] = None , a: Optional[torch.FloatTensor] = None , a: Optional[str] = "pil" , a: bool = True , a: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , a: int = 1 , **a: Optional[Any] , ): __lowerCamelCase : Dict = 'cuda' if torch.cuda.is_available() else 'cpu' self.to(a ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F'`height` and `width` must be divisible by 8 but are {height} and {width}.' ) # Get first result from Stable Diffusion Checkpoint v1.1 __lowerCamelCase : Union[str, Any] = self.textaimg_sda_a( prompt=a , height=a , width=a , num_inference_steps=a , guidance_scale=a , negative_prompt=a , num_images_per_prompt=a , eta=a , generator=a , latents=a , output_type=a , return_dict=a , callback=a , callback_steps=a , **a , ) # Get first result from Stable Diffusion Checkpoint v1.2 __lowerCamelCase : List[Any] = self.textaimg_sda_a( prompt=a , height=a , width=a , num_inference_steps=a , guidance_scale=a , negative_prompt=a , num_images_per_prompt=a , eta=a , generator=a , latents=a , output_type=a , return_dict=a , callback=a , callback_steps=a , **a , ) # Get first result from Stable Diffusion Checkpoint v1.3 __lowerCamelCase : Any = self.textaimg_sda_a( prompt=a , height=a , width=a , num_inference_steps=a , guidance_scale=a , negative_prompt=a , num_images_per_prompt=a , eta=a , generator=a , latents=a , output_type=a , return_dict=a , callback=a , callback_steps=a , **a , ) # Get first result from Stable Diffusion Checkpoint v1.4 __lowerCamelCase : Any = self.textaimg_sda_a( prompt=a , height=a , width=a , num_inference_steps=a , guidance_scale=a , negative_prompt=a , num_images_per_prompt=a , eta=a , generator=a , latents=a , output_type=a , return_dict=a , callback=a , callback_steps=a , **a , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
669
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
1
from manim import * class A_ ( __UpperCamelCase ): '''simple docstring''' def _snake_case ( self: List[str] ): __lowerCamelCase : str = Rectangle(height=0.5 , width=0.5 ) __lowerCamelCase : Tuple = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) __lowerCamelCase : Dict = Rectangle(height=0.2_5 , width=0.2_5 ) __lowerCamelCase : List[Any] = [mem.copy() for i in range(6 )] __lowerCamelCase : Union[str, Any] = [mem.copy() for i in range(6 )] __lowerCamelCase : Optional[int] = VGroup(*a ).arrange(a , buff=0 ) __lowerCamelCase : int = VGroup(*a ).arrange(a , buff=0 ) __lowerCamelCase : Union[str, Any] = VGroup(a , a ).arrange(a , buff=0 ) __lowerCamelCase : List[str] = Text('CPU' , font_size=24 ) __lowerCamelCase : Optional[Any] = Group(a , a ).arrange(a , buff=0.5 , aligned_edge=a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(a ) __lowerCamelCase : Any = [mem.copy() for i in range(4 )] __lowerCamelCase : Union[str, Any] = VGroup(*a ).arrange(a , buff=0 ) __lowerCamelCase : Optional[int] = Text('GPU' , font_size=24 ) __lowerCamelCase : Optional[Any] = Group(a , a ).arrange(a , buff=0.5 , aligned_edge=a ) gpu.move_to([-1, -1, 0] ) self.add(a ) __lowerCamelCase : Any = [mem.copy() for i in range(6 )] __lowerCamelCase : Dict = VGroup(*a ).arrange(a , buff=0 ) __lowerCamelCase : int = Text('Model' , font_size=24 ) __lowerCamelCase : Union[str, Any] = Group(a , a ).arrange(a , buff=0.5 , aligned_edge=a ) model.move_to([3, -1.0, 0] ) self.add(a ) __lowerCamelCase : List[str] = [] __lowerCamelCase : Dict = [] for i, rect in enumerate(a ): __lowerCamelCase : List[str] = fill.copy().set_fill(a , opacity=0.8 ) target.move_to(a ) model_arr.append(a ) __lowerCamelCase : str = Rectangle(height=0.4_6 , width=0.4_6 ).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 ) __lowerCamelCase : Optional[int] = [meta_mem.copy() for i in range(6 )] __lowerCamelCase : Optional[Any] = [meta_mem.copy() for i in range(6 )] __lowerCamelCase : Optional[int] = VGroup(*a ).arrange(a , buff=0 ) __lowerCamelCase : int = VGroup(*a ).arrange(a , buff=0 ) __lowerCamelCase : Optional[int] = VGroup(a , a ).arrange(a , buff=0 ) __lowerCamelCase : int = Text('Disk' , font_size=24 ) __lowerCamelCase : Dict = Group(a , a ).arrange(a , buff=0.5 , aligned_edge=a ) disk.move_to([-4, -1.2_5, 0] ) self.add(a , a ) __lowerCamelCase : str = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __lowerCamelCase : str = 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 ) __lowerCamelCase : Optional[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 ) __lowerCamelCase : Dict = 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 ) ) __lowerCamelCase : 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.0_2 ) self.play(MoveToTarget(a ) ) self.play(FadeOut(a ) ) __lowerCamelCase : str = 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] ) __lowerCamelCase : 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 ) ) __lowerCamelCase : List[Any] = {'run_time': 1, 'fade_in': True, 'fade_out': True, 'buff': 0.0_2} 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] ) ) __lowerCamelCase : List[str] = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.0_2 , a , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.0_2 ) __lowerCamelCase : str = 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: __lowerCamelCase : str = 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.0_2 , 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] ) ) __lowerCamelCase : Optional[Any] = a_c __lowerCamelCase : Dict = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.0_2 , buff=0.5 ) self.play( FadeOut(a ) , FadeOut(a , run_time=0.5 ) , ) __lowerCamelCase : int = 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()
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
1
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """Speech2TextFeatureExtractor""" __snake_case = """Speech2TextTokenizer""" def __init__( self: Union[str, Any] , a: List[Any] , a: str ): super().__init__(a , a ) __lowerCamelCase : Optional[int] = self.feature_extractor __lowerCamelCase : Optional[int] = False def __call__( self: Dict , *a: List[Any] , **a: Tuple ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a , **a ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) __lowerCamelCase : List[str] = kwargs.pop('raw_speech' ) else: __lowerCamelCase : Optional[int] = kwargs.pop('audio' , a ) __lowerCamelCase : Optional[Any] = kwargs.pop('sampling_rate' , a ) __lowerCamelCase : Optional[int] = kwargs.pop('text' , a ) if len(a ) > 0: __lowerCamelCase : List[str] = args[0] __lowerCamelCase : Optional[Any] = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: __lowerCamelCase : str = self.feature_extractor(a , *a , sampling_rate=a , **a ) if text is not None: __lowerCamelCase : Optional[int] = self.tokenizer(a , **a ) if text is None: return inputs elif audio is None: return encodings else: __lowerCamelCase : Any = encodings['input_ids'] return inputs def _snake_case ( self: Tuple , *a: Dict , **a: List[Any] ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Optional[Any] , *a: List[Any] , **a: Any ): return self.tokenizer.decode(*a , **a ) @contextmanager def _snake_case ( self: Optional[int] ): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) __lowerCamelCase : Optional[Any] = True __lowerCamelCase : Dict = self.tokenizer yield __lowerCamelCase : str = self.feature_extractor __lowerCamelCase : Optional[Any] = False
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
1
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
1
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = VQModel __snake_case = """sample""" @property def _snake_case ( self: Tuple , a: str=(32, 32) ): __lowerCamelCase : Tuple = 4 __lowerCamelCase : List[str] = 3 __lowerCamelCase : Optional[int] = floats_tensor((batch_size, num_channels) + sizes ).to(a ) return {"sample": image} @property def _snake_case ( self: str ): return (3, 32, 32) @property def _snake_case ( self: Optional[Any] ): return (3, 32, 32) def _snake_case ( self: Tuple ): __lowerCamelCase : Any = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } __lowerCamelCase : Dict = self.dummy_input return init_dict, inputs_dict def _snake_case ( self: int ): pass def _snake_case ( self: Any ): pass def _snake_case ( self: Tuple ): __lowerCamelCase , __lowerCamelCase : List[str] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=a ) self.assertIsNotNone(a ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(a ) __lowerCamelCase : Union[str, Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _snake_case ( self: int ): __lowerCamelCase : str = VQModel.from_pretrained('fusing/vqgan-dummy' ) model.to(a ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) __lowerCamelCase : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) __lowerCamelCase : List[Any] = image.to(a ) with torch.no_grad(): __lowerCamelCase : str = model(a ).sample __lowerCamelCase : Dict = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off __lowerCamelCase : str = torch.tensor([-0.0_1_5_3, -0.4_0_4_4, -0.1_8_8_0, -0.5_1_6_1, -0.2_4_1_8, -0.4_0_7_2, -0.1_6_1_2, -0.0_6_3_3, -0.0_1_4_3] ) # fmt: on self.assertTrue(torch.allclose(a , a , atol=1e-3 ) )
669
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { 'configuration_electra': ['ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ElectraConfig', 'ElectraOnnxConfig'], 'tokenization_electra': ['ElectraTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['ElectraTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '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: lowercase_ = [ '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: lowercase_ = [ '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 lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
669
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class A_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/config.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/config.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/config.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/config.json', 'bert-base-multilingual-uncased': 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json', 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/config.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/config.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-base-cased-finetuned-mrpc': 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json', 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json', 'bert-base-german-dbmdz-uncased': 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json', 'cl-tohoku/bert-base-japanese': 'https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json', 'cl-tohoku/bert-base-japanese-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json' ), 'wietsedv/bert-base-dutch-cased': 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json', # See all BERT models at https://huggingface.co/models?filter=bert } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """bert""" def __init__( self: Any , a: Tuple=3_0522 , a: Tuple=768 , a: int=12 , a: Tuple=12 , a: str=3072 , a: Optional[Any]="gelu" , a: Any=0.1 , a: str=0.1 , a: Union[str, Any]=512 , a: Union[str, Any]=2 , a: Optional[Any]=0.0_2 , a: int=1e-12 , a: Any=0 , a: List[Any]="absolute" , a: str=True , a: Optional[Any]=None , **a: List[Any] , ): super().__init__(pad_token_id=a , **a ) __lowerCamelCase : Any = vocab_size __lowerCamelCase : Tuple = hidden_size __lowerCamelCase : Any = num_hidden_layers __lowerCamelCase : Optional[int] = num_attention_heads __lowerCamelCase : Tuple = hidden_act __lowerCamelCase : Optional[Any] = intermediate_size __lowerCamelCase : List[str] = hidden_dropout_prob __lowerCamelCase : Dict = attention_probs_dropout_prob __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : int = type_vocab_size __lowerCamelCase : Optional[int] = initializer_range __lowerCamelCase : Dict = layer_norm_eps __lowerCamelCase : Dict = position_embedding_type __lowerCamelCase : Union[str, Any] = use_cache __lowerCamelCase : Optional[Any] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Dict ): if self.task == "multiple-choice": __lowerCamelCase : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
1
import sys def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [[0 for x in range(SCREAMING_SNAKE_CASE__ )] for x in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase : List[str] = [[0 for x in range(SCREAMING_SNAKE_CASE__ )] for x in range(SCREAMING_SNAKE_CASE__ )] for chain_length in range(2 , SCREAMING_SNAKE_CASE__ ): for a in range(1 , n - chain_length + 1 ): __lowerCamelCase : List[Any] = a + chain_length - 1 __lowerCamelCase : Optional[int] = sys.maxsize for c in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: __lowerCamelCase : Union[str, Any] = cost __lowerCamelCase : List[str] = c return matrix, sol def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if i == j: print('A' + str(SCREAMING_SNAKE_CASE__ ) , end=' ' ) else: print('(' , end=' ' ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , optimal_solution[i][j] ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , optimal_solution[i][j] + 1 , SCREAMING_SNAKE_CASE__ ) print(')' , end=' ' ) def UpperCamelCase__ ( ): __lowerCamelCase : Dict = [30, 35, 15, 5, 10, 20, 25] __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__ ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 __lowerCamelCase , __lowerCamelCase : List[str] = matrix_chain_order(SCREAMING_SNAKE_CASE__ ) print('No. of Operation required: ' + str(matrix[1][n - 1] ) ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , 1 , n - 1 ) if __name__ == "__main__": main()
669
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
1
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Initialise PyTorch model __lowerCamelCase : Dict = BertConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print(f'Building PyTorch model from configuration: {config}' ) __lowerCamelCase : Union[str, Any] = BertForPreTraining(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint load_tf_weights_in_bert(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--bert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) lowercase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
669
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( 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 , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
1
import unittest from knapsack import knapsack as k class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Union[str, Any] = [0] __lowerCamelCase : Tuple = [0] __lowerCamelCase : Any = len(a ) self.assertEqual(k.knapsack(a , a , a , a ) , 0 ) __lowerCamelCase : Dict = [60] __lowerCamelCase : Dict = [10] __lowerCamelCase : List[Any] = len(a ) self.assertEqual(k.knapsack(a , a , a , a ) , 0 ) def _snake_case ( self: Any ): __lowerCamelCase : List[Any] = 3 __lowerCamelCase : Any = [1, 2, 3] __lowerCamelCase : str = [3, 2, 1] __lowerCamelCase : List[Any] = len(a ) self.assertEqual(k.knapsack(a , a , a , a ) , 5 ) def _snake_case ( self: str ): __lowerCamelCase : Union[str, Any] = 50 __lowerCamelCase : int = [60, 100, 120] __lowerCamelCase : Dict = [10, 20, 30] __lowerCamelCase : Union[str, Any] = len(a ) self.assertEqual(k.knapsack(a , a , a , a ) , 220 ) if __name__ == "__main__": unittest.main()
669
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
1
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowercase_ = 'platform' import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , ): if attention_mask is None: __lowerCamelCase : Dict = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: __lowerCamelCase : Union[str, Any] = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: __lowerCamelCase : Optional[Any] = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __lowerCamelCase : List[str] = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __lowerCamelCase : int = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class A_ : '''simple docstring''' def __init__( self: Union[str, Any] , a: Optional[Any] , a: List[Any]=13 , a: Tuple=7 , a: Union[str, Any]=True , a: int=False , a: str=99 , a: str=16 , a: List[Any]=2 , a: Union[str, Any]=4 , a: Optional[Any]=4 , a: List[Any]="gelu" , a: Any=0.1 , a: Dict=0.1 , a: int=32 , a: Any=2 , a: List[str]=1 , a: Any=0 , a: Optional[int]=0.0_2 , ): __lowerCamelCase : Union[str, Any] = parent __lowerCamelCase : Tuple = batch_size __lowerCamelCase : str = seq_length __lowerCamelCase : Dict = is_training __lowerCamelCase : Dict = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : int = num_attention_heads __lowerCamelCase : Optional[Any] = intermediate_size __lowerCamelCase : Optional[Any] = hidden_act __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : List[str] = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Optional[Any] = eos_token_id __lowerCamelCase : Optional[Any] = pad_token_id __lowerCamelCase : int = bos_token_id __lowerCamelCase : Optional[Any] = initializer_range def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) __lowerCamelCase : List[Any] = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) __lowerCamelCase : List[Any] = shift_tokens_right(a , 1 , 2 ) __lowerCamelCase : Optional[int] = BlenderbotConfig( 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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=a , ) __lowerCamelCase : Tuple = prepare_blenderbot_inputs_dict(a , a , a ) return config, inputs_dict def _snake_case ( self: Optional[int] ): __lowerCamelCase , __lowerCamelCase : str = self.prepare_config_and_inputs() return config, inputs_dict def _snake_case ( self: Tuple , a: Tuple , a: Optional[Any] , a: Dict ): __lowerCamelCase : Dict = 20 __lowerCamelCase : Dict = model_class_name(a ) __lowerCamelCase : Tuple = model.encode(inputs_dict['input_ids'] ) __lowerCamelCase , __lowerCamelCase : List[str] = ( inputs_dict['decoder_input_ids'], inputs_dict['decoder_attention_mask'], ) __lowerCamelCase : Tuple = model.init_cache(decoder_input_ids.shape[0] , a , a ) __lowerCamelCase : Union[str, Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='i4' ) __lowerCamelCase : Optional[int] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __lowerCamelCase : str = model.decode( decoder_input_ids[:, :-1] , a , decoder_attention_mask=a , past_key_values=a , decoder_position_ids=a , ) __lowerCamelCase : Optional[Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCamelCase : int = model.decode( decoder_input_ids[:, -1:] , a , decoder_attention_mask=a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=a , ) __lowerCamelCase : Dict = model.decode(a , a ) __lowerCamelCase : Optional[int] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F'Max diff is {diff}' ) def _snake_case ( self: List[str] , a: Any , a: Union[str, Any] , a: Union[str, Any] ): __lowerCamelCase : Any = 20 __lowerCamelCase : List[str] = model_class_name(a ) __lowerCamelCase : Tuple = model.encode(inputs_dict['input_ids'] ) __lowerCamelCase , __lowerCamelCase : Dict = ( inputs_dict['decoder_input_ids'], inputs_dict['decoder_attention_mask'], ) __lowerCamelCase : Tuple = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __lowerCamelCase : Any = model.init_cache(decoder_input_ids.shape[0] , a , a ) __lowerCamelCase : Optional[Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __lowerCamelCase : int = model.decode( decoder_input_ids[:, :-1] , a , decoder_attention_mask=a , past_key_values=a , decoder_position_ids=a , ) __lowerCamelCase : Tuple = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4' ) __lowerCamelCase : str = model.decode( decoder_input_ids[:, -1:] , a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=a , decoder_position_ids=a , ) __lowerCamelCase : Optional[int] = model.decode(a , a , decoder_attention_mask=a ) __lowerCamelCase : Dict = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F'Max diff is {diff}' ) @require_flax class A_ ( unittest.TestCase ): '''simple docstring''' __snake_case = 99 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) __lowerCamelCase : Union[str, Any] = input_ids.shape[0] __lowerCamelCase : Union[str, Any] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def _snake_case ( self: Optional[int] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._get_config_and_data() __lowerCamelCase : List[Any] = FlaxBlenderbotForConditionalGeneration(a ) __lowerCamelCase : Optional[Any] = lm_model(input_ids=a ) __lowerCamelCase : Optional[Any] = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['logits'].shape , a ) def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) __lowerCamelCase : Any = FlaxBlenderbotForConditionalGeneration(a ) __lowerCamelCase : Dict = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) __lowerCamelCase : Any = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) __lowerCamelCase : Optional[int] = lm_model(input_ids=a , decoder_input_ids=a ) __lowerCamelCase : List[Any] = (*summary.shape, config.vocab_size) self.assertEqual(outputs['logits'].shape , a ) def _snake_case ( self: List[Any] ): __lowerCamelCase : Optional[Any] = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) __lowerCamelCase : List[str] = shift_tokens_right(a , 1 , 2 ) __lowerCamelCase : str = np.equal(a , 1 ).astype(np.floataa ).sum() __lowerCamelCase : int = np.equal(a , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(a , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class A_ ( __UpperCamelCase , unittest.TestCase , __UpperCamelCase ): '''simple docstring''' __snake_case = True __snake_case = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) __snake_case = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def _snake_case ( self: Any ): __lowerCamelCase : Union[str, Any] = FlaxBlenderbotModelTester(self ) def _snake_case ( self: List[str] ): __lowerCamelCase , __lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(a , a , a ) def _snake_case ( self: Tuple ): __lowerCamelCase , __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(a , a , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase , __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __lowerCamelCase : List[str] = self._prepare_for_class(a , a ) __lowerCamelCase : Union[str, Any] = model_class(a ) @jax.jit def encode_jitted(a: List[str] , a: Tuple=None , **a: Tuple ): return model.encode(input_ids=a , attention_mask=a ) with self.subTest('JIT Enabled' ): __lowerCamelCase : Tuple = encode_jitted(**a ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): __lowerCamelCase : List[str] = encode_jitted(**a ).to_tuple() self.assertEqual(len(a ) , len(a ) ) for jitted_output, output in zip(a , a ): self.assertEqual(jitted_output.shape , output.shape ) def _snake_case ( self: Tuple ): __lowerCamelCase , __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __lowerCamelCase : List[Any] = model_class(a ) __lowerCamelCase : Any = model.encode(inputs_dict['input_ids'] , inputs_dict['attention_mask'] ) __lowerCamelCase : List[Any] = { 'decoder_input_ids': inputs_dict['decoder_input_ids'], 'decoder_attention_mask': inputs_dict['decoder_attention_mask'], 'encoder_outputs': encoder_outputs, } @jax.jit def decode_jitted(a: List[str] , a: Any , a: int ): return model.decode( decoder_input_ids=a , decoder_attention_mask=a , encoder_outputs=a , ) with self.subTest('JIT Enabled' ): __lowerCamelCase : int = decode_jitted(**a ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): __lowerCamelCase : List[str] = decode_jitted(**a ).to_tuple() self.assertEqual(len(a ) , len(a ) ) for jitted_output, output in zip(a , a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def _snake_case ( self: Optional[Any] ): for model_class_name in self.all_model_classes: __lowerCamelCase : int = model_class_name.from_pretrained('facebook/blenderbot-400M-distill' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids __lowerCamelCase : Optional[Any] = np.ones((1, 1) ) * model.config.eos_token_id __lowerCamelCase : str = model(a ) self.assertIsNotNone(a ) @unittest.skipUnless(jax_device != 'cpu' , '3B test too slow on CPU.' ) @slow def _snake_case ( self: Tuple ): __lowerCamelCase : str = {'num_beams': 1, 'early_stopping': True, 'min_length': 15, 'max_length': 25} __lowerCamelCase : Optional[Any] = {'skip_special_tokens': True, 'clean_up_tokenization_spaces': True} __lowerCamelCase : Optional[int] = FlaxBlenderbotForConditionalGeneration.from_pretrained('facebook/blenderbot-3B' , from_pt=a ) __lowerCamelCase : Optional[Any] = BlenderbotTokenizer.from_pretrained('facebook/blenderbot-3B' ) __lowerCamelCase : Dict = ['Sam'] __lowerCamelCase : int = tokenizer(a , return_tensors='jax' ) __lowerCamelCase : Union[str, Any] = model.generate(**a , **a ) __lowerCamelCase : Any = 'Sam is a great name. It means "sun" in Gaelic.' __lowerCamelCase : Optional[int] = tokenizer.batch_decode(a , **a ) assert generated_txt[0].strip() == tgt_text
669
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
1
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = [ 'decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = emb.weight.shape __lowerCamelCase : List[str] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = emb.weight.data return lin_layer def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = torch.load(SCREAMING_SNAKE_CASE__ , map_location='cpu' ) __lowerCamelCase : Dict = Namespace(**checkpoint['cfg']['model'] ) __lowerCamelCase : Any = checkpoint['model'] remove_ignore_keys_(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = state_dict['decoder.embed_tokens.weight'].shape[0] __lowerCamelCase : int = {key.replace('decoder' , 'model' ): val for key, val in state_dict.items()} __lowerCamelCase : Dict = XGLMConfig( vocab_size=SCREAMING_SNAKE_CASE__ , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='gelu' , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) __lowerCamelCase : str = XGLMForCausalLM(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') lowercase_ = parser.parse_args() lowercase_ = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class A_ : '''simple docstring''' def __init__( self: Any , a: Tuple , a: int , a: int ): if dst_width < 0 or dst_height < 0: raise ValueError('Destination width/height should be > 0' ) __lowerCamelCase : List[Any] = img __lowerCamelCase : List[Any] = img.shape[1] __lowerCamelCase : Dict = img.shape[0] __lowerCamelCase : Optional[int] = dst_width __lowerCamelCase : Tuple = dst_height __lowerCamelCase : int = self.src_w / self.dst_w __lowerCamelCase : str = self.src_h / self.dst_h __lowerCamelCase : str = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255 ) def _snake_case ( self: int ): for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase : Any = self.img[self.get_y(a )][self.get_x(a )] def _snake_case ( self: List[Any] , a: int ): return int(self.ratio_x * x ) def _snake_case ( self: Tuple , a: int ): return int(self.ratio_y * y ) if __name__ == "__main__": lowercase_ ,lowercase_ = 8_0_0, 6_0_0 lowercase_ = imread('image_data/lena.jpg', 1) lowercase_ = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F"""Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}""", n.output ) waitKey(0) destroyAllWindows()
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: Optional[int] , a: Optional[int] , a: List[Any] , a: Union[str, Any]=1024 , a: Optional[int]=1024 , a: Optional[Any]=3.6 ): __lowerCamelCase : Optional[Any] = tokenizer __lowerCamelCase : int = tokenizer.bos_token_id __lowerCamelCase : Union[str, Any] = dataset __lowerCamelCase : List[str] = seq_length __lowerCamelCase : Optional[int] = seq_length * chars_per_token * num_of_sequences def __iter__( self: str ): __lowerCamelCase : Optional[Any] = iter(self.dataset ) __lowerCamelCase : Tuple = True while more_examples: __lowerCamelCase , __lowerCamelCase : Union[str, Any] = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(a )['content'] ) buffer_len += len(buffer[-1] ) except StopIteration: __lowerCamelCase : str = False break __lowerCamelCase : Optional[int] = tokenizer(a , truncation=a )['input_ids'] __lowerCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(a ) , self.seq_length ): __lowerCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(a ) == self.seq_length: yield torch.tensor(a ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = {'streaming': True} __lowerCamelCase : Optional[int] = load_dataset(args.dataset_name , split='train' , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = ConstantLengthDataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , seq_length=args.seq_length ) __lowerCamelCase : Union[str, Any] = DataLoader(SCREAMING_SNAKE_CASE__ , batch_size=args.batch_size ) return eval_dataloader def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): model.eval() __lowerCamelCase : Optional[Any] = [] for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): with torch.no_grad(): __lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(SCREAMING_SNAKE_CASE__ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __lowerCamelCase : List[str] = torch.mean(torch.cat(SCREAMING_SNAKE_CASE__ ) ) try: __lowerCamelCase : List[str] = torch.exp(SCREAMING_SNAKE_CASE__ ) except OverflowError: __lowerCamelCase : int = float('inf' ) return loss.item(), perplexity.item() # Setup Accelerator lowercase_ = Accelerator() # Parse configuration lowercase_ = HfArgumentParser(EvaluationArguments) lowercase_ = parser.parse_args() set_seed(args.seed) # Logging lowercase_ = logging.getLogger(__name__) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) # Load model and tokenizer lowercase_ = AutoModelForCausalLM.from_pretrained(args.model_ckpt) lowercase_ = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader lowercase_ = create_dataloader(args) # Prepare everything with our `accelerator`. lowercase_ ,lowercase_ = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('Evaluating and saving model after training') lowercase_ ,lowercase_ = evaluate(args) logger.info(F"""loss/eval: {eval_loss}, perplexity: {perplexity}""")
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (UniPCMultistepScheduler,) __snake_case = (("""num_inference_steps""", 25),) def _snake_case ( self: int , **a: Tuple ): __lowerCamelCase : int = { 'num_train_timesteps': 1000, 'beta_start': 0.0_0_0_1, 'beta_end': 0.0_2, 'beta_schedule': 'linear', 'solver_order': 2, 'solver_type': 'bh2', } config.update(**a ) return config def _snake_case ( self: Any , a: Optional[int]=0 , **a: List[Any] ): __lowerCamelCase : Optional[Any] = dict(self.forward_default_kwargs ) __lowerCamelCase : Any = kwargs.pop('num_inference_steps' , a ) __lowerCamelCase : int = self.dummy_sample __lowerCamelCase : Optional[Any] = 0.1 * sample __lowerCamelCase : str = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: __lowerCamelCase : int = self.get_scheduler_config(**a ) __lowerCamelCase : int = scheduler_class(**a ) scheduler.set_timesteps(a ) # copy over dummy past residuals __lowerCamelCase : Union[str, Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a ) __lowerCamelCase : Optional[Any] = scheduler_class.from_pretrained(a ) new_scheduler.set_timesteps(a ) # copy over dummy past residuals __lowerCamelCase : str = dummy_past_residuals[: new_scheduler.config.solver_order] __lowerCamelCase , __lowerCamelCase : Tuple = sample, sample for t in range(a , time_step + scheduler.config.solver_order + 1 ): __lowerCamelCase : str = scheduler.step(a , a , a , **a ).prev_sample __lowerCamelCase : Union[str, Any] = new_scheduler.step(a , a , a , **a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _snake_case ( self: int , a: Optional[Any]=0 , **a: Tuple ): __lowerCamelCase : Optional[Any] = dict(self.forward_default_kwargs ) __lowerCamelCase : Dict = kwargs.pop('num_inference_steps' , a ) __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : Any = 0.1 * sample __lowerCamelCase : Any = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: __lowerCamelCase : str = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) scheduler.set_timesteps(a ) # copy over dummy past residuals (must be after setting timesteps) __lowerCamelCase : Dict = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a ) __lowerCamelCase : str = scheduler_class.from_pretrained(a ) # copy over dummy past residuals new_scheduler.set_timesteps(a ) # copy over dummy past residual (must be after setting timesteps) __lowerCamelCase : int = dummy_past_residuals[: new_scheduler.config.solver_order] __lowerCamelCase : List[Any] = scheduler.step(a , a , a , **a ).prev_sample __lowerCamelCase : List[str] = new_scheduler.step(a , a , a , **a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _snake_case ( self: Tuple , a: Union[str, Any]=None , **a: Dict ): if scheduler is None: __lowerCamelCase : str = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config(**a ) __lowerCamelCase : Optional[Any] = scheduler_class(**a ) __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[int] = self.get_scheduler_config(**a ) __lowerCamelCase : Optional[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = 10 __lowerCamelCase : Dict = self.dummy_model() __lowerCamelCase : List[str] = self.dummy_sample_deter scheduler.set_timesteps(a ) for i, t in enumerate(scheduler.timesteps ): __lowerCamelCase : Optional[int] = model(a , a ) __lowerCamelCase : Tuple = scheduler.step(a , a , a ).prev_sample return sample def _snake_case ( self: Optional[Any] ): __lowerCamelCase : List[str] = dict(self.forward_default_kwargs ) __lowerCamelCase : Tuple = kwargs.pop('num_inference_steps' , a ) for scheduler_class in self.scheduler_classes: __lowerCamelCase : List[str] = self.get_scheduler_config() __lowerCamelCase : Any = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = self.dummy_sample __lowerCamelCase : Optional[Any] = 0.1 * sample if num_inference_steps is not None and hasattr(a , 'set_timesteps' ): scheduler.set_timesteps(a ) elif num_inference_steps is not None and not hasattr(a , 'set_timesteps' ): __lowerCamelCase : Dict = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __lowerCamelCase : Any = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] __lowerCamelCase : Any = dummy_past_residuals[: scheduler.config.solver_order] __lowerCamelCase : str = scheduler.timesteps[5] __lowerCamelCase : List[str] = scheduler.timesteps[6] __lowerCamelCase : Dict = scheduler.step(a , a , a , **a ).prev_sample __lowerCamelCase : str = scheduler.step(a , a , a , **a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: List[Any] ): # make sure that iterating over schedulers with same config names gives same results # for defaults __lowerCamelCase : List[Any] = UniPCMultistepScheduler(**self.get_scheduler_config() ) __lowerCamelCase : int = self.full_loop(scheduler=a ) __lowerCamelCase : Tuple = torch.mean(torch.abs(a ) ) assert abs(result_mean.item() - 0.2_4_6_4 ) < 1e-3 __lowerCamelCase : int = DPMSolverSinglestepScheduler.from_config(scheduler.config ) __lowerCamelCase : Tuple = DEISMultistepScheduler.from_config(scheduler.config ) __lowerCamelCase : Any = DPMSolverMultistepScheduler.from_config(scheduler.config ) __lowerCamelCase : List[Any] = UniPCMultistepScheduler.from_config(scheduler.config ) __lowerCamelCase : List[Any] = self.full_loop(scheduler=a ) __lowerCamelCase : List[Any] = torch.mean(torch.abs(a ) ) assert abs(result_mean.item() - 0.2_4_6_4 ) < 1e-3 def _snake_case ( self: Tuple ): for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[Any] ): self.check_over_configs(thresholding=a ) for order in [1, 2, 3]: for solver_type in ["bh1", "bh2"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=a , prediction_type=a , sample_max_value=a , solver_order=a , solver_type=a , ) def _snake_case ( self: Optional[int] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a ) def _snake_case ( self: Optional[Any] ): for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=a , solver_type=a , prediction_type=a , ) __lowerCamelCase : Dict = self.full_loop( solver_order=a , solver_type=a , prediction_type=a , ) assert not torch.isnan(a ).any(), "Samples have nan numbers" def _snake_case ( self: Tuple ): self.check_over_configs(lower_order_final=a ) self.check_over_configs(lower_order_final=a ) def _snake_case ( self: Optional[int] ): for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=a , time_step=0 ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : str = self.full_loop() __lowerCamelCase : Union[str, Any] = torch.mean(torch.abs(a ) ) assert abs(result_mean.item() - 0.2_4_6_4 ) < 1e-3 def _snake_case ( self: Any ): __lowerCamelCase : List[str] = self.full_loop(prediction_type='v_prediction' ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_mean.item() - 0.1_0_1_4 ) < 1e-3 def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Dict = self.scheduler_classes[0] __lowerCamelCase : Optional[int] = self.get_scheduler_config(thresholding=a , dynamic_thresholding_ratio=0 ) __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : str = 10 __lowerCamelCase : List[str] = self.dummy_model() __lowerCamelCase : List[str] = self.dummy_sample_deter.half() scheduler.set_timesteps(a ) for i, t in enumerate(scheduler.timesteps ): __lowerCamelCase : List[str] = model(a , a ) __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample assert sample.dtype == torch.floataa def _snake_case ( self: List[str] , **a: List[Any] ): for scheduler_class in self.scheduler_classes: __lowerCamelCase : Optional[Any] = self.get_scheduler_config(**a ) __lowerCamelCase : List[Any] = scheduler_class(**a ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
669
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
import pprint import requests lowercase_ = 'https://zenquotes.io/api' def UpperCamelCase__ ( ): return requests.get(API_ENDPOINT_URL + '/today' ).json() def UpperCamelCase__ ( ): return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": lowercase_ = random_quotes() pprint.pprint(response)
669
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return "".join([hex(SCREAMING_SNAKE_CASE__ )[2:].zfill(2 ).upper() for byte in list(SCREAMING_SNAKE_CASE__ )] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(SCREAMING_SNAKE_CASE__ ) % 2) != 0: raise ValueError( 'Base16 encoded data is invalid:\nData does not have an even number of hex digits.' ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(SCREAMING_SNAKE_CASE__ ) <= set('0123456789ABCDEF' ): raise ValueError( 'Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters.' ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
669
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
1
import json import unittest import numpy as np from huggingface_hub import hf_hub_download 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 transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="shi-labs/oneformer_demo" ): with open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) , 'r' ) as f: __lowerCamelCase : List[str] = json.load(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = {} __lowerCamelCase : Dict = [] __lowerCamelCase : Any = [] for key, info in class_info.items(): __lowerCamelCase : List[Any] = info['name'] class_names.append(info['name'] ) if info["isthing"]: thing_ids.append(int(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Optional[Any] = thing_ids __lowerCamelCase : str = class_names return metadata class A_ ( unittest.TestCase ): '''simple docstring''' def __init__( self: int , a: Optional[Any] , a: Dict=7 , a: Optional[int]=3 , a: Dict=30 , a: Optional[Any]=400 , a: int=None , a: List[Any]=True , a: List[str]=True , a: List[Any]=[0.5, 0.5, 0.5] , a: Optional[Any]=[0.5, 0.5, 0.5] , a: Tuple=10 , a: Dict=False , a: Union[str, Any]=255 , a: Optional[Any]="shi-labs/oneformer_demo" , a: Optional[int]="ade20k_panoptic.json" , a: Dict=10 , ): __lowerCamelCase : Optional[Any] = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : str = num_channels __lowerCamelCase : Union[str, Any] = min_resolution __lowerCamelCase : int = max_resolution __lowerCamelCase : Union[str, Any] = do_resize __lowerCamelCase : int = {'shortest_edge': 32, 'longest_edge': 1333} if size is None else size __lowerCamelCase : Tuple = do_normalize __lowerCamelCase : List[Any] = image_mean __lowerCamelCase : str = image_std __lowerCamelCase : Any = class_info_file __lowerCamelCase : str = prepare_metadata(a , a ) __lowerCamelCase : Union[str, Any] = num_text __lowerCamelCase : Any = repo_path # for the post_process_functions __lowerCamelCase : int = 2 __lowerCamelCase : Optional[int] = 10 __lowerCamelCase : Tuple = 10 __lowerCamelCase : Optional[int] = 3 __lowerCamelCase : Dict = 4 __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : Optional[int] = do_reduce_labels __lowerCamelCase : List[str] = ignore_index def _snake_case ( self: Tuple ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def _snake_case ( self: Any , a: List[Any] , a: str=False ): if not batched: __lowerCamelCase : Union[str, Any] = image_inputs[0] if isinstance(a , Image.Image ): __lowerCamelCase , __lowerCamelCase : Tuple = image.size else: __lowerCamelCase , __lowerCamelCase : Tuple = image.shape[1], image.shape[2] if w < h: __lowerCamelCase : Optional[int] = int(self.size['shortest_edge'] * h / w ) __lowerCamelCase : Optional[Any] = self.size['shortest_edge'] elif w > h: __lowerCamelCase : List[str] = self.size['shortest_edge'] __lowerCamelCase : List[str] = int(self.size['shortest_edge'] * w / h ) else: __lowerCamelCase : List[str] = self.size['shortest_edge'] __lowerCamelCase : Tuple = self.size['shortest_edge'] else: __lowerCamelCase : List[str] = [] for image in image_inputs: __lowerCamelCase , __lowerCamelCase : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCamelCase : str = max(a , key=lambda a : item[0] )[0] __lowerCamelCase : str = max(a , key=lambda a : item[1] )[1] return expected_height, expected_width def _snake_case ( self: Union[str, Any] ): return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string __snake_case = image_processing_class def _snake_case ( self: int ): __lowerCamelCase : Tuple = OneFormerImageProcessorTester(self ) @property def _snake_case ( self: int ): return self.image_processing_tester.prepare_image_processor_dict() def _snake_case ( self: Optional[int] ): __lowerCamelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , 'image_mean' ) ) self.assertTrue(hasattr(a , 'image_std' ) ) self.assertTrue(hasattr(a , 'do_normalize' ) ) self.assertTrue(hasattr(a , 'do_resize' ) ) self.assertTrue(hasattr(a , 'size' ) ) self.assertTrue(hasattr(a , 'ignore_index' ) ) self.assertTrue(hasattr(a , 'class_info_file' ) ) self.assertTrue(hasattr(a , 'num_text' ) ) self.assertTrue(hasattr(a , 'repo_path' ) ) self.assertTrue(hasattr(a , 'metadata' ) ) self.assertTrue(hasattr(a , 'do_reduce_labels' ) ) def _snake_case ( self: int ): pass def _snake_case ( self: Any ): # Initialize image_processor __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase : Optional[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input __lowerCamelCase : Optional[Any] = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values __lowerCamelCase , __lowerCamelCase : List[str] = self.image_processing_tester.get_expected_values(a ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCamelCase , __lowerCamelCase : List[str] = self.image_processing_tester.get_expected_values(a , batched=a ) __lowerCamelCase : List[str] = image_processor( a , ['semantic'] * len(a ) , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def _snake_case ( self: int ): # Initialize image_processor __lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase : Optional[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input __lowerCamelCase : Tuple = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values __lowerCamelCase , __lowerCamelCase : List[Any] = self.image_processing_tester.get_expected_values(a ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processing_tester.get_expected_values(a , batched=a ) __lowerCamelCase : Tuple = image_processor( a , ['semantic'] * len(a ) , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def _snake_case ( self: Optional[int] ): # Initialize image_processor __lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase : Tuple = prepare_image_inputs(self.image_processing_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input __lowerCamelCase : Any = image_processor(image_inputs[0] , ['semantic'] , return_tensors='pt' ).pixel_values __lowerCamelCase , __lowerCamelCase : Optional[Any] = self.image_processing_tester.get_expected_values(a ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCamelCase , __lowerCamelCase : Tuple = self.image_processing_tester.get_expected_values(a , batched=a ) __lowerCamelCase : str = image_processor( a , ['semantic'] * len(a ) , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def _snake_case ( self: str , a: Optional[Any]=False , a: Any=False , a: Tuple="np" ): __lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # prepare image and target __lowerCamelCase : Optional[Any] = self.image_processing_tester.num_labels __lowerCamelCase : str = None __lowerCamelCase : Dict = None __lowerCamelCase : Dict = prepare_image_inputs(self.image_processing_tester , equal_resolution=a ) if with_segmentation_maps: __lowerCamelCase : List[str] = num_labels if is_instance_map: __lowerCamelCase : str = list(range(a ) ) * 2 __lowerCamelCase : Optional[int] = dict(enumerate(a ) ) __lowerCamelCase : str = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": __lowerCamelCase : Dict = [Image.fromarray(a ) for annotation in annotations] __lowerCamelCase : Dict = image_processor( a , ['semantic'] * len(a ) , a , return_tensors='pt' , instance_id_to_semantic_id=a , pad_and_return_pixel_mask=a , ) return inputs def _snake_case ( self: str ): pass def _snake_case ( self: int ): def common(a: str=False , a: Union[str, Any]=None ): __lowerCamelCase : Optional[Any] = self.comm_get_image_processor_inputs( with_segmentation_maps=a , is_instance_map=a , segmentation_type=a ) __lowerCamelCase : int = inputs['mask_labels'] __lowerCamelCase : Any = inputs['class_labels'] __lowerCamelCase : Optional[Any] = inputs['pixel_values'] __lowerCamelCase : str = inputs['text_inputs'] # check the batch_size for mask_label, class_label, text_input in zip(a , a , a ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(a ) , self.image_processing_tester.num_text ) common() common(is_instance_map=a ) common(is_instance_map=a , segmentation_type='pil' ) common(is_instance_map=a , segmentation_type='pil' ) def _snake_case ( self: Any ): __lowerCamelCase : Any = np.zeros((20, 50) ) __lowerCamelCase : int = 1 __lowerCamelCase : List[Any] = 1 __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Optional[Any] = binary_mask_to_rle(a ) self.assertEqual(len(a ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def _snake_case ( self: str ): __lowerCamelCase : Tuple = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) __lowerCamelCase : Any = self.image_processing_tester.get_fake_oneformer_outputs() __lowerCamelCase : Tuple = fature_extractor.post_process_semantic_segmentation(a ) self.assertEqual(len(a ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) __lowerCamelCase : Optional[Any] = [(1, 4) for i in range(self.image_processing_tester.batch_size )] __lowerCamelCase : Union[str, Any] = fature_extractor.post_process_semantic_segmentation(a , target_sizes=a ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def _snake_case ( self: Dict ): __lowerCamelCase : Optional[Any] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) __lowerCamelCase : str = self.image_processing_tester.get_fake_oneformer_outputs() __lowerCamelCase : Dict = image_processor.post_process_instance_segmentation(a , threshold=0 ) self.assertTrue(len(a ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue('segmentation' in el ) self.assertTrue('segments_info' in el ) self.assertEqual(type(el['segments_info'] ) , a ) self.assertEqual( el['segmentation'].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : List[str] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file='ade20k_panoptic.json' , num_text=self.image_processing_tester.num_text , repo_path='shi-labs/oneformer_demo' , ) __lowerCamelCase : str = self.image_processing_tester.get_fake_oneformer_outputs() __lowerCamelCase : Tuple = image_processor.post_process_panoptic_segmentation(a , threshold=0 ) self.assertTrue(len(a ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue('segmentation' in el ) self.assertTrue('segments_info' in el ) self.assertEqual(type(el['segments_info'] ) , a ) self.assertEqual( el['segmentation'].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
669
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
1
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
1
import random def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False ): __lowerCamelCase : dict = {i: [] for i in range(SCREAMING_SNAKE_CASE__ )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(SCREAMING_SNAKE_CASE__ ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE__ ): if random.random() < probability: graph[i].append(SCREAMING_SNAKE_CASE__ ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(SCREAMING_SNAKE_CASE__ ) return graph def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return { i: [j for j in range(SCREAMING_SNAKE_CASE__ ) if i != j] for i in range(SCREAMING_SNAKE_CASE__ ) } if __name__ == "__main__": import doctest doctest.testmod()
669
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
1
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = OpenAIGPTTokenizer __snake_case = OpenAIGPTTokenizerFast __snake_case = True __snake_case = False def _snake_case ( self: Any ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __lowerCamelCase : str = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] __lowerCamelCase : Union[str, Any] = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : Optional[int] = ['#version: 0.2', 'l o', 'lo w', 'e r</w>', ''] __lowerCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' ) as fp: fp.write(json.dumps(a ) ) with open(self.merges_file , 'w' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: List[str] , a: List[Any] ): return "lower newer", "lower newer" def _snake_case ( self: Tuple ): __lowerCamelCase : Dict = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) __lowerCamelCase : Dict = 'lower' __lowerCamelCase : Dict = ['low', 'er</w>'] __lowerCamelCase : Optional[Any] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : Tuple = tokens + ['<unk>'] __lowerCamelCase : Tuple = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) def _snake_case ( self: Dict , a: str=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[str] = self.rust_tokenizer_class.from_pretrained(a , **a ) # Simple input __lowerCamelCase : Union[str, Any] = 'This is a simple input' __lowerCamelCase : Optional[int] = ['This is a simple input 1', 'This is a simple input 2'] __lowerCamelCase : Dict = ('This is a simple input', 'This is a pair') __lowerCamelCase : Tuple = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(a , tokenizer_r.encode , a , max_length=a , padding='max_length' ) # Simple input self.assertRaises(a , tokenizer_r.encode_plus , a , max_length=a , padding='max_length' ) # Simple input self.assertRaises( a , tokenizer_r.batch_encode_plus , a , max_length=a , padding='max_length' , ) # Pair input self.assertRaises(a , tokenizer_r.encode , a , max_length=a , padding='max_length' ) # Pair input self.assertRaises(a , tokenizer_r.encode_plus , a , max_length=a , padding='max_length' ) # Pair input self.assertRaises( a , tokenizer_r.batch_encode_plus , a , max_length=a , padding='max_length' , ) def _snake_case ( self: Any ): pass @require_ftfy @require_spacy @require_tokenizers class A_ ( __UpperCamelCase ): '''simple docstring''' pass
669
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : Any = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.' ) if images is not None: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(a ) conf_scores.append(a ) return dec_strs, conf_scores def _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
1
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class A_ ( pl.LightningModule ): '''simple docstring''' def __init__( self: Optional[int] , a: List[str] ): super().__init__() __lowerCamelCase : Optional[Any] = model __lowerCamelCase : Optional[Any] = 2 __lowerCamelCase : Union[str, Any] = nn.Linear(self.model.config.hidden_size , self.num_labels ) def _snake_case ( self: Optional[Any] ): pass def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # load longformer model from model identifier __lowerCamelCase : str = LongformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = LightningModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[Any] = torch.load(SCREAMING_SNAKE_CASE__ , map_location=torch.device('cpu' ) ) lightning_model.load_state_dict(ckpt['state_dict'] ) # init longformer question answering model __lowerCamelCase : str = LongformerForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__ ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(f'Conversion successful. Model saved under {pytorch_dump_folder_path}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--longformer_model', default=None, type=str, required=True, help='model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.', ) parser.add_argument( '--longformer_question_answering_ckpt_path', default=None, type=str, required=True, help='Path the official PyTorch Lightning Checkpoint.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) lowercase_ = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
669
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
1
from abc import ABC, abstractmethod from argparse import ArgumentParser class A_ ( __UpperCamelCase ): '''simple docstring''' @staticmethod @abstractmethod def _snake_case ( a: ArgumentParser ): raise NotImplementedError() @abstractmethod def _snake_case ( self: List[str] ): raise NotImplementedError()
669
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
1