code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' def UpperCamelCase_( snake_case : int ): '''simple docstring''' if not isinstance(snake_case , snake_case ): raise ValueError("Input must be an integer" ) if input_num <= 0: raise ValueError("Input must be positive" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _SCREAMING_SNAKE_CASE : int = { "configuration_clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig", ], "processing_clip": ["CLIPProcessor"], "tokenization_clip": ["CLIPTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = ["CLIPTokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = ["CLIPFeatureExtractor"] _SCREAMING_SNAKE_CASE : Dict = ["CLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' import re def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$" ) if match := re.search(snake_case , snake_case ): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("+918827897895"))
85
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE : Union[str, Any] = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } _SCREAMING_SNAKE_CASE : int = { "gpt-neox-20b": 2048, } class _snake_case ( lowercase_ ): lowerCAmelCase_ : str = VOCAB_FILES_NAMES lowerCAmelCase_ : Tuple = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ : str = ["input_ids", "attention_mask"] def __init__( self , a__=None , a__=None , a__=None , a__="<|endoftext|>" , a__="<|endoftext|>" , a__="<|endoftext|>" , a__=False , **a__ , ) -> Tuple: '''simple docstring''' super().__init__( a__ , a__ , tokenizer_file=a__ , unk_token=a__ , bos_token=a__ , eos_token=a__ , add_prefix_space=a__ , **a__ , ) snake_case_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , a__ ) != add_prefix_space: snake_case_ = getattr(a__ , pre_tok_state.pop("type" ) ) snake_case_ = add_prefix_space snake_case_ = pre_tok_class(**a__ ) snake_case_ = add_prefix_space def lowerCAmelCase__ ( self , a__ , a__ = None ) -> Tuple[str]: '''simple docstring''' snake_case_ = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ ) def lowerCAmelCase__ ( self , a__ ) -> List[int]: '''simple docstring''' snake_case_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(a__ , add_special_tokens=a__ ) + [self.eos_token_id] ) if len(a__ ) > self.model_max_length: snake_case_ = input_ids[-self.model_max_length :] return input_ids
85
1
'''simple docstring''' from manim import * class _snake_case ( lowercase_ ): def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = Rectangle(height=0.5 , width=0.5 ) snake_case_ = Rectangle(height=0.2_5 , width=0.2_5 ) snake_case_ = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) snake_case_ = [mem.copy() for i in range(6 )] snake_case_ = [mem.copy() for i in range(6 )] snake_case_ = VGroup(*a__ ).arrange(a__ , buff=0 ) snake_case_ = VGroup(*a__ ).arrange(a__ , buff=0 ) snake_case_ = VGroup(a__ , a__ ).arrange(a__ , buff=0 ) snake_case_ = Text("CPU" , font_size=24 ) snake_case_ = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(a__ ) snake_case_ = [mem.copy() for i in range(4 )] snake_case_ = VGroup(*a__ ).arrange(a__ , buff=0 ) snake_case_ = Text("GPU" , font_size=24 ) snake_case_ = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) gpu.move_to([-1, -1, 0] ) self.add(a__ ) snake_case_ = [mem.copy() for i in range(6 )] snake_case_ = VGroup(*a__ ).arrange(a__ , buff=0 ) snake_case_ = Text("Model" , font_size=24 ) snake_case_ = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) model.move_to([3, -1.0, 0] ) self.add(a__ ) snake_case_ = [] snake_case_ = [] snake_case_ = [] for i, rect in enumerate(a__ ): rect.set_stroke(a__ ) snake_case_ = Rectangle(height=0.4_6 / 4 , width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(a__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=a__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=a__ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=a__ , buff=0.0 ) self.add(a__ ) model_cpu_arr.append(a__ ) self.add(*a__ , *a__ , *a__ ) snake_case_ = [mem.copy() for i in range(6 )] snake_case_ = VGroup(*a__ ).arrange(a__ , buff=0 ) snake_case_ = Text("Loaded Checkpoint" , font_size=24 ) snake_case_ = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) checkpoint.move_to([3, 0.5, 0] ) self.add(a__ ) snake_case_ = [] snake_case_ = [] for i, rect in enumerate(a__ ): snake_case_ = fill.copy().set_fill(a__ , opacity=0.7 ) target.move_to(a__ ) ckpt_arr.append(a__ ) snake_case_ = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(a__ ) self.add(*a__ , *a__ ) snake_case_ = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) snake_case_ = 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__ ) snake_case_ = 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__ ) snake_case_ = MarkupText( F'Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) snake_case_ = [meta_mem.copy() for i in range(6 )] snake_case_ = [meta_mem.copy() for i in range(6 )] snake_case_ = VGroup(*a__ ).arrange(a__ , buff=0 ) snake_case_ = VGroup(*a__ ).arrange(a__ , buff=0 ) snake_case_ = VGroup(a__ , a__ ).arrange(a__ , buff=0 ) snake_case_ = Text("Disk" , font_size=24 ) snake_case_ = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ ) disk.move_to([-4.0, -1.2_5, 0] ) self.play(Write(a__ , run_time=3 ) , Write(a__ , run_time=1 ) , Create(a__ , run_time=1 ) ) snake_case_ = [] for i, rect in enumerate(a__ ): snake_case_ = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(a__ , run_time=1.5 ) ) self.play(*a__ ) self.play(FadeOut(a__ ) ) snake_case_ = MarkupText(F'Then, the checkpoint is removed from memory\nthrough garbage collection.' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(a__ , run_time=3 ) ) self.play( FadeOut(a__ , a__ , *a__ , *a__ ) , ) self.wait()
85
'''simple docstring''' import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def UpperCamelCase_( snake_case : Tuple ): '''simple docstring''' snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = 0.01 with locka.acquire(): with pytest.raises(snake_case ): snake_case_ = time.time() locka.acquire(snake_case ) assert time.time() - _start > timeout def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = "a" * 1_0_0_0 + ".lock" snake_case_ = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(snake_case ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 snake_case_ = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case ): locka.acquire(0 )
85
1
'''simple docstring''' import json import sys def UpperCamelCase_( snake_case : List[Any] , snake_case : Tuple ): '''simple docstring''' with open(snake_case , encoding="utf-8" ) as f: snake_case_ = json.load(snake_case ) snake_case_ = ["<details>", "<summary>Show updated benchmarks!</summary>", " "] for benchmark_name in sorted(snake_case ): snake_case_ = results[benchmark_name] snake_case_ = benchmark_name.split("/" )[-1] output_md.append(f'### Benchmark: {benchmark_file_name}' ) snake_case_ = "| metric |" snake_case_ = "|--------|" snake_case_ = "| new / old (diff) |" for metric_name in sorted(snake_case ): snake_case_ = benchmark_res[metric_name] snake_case_ = metric_vals["new"] snake_case_ = metric_vals.get("old" , snake_case ) snake_case_ = metric_vals.get("diff" , snake_case ) snake_case_ = f' {new_val:f}' if isinstance(snake_case , (int, float) ) else "None" if old_val is not None: val_str += f' / {old_val:f}' if isinstance(snake_case , (int, float) ) else "None" if dif_val is not None: val_str += f' ({dif_val:f})' if isinstance(snake_case , (int, float) ) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append("</details>" ) with open(snake_case , "w" , encoding="utf-8" ) as f: f.writelines("\n".join(snake_case ) ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Tuple = sys.argv[1] _SCREAMING_SNAKE_CASE : Optional[int] = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _snake_case ( datasets.BuilderConfig ): lowerCAmelCase_ : Optional[datasets.Features] = None def UpperCamelCase_( snake_case : "pyspark.sql.DataFrame" , snake_case : List[int] , ): '''simple docstring''' import pyspark def generate_fn(): snake_case_ = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: snake_case_ = df_with_partition_id.select("*" ).where(f'part_id = {partition_id}' ).drop("part_id" ) snake_case_ = partition_df.collect() snake_case_ = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class _snake_case ( _BaseExamplesIterable ): def __init__( self , a__ , a__=None , ) -> Any: '''simple docstring''' snake_case_ = df snake_case_ = partition_order or range(self.df.rdd.getNumPartitions() ) snake_case_ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Union[str, Any]: '''simple docstring''' yield from self.generate_examples_fn() def lowerCAmelCase__ ( self , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = self.split_shard_indices_by_worker(a__ , a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) @property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return len(self.partition_order ) class _snake_case ( datasets.DatasetBuilder ): lowerCAmelCase_ : Dict = SparkConfig def __init__( self , a__ , a__ = None , a__ = None , **a__ , ) -> str: '''simple docstring''' import pyspark snake_case_ = pyspark.sql.SparkSession.builder.getOrCreate() snake_case_ = df snake_case_ = working_dir super().__init__( cache_dir=a__ , config_name=str(self.df.semanticHash() ) , **a__ , ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' def create_cache_and_write_probe(a__ ): # 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__ ) snake_case_ = 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: snake_case_ = ( 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 lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' import pyspark def get_arrow_batch_size(a__ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) snake_case_ = self.df.count() snake_case_ = 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. snake_case_ = ( 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 ) snake_case_ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. snake_case_ = min(a__ , int(approx_total_size / max_shard_size ) ) snake_case_ = self.df.repartition(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: '''simple docstring''' import pyspark snake_case_ = ParquetWriter if file_format == "parquet" else ArrowWriter snake_case_ = os.path.join(self._working_dir , os.path.basename(a__ ) ) if self._working_dir else fpath snake_case_ = 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. snake_case_ = self.config.features snake_case_ = self._writer_batch_size snake_case_ = self._fs.storage_options def write_arrow(a__ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. snake_case_ = pyspark.TaskContext().taskAttemptId() snake_case_ = 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"] , ) snake_case_ = 0 snake_case_ = 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__ , ) snake_case_ = 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: snake_case_ , snake_case_ = 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 snake_case_ = 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__ , ) snake_case_ = pa.Table.from_batches([batch] ) writer.write_table(a__ ) if writer._num_bytes > 0: snake_case_ , snake_case_ = 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__ ) ): snake_case_ = os.path.join(os.path.dirname(a__ ) , os.path.basename(a__ ) ) shutil.move(a__ , a__ ) snake_case_ = ( 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 lowerCAmelCase__ ( self , a__ , a__ = "arrow" , a__ = None , a__ = None , **a__ , ) -> int: '''simple docstring''' self._validate_cache_dir() snake_case_ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a__ ) snake_case_ = not is_remote_filesystem(self._fs ) snake_case_ = os.path.join if is_local else posixpath.join snake_case_ = "-TTTTT-SSSSS-of-NNNNN" snake_case_ = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' snake_case_ = path_join(self._output_dir , a__ ) snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = [] snake_case_ = [] for task_id, content in self._prepare_split_single(a__ , a__ , a__ ): ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = 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__ ) snake_case_ = total_num_examples snake_case_ = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: snake_case_ = 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. snake_case_ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a__ , a__ , a__ , ): 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}' ) , ) snake_case_ = [] snake_case_ = 0 for i in range(len(a__ ) ): snake_case_ , snake_case_ = 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 snake_case_ = 0 snake_case_ = 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 lowerCAmelCase__ ( self , a__ , ) -> SparkExamplesIterable: '''simple docstring''' return SparkExamplesIterable(self.df )
85
1
'''simple docstring''' import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu _SCREAMING_SNAKE_CASE : int = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: _SCREAMING_SNAKE_CASE : List[Any] = json.load(f) @require_torch class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self , a__ ) -> Dict: '''simple docstring''' return FSMTTokenizer.from_pretrained(a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' snake_case_ = FSMTForConditionalGeneration.from_pretrained(a__ ).to(a__ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 2_6.0], ["ru-en", 2_2.0], ["en-de", 2_2.0], ["de-en", 2_9.0], ] ) @slow def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = F'facebook/wmt19-{pair}' snake_case_ = self.get_tokenizer(a__ ) snake_case_ = self.get_model(a__ ) snake_case_ = bleu_data[pair]["src"] snake_case_ = bleu_data[pair]["tgt"] snake_case_ = tokenizer(a__ , return_tensors="pt" , truncation=a__ , padding="longest" ).to(a__ ) snake_case_ = model.generate( input_ids=batch.input_ids , num_beams=8 , ) snake_case_ = tokenizer.batch_decode( a__ , skip_special_tokens=a__ , clean_up_tokenization_spaces=a__ ) snake_case_ = calculate_bleu(a__ , a__ ) print(a__ ) self.assertGreaterEqual(scores["bleu"] , a__ )
85
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB 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 typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : List[str] = { "configuration_cpmant": ["CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CpmAntConfig"], "tokenization_cpmant": ["CpmAntTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST", "CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class _snake_case : def __init__( self , a__ , a__=3 , a__=32 , a__=3 , a__=10 , a__=[8, 16, 32, 64] , a__=[1, 1, 2, 1] , a__=True , a__=True , a__="relu" , a__=3 , a__=None , a__=["stage2", "stage3", "stage4"] , a__=[2, 3, 4] , a__=1 , ) -> List[Any]: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = embeddings_size snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = scope snake_case_ = len(a__ ) snake_case_ = out_features snake_case_ = out_indices snake_case_ = num_groups def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return BitConfig( 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 , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> Optional[Any]: '''simple docstring''' snake_case_ = BitModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = BitForImageClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = BitBackbone(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = BitBackbone(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : str = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () lowerCAmelCase_ : int = ( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) lowerCAmelCase_ : Union[str, Any] = False lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Any = False lowerCAmelCase_ : Optional[Any] = False lowerCAmelCase_ : Optional[Any] = False def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = BitModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , has_text_modality=a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' return @unittest.skip(reason="Bit does not output attentions" ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' pass @unittest.skip(reason="Bit does not use inputs_embeds" ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' pass @unittest.skip(reason="Bit does not support input and output embeddings" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*a__ ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(config=a__ ) for name, module in model.named_modules(): if isinstance(a__ , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' def check_hidden_states_output(a__ , a__ , a__ ): snake_case_ = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(a__ , a__ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(a__ ) , expected_num_stages + 1 ) # Bit'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] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = ["preactivation", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: snake_case_ = layer_type snake_case_ = True check_hidden_states_output(a__ , a__ , a__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(a__ , a__ , a__ ) @unittest.skip(reason="Bit does not use feedforward chunking" ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) @slow def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = BitModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _snake_case ( unittest.TestCase ): @cached_property def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(a__ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(images=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , a__ ) snake_case_ = torch.tensor([[-0.6_5_2_6, -0.5_2_6_3, -1.4_3_9_8]] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) ) @require_torch class _snake_case ( lowercase_ , unittest.TestCase ): lowerCAmelCase_ : int = (BitBackbone,) if is_torch_available() else () lowerCAmelCase_ : Optional[Any] = BitConfig lowerCAmelCase_ : Optional[Any] = False def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = BitModelTester(self )
85
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu _SCREAMING_SNAKE_CASE : Union[str, Any] = False class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return 32 @property def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 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 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(a__ ) @property def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 12 snake_case_ = 12 snake_case_ = { "attention_bias": True, "cross_attention_dim": 32, "attention_head_dim": height * width, "num_attention_heads": 1, "num_vector_embeds": self.num_embed, "num_embeds_ada_norm": self.num_embeds_ada_norm, "norm_num_groups": 32, "sample_size": width, "activation_fn": "geglu-approximate", } snake_case_ = TransformeraDModel(**a__ ) return model def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings(learnable=a__ ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_5_5_1, 0.6_1_6_8, 0.5_0_0_8, 0.5_6_7_6, 0.5_6_5_9, 0.4_2_9_5, 0.6_0_7_3, 0.5_5_9_9, 0.4_9_9_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings( learnable=a__ , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_6_9_3, 0.6_0_7_5, 0.4_9_5_9, 0.5_7_0_1, 0.5_5_8_3, 0.4_3_3_3, 0.6_1_7_1, 0.5_6_8_4, 0.4_9_8_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy" ) snake_case_ = VQDiffusionPipeline.from_pretrained("microsoft/vq-diffusion-ithq" ) snake_case_ = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipeline( "teddy bear playing in the pool" , num_images_per_prompt=1 , generator=a__ , output_type="np" , ) snake_case_ = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
85
1
'''simple docstring''' import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() _SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = torch.load(snake_case , map_location="cpu" ) if "model" in sd.keys(): snake_case_ = torch.load(snake_case , map_location="cpu" )["model"] # pop unnecessary weights snake_case_ = [ "decoder.version", "decoder.output_projection.weight", ] for key in keys_to_delete: if key in sd: sd.pop(snake_case ) snake_case_ = { "decoder.project_in_dim.weight": "decoder.project_in.weight", "decoder.project_out_dim.weight": "decoder.project_out.weight", "decoder.layer_norm.weight": "decoder.final_layer_norm.weight", "decoder.layer_norm.bias": "decoder.final_layer_norm.bias", } for old_key, new_key in keys_to_rename.items(): if old_key in sd: snake_case_ = sd.pop(snake_case ) snake_case_ = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: snake_case_ = sd[key] # We split QKV in separate Q,K,V snake_case_ = key.replace(".qkv_proj." , ".q_proj." ) snake_case_ = key.replace(".qkv_proj." , ".k_proj." ) snake_case_ = key.replace(".qkv_proj." , ".v_proj." ) snake_case_ = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 snake_case_ , snake_case_ , snake_case_ = torch.split(snake_case , depth // 3 , dim=0 ) snake_case_ = q snake_case_ = k snake_case_ = v del sd[key] return sd @torch.no_grad() def UpperCamelCase_( snake_case : Optional[Any] , snake_case : List[str] , snake_case : List[Any]=None ): '''simple docstring''' snake_case_ = load_checkpoint(snake_case ) if config is not None: snake_case_ = OPTConfig.from_pretrained(snake_case ) else: snake_case_ = OPTConfig() snake_case_ = OPTModel(snake_case ).half().eval() model.load_state_dict(snake_case ) # Check results Path(snake_case ).mkdir(exist_ok=snake_case ) model.save_pretrained(snake_case ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fairseq_path", type=str, help=( "path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:" " https://huggingface.co/models?other=opt_metasq" ), ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--hf_config", default=None, type=str, help="Define HF config.") _SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
85
'''simple docstring''' from statistics import mean, stdev def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = min(snake_case ) snake_case_ = max(snake_case ) # normalize data return [round((x - x_min) / (x_max - x_min) , snake_case ) for x in data] def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = mean(snake_case ) snake_case_ = stdev(snake_case ) # standardize data return [round((x - mu) / (sigma) , snake_case ) for x in data]
85
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return model @property def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , cross_attention_dim=10 , ) return model @property def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D") , up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D") , ) snake_case_ = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return vqvae, unet @slow def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case_ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) snake_case_ = DDPMScheduler() snake_case_ = AudioDiffusionPipeline(vqvae=a__ , unet=self.dummy_unet , mel=a__ , scheduler=a__ ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = torch.Generator(device=a__ ).manual_seed(42 ) snake_case_ = pipe(generator=a__ , steps=4 ) snake_case_ = output.audios[0] snake_case_ = output.images[0] snake_case_ = torch.Generator(device=a__ ).manual_seed(42 ) snake_case_ = pipe(generator=a__ , steps=4 , return_dict=a__ ) snake_case_ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) snake_case_ = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] snake_case_ = np.frombuffer(image_from_tuple.tobytes() , dtype="uint8" )[:10] snake_case_ = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 snake_case_ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) snake_case_ = DDIMScheduler() snake_case_ = self.dummy_vqvae_and_unet snake_case_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=a__ , scheduler=a__ ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) np.random.seed(0 ) snake_case_ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) snake_case_ = torch.Generator(device=a__ ).manual_seed(42 ) snake_case_ = pipe(raw_audio=a__ , generator=a__ , start_step=5 , steps=10 ) snake_case_ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) snake_case_ = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] snake_case_ = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 snake_case_ = self.dummy_unet_condition snake_case_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=a__ , mel=a__ , scheduler=a__ ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) np.random.seed(0 ) snake_case_ = torch.rand((1, 1, 10) ) snake_case_ = pipe(generator=a__ , encoding=a__ ) snake_case_ = output.images[0] snake_case_ = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] snake_case_ = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = torch_device snake_case_ = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-ddim-256" ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = torch.Generator(device=a__ ).manual_seed(42 ) snake_case_ = pipe(generator=a__ ) snake_case_ = output.audios[0] snake_case_ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] snake_case_ = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] snake_case_ = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : str = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
85
1
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def UpperCamelCase_( snake_case : Optional[int] ): '''simple docstring''' if ( (cp >= 0X4E00 and cp <= 0X9FFF) or (cp >= 0X3400 and cp <= 0X4DBF) # or (cp >= 0X2_0000 and cp <= 0X2_A6DF) # or (cp >= 0X2_A700 and cp <= 0X2_B73F) # or (cp >= 0X2_B740 and cp <= 0X2_B81F) # or (cp >= 0X2_B820 and cp <= 0X2_CEAF) # or (cp >= 0XF900 and cp <= 0XFAFF) or (cp >= 0X2_F800 and cp <= 0X2_FA1F) # ): # return True return False def UpperCamelCase_( snake_case : str ): '''simple docstring''' for char in word: snake_case_ = ord(snake_case ) if not _is_chinese_char(snake_case ): return 0 return 1 def UpperCamelCase_( snake_case : List[str] ): '''simple docstring''' snake_case_ = set() for token in tokens: snake_case_ = len(snake_case ) > 1 and is_chinese(snake_case ) if chinese_word: word_set.add(snake_case ) snake_case_ = list(snake_case ) return word_list def UpperCamelCase_( snake_case : List[str] , snake_case : set() ): '''simple docstring''' if not chinese_word_set: return bert_tokens snake_case_ = max([len(snake_case ) for w in chinese_word_set] ) snake_case_ = bert_tokens snake_case_ , snake_case_ = 0, len(snake_case ) while start < end: snake_case_ = True if is_chinese(bert_word[start] ): snake_case_ = min(end - start , snake_case ) for i in range(snake_case , 1 , -1 ): snake_case_ = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): snake_case_ = "##" + bert_word[j] snake_case_ = start + i snake_case_ = False break if single_word: start += 1 return bert_word def UpperCamelCase_( snake_case : List[str] , snake_case : LTP , snake_case : BertTokenizer ): '''simple docstring''' snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] snake_case_ = [get_chinese_word(snake_case ) for r in res] ltp_res.extend(snake_case ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=snake_case , truncation=snake_case , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for input_ids, chinese_word in zip(snake_case , snake_case ): snake_case_ = [] for id in input_ids: snake_case_ = bert_tokenizer._convert_id_to_token(snake_case ) input_tokens.append(snake_case ) snake_case_ = add_sub_symbol(snake_case , snake_case ) snake_case_ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(snake_case ): if token[:2] == "##": snake_case_ = token[2:] # save chinese tokens' pos if len(snake_case ) == 1 and _is_chinese_char(ord(snake_case ) ): ref_id.append(snake_case ) ref_ids.append(snake_case ) assert len(snake_case ) == len(snake_case ) return ref_ids def UpperCamelCase_( snake_case : int ): '''simple docstring''' with open(args.file_name , "r" , encoding="utf-8" ) as f: snake_case_ = f.readlines() snake_case_ = [line.strip() for line in data if len(snake_case ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' snake_case_ = LTP(args.ltp ) # faster in GPU device snake_case_ = BertTokenizer.from_pretrained(args.bert ) snake_case_ = prepare_ref(snake_case , snake_case , snake_case ) with open(args.save_path , "w" , encoding="utf-8" ) as f: snake_case_ = [json.dumps(snake_case ) + "\n" for ref in ref_ids] f.writelines(snake_case ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Dict = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path" ) parser.add_argument("--bert", type=str, default="./resources/robert", help="resources for Bert tokenizer") parser.add_argument("--save_path", type=str, default="./resources/ref.txt", help="path to save res") _SCREAMING_SNAKE_CASE : str = parser.parse_args() main(args)
85
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. snake_case_ = min(snake_case , snake_case ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' if not isinstance(snake_case , snake_case ) or n < 0: raise ValueError("Invalid input" ) snake_case_ = 1_0**n snake_case_ = 2_8_4_3_3 * (pow(2 , 7_8_3_0_4_5_7 , snake_case )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"{solution(10) = }")
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE : Tuple = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConditionalDetrConfig", "ConditionalDetrOnnxConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = ["ConditionalDetrFeatureExtractor"] _SCREAMING_SNAKE_CASE : List[Any] = ["ConditionalDetrImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Dict = [ "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "ConditionalDetrForObjectDetection", "ConditionalDetrForSegmentation", "ConditionalDetrModel", "ConditionalDetrPreTrainedModel", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer _SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Optional[int] = "AutoTokenizer" lowerCAmelCase_ : int = ["tokenizer"] lowerCAmelCase_ : List[Any] = { "semantic_prompt": 1, "coarse_prompt": 2, "fine_prompt": 2, } def __init__( self , a__ , a__=None ) -> Optional[Any]: '''simple docstring''' super().__init__(a__ ) snake_case_ = speaker_embeddings @classmethod def lowerCAmelCase__ ( cls , a__ , a__="speaker_embeddings_path.json" , **a__ ) -> Any: '''simple docstring''' if speaker_embeddings_dict_path is not None: snake_case_ = get_file_from_repo( a__ , a__ , subfolder=kwargs.pop("subfolder" , a__ ) , cache_dir=kwargs.pop("cache_dir" , a__ ) , force_download=kwargs.pop("force_download" , a__ ) , proxies=kwargs.pop("proxies" , a__ ) , resume_download=kwargs.pop("resume_download" , a__ ) , local_files_only=kwargs.pop("local_files_only" , a__ ) , use_auth_token=kwargs.pop("use_auth_token" , a__ ) , revision=kwargs.pop("revision" , a__ ) , ) if speaker_embeddings_path is None: logger.warning( F'`{os.path.join(a__ , a__ )}` does not exists\n , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.' ) snake_case_ = None else: with open(a__ ) as speaker_embeddings_json: snake_case_ = json.load(a__ ) else: snake_case_ = None snake_case_ = AutoTokenizer.from_pretrained(a__ , **a__ ) return cls(tokenizer=a__ , speaker_embeddings=a__ ) def lowerCAmelCase__ ( self , a__ , a__="speaker_embeddings_path.json" , a__="speaker_embeddings" , a__ = False , **a__ , ) -> Tuple: '''simple docstring''' if self.speaker_embeddings is not None: os.makedirs(os.path.join(a__ , a__ , "v2" ) , exist_ok=a__ ) snake_case_ = {} snake_case_ = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": snake_case_ = self._load_voice_preset(a__ ) snake_case_ = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict["repo_or_path"] , a__ , F'{prompt_key}_{key}' ) , voice_preset[key] , allow_pickle=a__ , ) snake_case_ = os.path.join(a__ , F'{prompt_key}_{key}.npy' ) snake_case_ = tmp_dict with open(os.path.join(a__ , a__ ) , "w" ) as fp: json.dump(a__ , a__ ) super().save_pretrained(a__ , a__ , **a__ ) def lowerCAmelCase__ ( self , a__ = None , **a__ ) -> List[str]: '''simple docstring''' snake_case_ = self.speaker_embeddings[voice_preset] snake_case_ = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( F'Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].' ) snake_case_ = get_file_from_repo( self.speaker_embeddings.get("repo_or_path" , "/" ) , voice_preset_paths[key] , subfolder=kwargs.pop("subfolder" , a__ ) , cache_dir=kwargs.pop("cache_dir" , a__ ) , force_download=kwargs.pop("force_download" , a__ ) , proxies=kwargs.pop("proxies" , a__ ) , resume_download=kwargs.pop("resume_download" , a__ ) , local_files_only=kwargs.pop("local_files_only" , a__ ) , use_auth_token=kwargs.pop("use_auth_token" , a__ ) , revision=kwargs.pop("revision" , a__ ) , ) if path is None: raise ValueError( F'`{os.path.join(self.speaker_embeddings.get("repo_or_path" , "/" ) , voice_preset_paths[key] )}` does not exists\n , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n embeddings.' ) snake_case_ = np.load(a__ ) return voice_preset_dict def lowerCAmelCase__ ( self , a__ = None ) -> Dict: '''simple docstring''' for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(F'Voice preset unrecognized, missing {key} as a key.' ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(F'{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.' ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(F'{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.' ) def __call__( self , a__=None , a__=None , a__="pt" , a__=256 , a__=False , a__=True , a__=False , **a__ , ) -> List[str]: '''simple docstring''' if voice_preset is not None and not isinstance(a__ , a__ ): if ( isinstance(a__ , a__ ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): snake_case_ = self._load_voice_preset(a__ ) else: if isinstance(a__ , a__ ) and not voice_preset.endswith(".npz" ): snake_case_ = voice_preset + ".npz" snake_case_ = np.load(a__ ) if voice_preset is not None: self._validate_voice_preset_dict(a__ , **a__ ) snake_case_ = BatchFeature(data=a__ , tensor_type=a__ ) snake_case_ = self.tokenizer( a__ , return_tensors=a__ , padding="max_length" , max_length=a__ , return_attention_mask=a__ , return_token_type_ids=a__ , add_special_tokens=a__ , **a__ , ) if voice_preset is not None: snake_case_ = voice_preset return encoded_text
85
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--txt2img_unclip", default="kakaobrain/karlo-v1-alpha", type=str, required=False, help="The pretrained txt2img unclip.", ) _SCREAMING_SNAKE_CASE : int = parser.parse_args() _SCREAMING_SNAKE_CASE : List[Any] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor() _SCREAMING_SNAKE_CASE : str = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") _SCREAMING_SNAKE_CASE : int = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
85
1
'''simple docstring''' from __future__ import annotations import math def UpperCamelCase_( snake_case : list , snake_case : list ): '''simple docstring''' if len(snake_case ) != 2 or len(a[0] ) != 2 or len(snake_case ) != 2 or len(b[0] ) != 2: raise Exception("Matrices are not 2x2" ) snake_case_ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def UpperCamelCase_( snake_case : list , snake_case : list ): '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(snake_case ) ) ] def UpperCamelCase_( snake_case : list , snake_case : list ): '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(snake_case ) ) ] def UpperCamelCase_( snake_case : list ): '''simple docstring''' if len(snake_case ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("Odd matrices are not supported!" ) snake_case_ = len(snake_case ) snake_case_ = matrix_length // 2 snake_case_ = [[a[i][j] for j in range(snake_case , snake_case )] for i in range(snake_case )] snake_case_ = [ [a[i][j] for j in range(snake_case , snake_case )] for i in range(snake_case , snake_case ) ] snake_case_ = [[a[i][j] for j in range(snake_case )] for i in range(snake_case )] snake_case_ = [[a[i][j] for j in range(snake_case )] for i in range(snake_case , snake_case )] return top_left, top_right, bot_left, bot_right def UpperCamelCase_( snake_case : list ): '''simple docstring''' return len(snake_case ), len(matrix[0] ) def UpperCamelCase_( snake_case : list ): '''simple docstring''' print("\n".join(str(snake_case ) for line in matrix ) ) def UpperCamelCase_( snake_case : list , snake_case : list ): '''simple docstring''' if matrix_dimensions(snake_case ) == (2, 2): return default_matrix_multiplication(snake_case , snake_case ) snake_case_ , snake_case_ , snake_case_ , snake_case_ = split_matrix(snake_case ) snake_case_ , snake_case_ , snake_case_ , snake_case_ = split_matrix(snake_case ) snake_case_ = actual_strassen(snake_case , matrix_subtraction(snake_case , snake_case ) ) snake_case_ = actual_strassen(matrix_addition(snake_case , snake_case ) , snake_case ) snake_case_ = actual_strassen(matrix_addition(snake_case , snake_case ) , snake_case ) snake_case_ = actual_strassen(snake_case , matrix_subtraction(snake_case , snake_case ) ) snake_case_ = actual_strassen(matrix_addition(snake_case , snake_case ) , matrix_addition(snake_case , snake_case ) ) snake_case_ = actual_strassen(matrix_subtraction(snake_case , snake_case ) , matrix_addition(snake_case , snake_case ) ) snake_case_ = actual_strassen(matrix_subtraction(snake_case , snake_case ) , matrix_addition(snake_case , snake_case ) ) snake_case_ = matrix_addition(matrix_subtraction(matrix_addition(snake_case , snake_case ) , snake_case ) , snake_case ) snake_case_ = matrix_addition(snake_case , snake_case ) snake_case_ = matrix_addition(snake_case , snake_case ) snake_case_ = matrix_subtraction(matrix_subtraction(matrix_addition(snake_case , snake_case ) , snake_case ) , snake_case ) # construct the new matrix from our 4 quadrants snake_case_ = [] for i in range(len(snake_case ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(snake_case ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def UpperCamelCase_( snake_case : list , snake_case : list ): '''simple docstring''' if matrix_dimensions(snake_case )[1] != matrix_dimensions(snake_case )[0]: snake_case_ = ( "Unable to multiply these matrices, please check the dimensions.\n" f'Matrix A: {matrixa}\n' f'Matrix B: {matrixa}' ) raise Exception(snake_case ) snake_case_ = matrix_dimensions(snake_case ) snake_case_ = matrix_dimensions(snake_case ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] snake_case_ = max(*snake_case , *snake_case ) snake_case_ = int(math.pow(2 , math.ceil(math.loga(snake_case ) ) ) ) snake_case_ = matrixa snake_case_ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , snake_case ): if i < dimensiona[0]: for _ in range(dimensiona[1] , snake_case ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , snake_case ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) snake_case_ = actual_strassen(snake_case , snake_case ) # Removing the additional zeros for i in range(0 , snake_case ): if i < dimensiona[0]: for _ in range(dimensiona[1] , snake_case ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Tuple = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] _SCREAMING_SNAKE_CASE : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
85
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "upernet" def __init__( self , a__=None , a__=512 , a__=0.0_2 , a__=[1, 2, 3, 6] , a__=True , a__=0.4 , a__=384 , a__=256 , a__=1 , a__=False , a__=255 , **a__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**a__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) snake_case_ = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a__ , a__ ): snake_case_ = backbone_config.get("model_type" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(a__ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1
'''simple docstring''' import unittest from transformers import DebertaConfig, is_torch_available 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class _snake_case ( lowercase_ ): def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=False , a__=True , a__="None" , a__=3 , a__=4 , a__=None , ) -> List[Any]: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = num_choices snake_case_ = relative_attention snake_case_ = position_biased_input snake_case_ = pos_att_type snake_case_ = scope def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return DebertaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.get_config() snake_case_ = 300 return config def lowerCAmelCase__ ( self , a__ ) -> List[str]: '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Any: '''simple docstring''' snake_case_ = DebertaModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ )[0] snake_case_ = model(a__ , token_type_ids=a__ )[0] snake_case_ = model(a__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Any: '''simple docstring''' snake_case_ = DebertaForMaskedLM(config=a__ ) model.to(a__ ) model.eval() snake_case_ = 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 lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = DebertaForSequenceClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , token_type_ids=a__ , labels=a__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = DebertaForTokenClassification(config=a__ ) model.to(a__ ) model.eval() snake_case_ = 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 lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = DebertaForQuestionAnswering(config=a__ ) model.to(a__ ) model.eval() snake_case_ = 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 lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : Optional[int] = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase_ : Dict = ( { "feature-extraction": DebertaModel, "fill-mask": DebertaForMaskedLM, "question-answering": DebertaForQuestionAnswering, "text-classification": DebertaForSequenceClassification, "token-classification": DebertaForTokenClassification, "zero-shot": DebertaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ : Optional[int] = True lowerCAmelCase_ : Union[str, Any] = False lowerCAmelCase_ : Tuple = False lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Tuple = False def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = DebertaModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , hidden_size=37 ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*a__ ) @slow def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = DebertaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) @require_torch @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @unittest.skip(reason="Model not available yet" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' pass @slow def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = DebertaModel.from_pretrained("microsoft/deberta-base" ) snake_case_ = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) snake_case_ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): snake_case_ = model(a__ , attention_mask=a__ )[0] # compare the actual values for a slice. snake_case_ = torch.tensor( [[[-0.5_9_8_6, -0.8_0_5_5, -0.8_4_6_2], [1.4_4_8_4, -0.9_3_4_8, -0.8_0_5_9], [0.3_1_2_3, 0.0_0_3_2, -1.4_1_3_1]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a__ , atol=1e-4 ) , F'{output[:, 1:4, 1:4]}' )
85
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def UpperCamelCase_( snake_case : Any ): '''simple docstring''' if ( (cp >= 0X4E00 and cp <= 0X9FFF) or (cp >= 0X3400 and cp <= 0X4DBF) # or (cp >= 0X2_0000 and cp <= 0X2_A6DF) # or (cp >= 0X2_A700 and cp <= 0X2_B73F) # or (cp >= 0X2_B740 and cp <= 0X2_B81F) # or (cp >= 0X2_B820 and cp <= 0X2_CEAF) # or (cp >= 0XF900 and cp <= 0XFAFF) or (cp >= 0X2_F800 and cp <= 0X2_FA1F) # ): # return True return False def UpperCamelCase_( snake_case : str ): '''simple docstring''' for char in word: snake_case_ = ord(snake_case ) if not _is_chinese_char(snake_case ): return 0 return 1 def UpperCamelCase_( snake_case : List[str] ): '''simple docstring''' snake_case_ = set() for token in tokens: snake_case_ = len(snake_case ) > 1 and is_chinese(snake_case ) if chinese_word: word_set.add(snake_case ) snake_case_ = list(snake_case ) return word_list def UpperCamelCase_( snake_case : List[str] , snake_case : set() ): '''simple docstring''' if not chinese_word_set: return bert_tokens snake_case_ = max([len(snake_case ) for w in chinese_word_set] ) snake_case_ = bert_tokens snake_case_ , snake_case_ = 0, len(snake_case ) while start < end: snake_case_ = True if is_chinese(bert_word[start] ): snake_case_ = min(end - start , snake_case ) for i in range(snake_case , 1 , -1 ): snake_case_ = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): snake_case_ = "##" + bert_word[j] snake_case_ = start + i snake_case_ = False break if single_word: start += 1 return bert_word def UpperCamelCase_( snake_case : List[str] , snake_case : LTP , snake_case : BertTokenizer ): '''simple docstring''' snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = ltp_tokenizer.pipeline(lines[i : i + 1_0_0] , tasks=["cws"] ).cws snake_case_ = [get_chinese_word(snake_case ) for r in res] ltp_res.extend(snake_case ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=snake_case , truncation=snake_case , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for input_ids, chinese_word in zip(snake_case , snake_case ): snake_case_ = [] for id in input_ids: snake_case_ = bert_tokenizer._convert_id_to_token(snake_case ) input_tokens.append(snake_case ) snake_case_ = add_sub_symbol(snake_case , snake_case ) snake_case_ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(snake_case ): if token[:2] == "##": snake_case_ = token[2:] # save chinese tokens' pos if len(snake_case ) == 1 and _is_chinese_char(ord(snake_case ) ): ref_id.append(snake_case ) ref_ids.append(snake_case ) assert len(snake_case ) == len(snake_case ) return ref_ids def UpperCamelCase_( snake_case : Any ): '''simple docstring''' with open(args.file_name , "r" , encoding="utf-8" ) as f: snake_case_ = f.readlines() snake_case_ = [line.strip() for line in data if len(snake_case ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' snake_case_ = LTP(args.ltp ) # faster in GPU device snake_case_ = BertTokenizer.from_pretrained(args.bert ) snake_case_ = prepare_ref(snake_case , snake_case , snake_case ) with open(args.save_path , "w" , encoding="utf-8" ) as f: snake_case_ = [json.dumps(snake_case ) + "\n" for ref in ref_ids] f.writelines(snake_case ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", required=False, type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", required=False, type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path", ) parser.add_argument( "--bert", required=False, type=str, default="./resources/robert", help="resources for Bert tokenizer", ) parser.add_argument( "--save_path", required=False, type=str, default="./resources/ref.txt", help="path to save res", ) _SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() main(args)
85
1
'''simple docstring''' import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class _snake_case ( lowercase_ ): def __init__( self ) -> List[Any]: '''simple docstring''' snake_case_ = [] def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> List[str]: '''simple docstring''' self.events.append("on_init_end" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> List[str]: '''simple docstring''' self.events.append("on_train_begin" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> int: '''simple docstring''' self.events.append("on_train_end" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> Any: '''simple docstring''' self.events.append("on_epoch_begin" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> Union[str, Any]: '''simple docstring''' self.events.append("on_epoch_end" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> Union[str, Any]: '''simple docstring''' self.events.append("on_step_begin" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> Optional[Any]: '''simple docstring''' self.events.append("on_step_end" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> Optional[int]: '''simple docstring''' self.events.append("on_evaluate" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> Union[str, Any]: '''simple docstring''' self.events.append("on_predict" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> str: '''simple docstring''' self.events.append("on_save" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> Tuple: '''simple docstring''' self.events.append("on_log" ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , **a__ ) -> str: '''simple docstring''' self.events.append("on_prediction_step" ) @require_torch class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = tempfile.mkdtemp() def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' shutil.rmtree(self.output_dir ) def lowerCAmelCase__ ( self , a__=0 , a__=0 , a__=64 , a__=64 , a__=None , a__=False , **a__ ) -> int: '''simple docstring''' snake_case_ = RegressionDataset(length=a__ ) snake_case_ = RegressionDataset(length=a__ ) snake_case_ = RegressionModelConfig(a=a__ , b=a__ ) snake_case_ = RegressionPreTrainedModel(a__ ) snake_case_ = TrainingArguments(self.output_dir , disable_tqdm=a__ , report_to=[] , **a__ ) return Trainer( a__ , a__ , train_dataset=a__ , eval_dataset=a__ , callbacks=a__ , ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[int]: '''simple docstring''' self.assertEqual(len(a__ ) , len(a__ ) ) # Order doesn't matter snake_case_ = sorted(a__ , key=lambda a__ : cb.__name__ if isinstance(a__ , a__ ) else cb.__class__.__name__ ) snake_case_ = sorted(a__ , key=lambda a__ : cb.__name__ if isinstance(a__ , a__ ) else cb.__class__.__name__ ) for cba, cba in zip(a__ , a__ ): if isinstance(a__ , a__ ) and isinstance(a__ , a__ ): self.assertEqual(a__ , a__ ) elif isinstance(a__ , a__ ) and not isinstance(a__ , a__ ): self.assertEqual(a__ , cba.__class__ ) elif not isinstance(a__ , a__ ) and isinstance(a__ , a__ ): self.assertEqual(cba.__class__ , a__ ) else: self.assertEqual(a__ , a__ ) def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ = ["on_init_end", "on_train_begin"] snake_case_ = 0 snake_case_ = len(trainer.get_eval_dataloader() ) snake_case_ = ["on_prediction_step"] * len(trainer.get_eval_dataloader() ) + ["on_log", "on_evaluate"] for _ in range(trainer.state.num_train_epochs ): expected_events.append("on_epoch_begin" ) for _ in range(a__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append("on_log" ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append("on_save" ) expected_events.append("on_epoch_end" ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.get_trainer() snake_case_ = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) # Callbacks passed at init are added to the default callbacks snake_case_ = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(a__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback snake_case_ = self.get_trainer(disable_tqdm=a__ ) snake_case_ = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = DEFAULT_CALLBACKS.copy() + [ProgressCallback] snake_case_ = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(a__ ) expected_callbacks.remove(a__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) snake_case_ = self.get_trainer() snake_case_ = trainer.pop_callback(a__ ) self.assertEqual(cb.__class__ , a__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) trainer.add_callback(a__ ) expected_callbacks.insert(0 , a__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) # We can also add, pop, or remove by instance snake_case_ = self.get_trainer() snake_case_ = trainer.callback_handler.callbacks[0] trainer.remove_callback(a__ ) expected_callbacks.remove(a__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) snake_case_ = self.get_trainer() snake_case_ = trainer.callback_handler.callbacks[0] snake_case_ = trainer.pop_callback(a__ ) self.assertEqual(a__ , a__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) trainer.add_callback(a__ ) expected_callbacks.insert(0 , a__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a__ ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action="ignore" , category=a__ ) snake_case_ = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() snake_case_ = trainer.callback_handler.callbacks[-2].events self.assertEqual(a__ , self.get_expected_events(a__ ) ) # Independent log/save/eval snake_case_ = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() snake_case_ = trainer.callback_handler.callbacks[-2].events self.assertEqual(a__ , self.get_expected_events(a__ ) ) snake_case_ = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() snake_case_ = trainer.callback_handler.callbacks[-2].events self.assertEqual(a__ , self.get_expected_events(a__ ) ) snake_case_ = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy="steps" ) trainer.train() snake_case_ = trainer.callback_handler.callbacks[-2].events self.assertEqual(a__ , self.get_expected_events(a__ ) ) snake_case_ = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy="epoch" ) trainer.train() snake_case_ = trainer.callback_handler.callbacks[-2].events self.assertEqual(a__ , self.get_expected_events(a__ ) ) # A bit of everything snake_case_ = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy="steps" , ) trainer.train() snake_case_ = trainer.callback_handler.callbacks[-2].events self.assertEqual(a__ , self.get_expected_events(a__ ) ) # warning should be emitted for duplicated callbacks with patch("transformers.trainer_callback.logger.warning" ) as warn_mock: snake_case_ = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(a__ ) in warn_mock.call_args[0][0]
85
'''simple docstring''' import warnings from functools import wraps from typing import Callable def UpperCamelCase_( snake_case : Callable ): '''simple docstring''' @wraps(snake_case ) def _inner_fn(*snake_case : Optional[int] , **snake_case : List[Any] ): warnings.warn( (f'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , snake_case , ) return fn(*snake_case , **snake_case ) return _inner_fn
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[Any] ): '''simple docstring''' if not head: return True # split the list to two parts snake_case_ , snake_case_ = head.next, head while fast and fast.next: snake_case_ = fast.next.next snake_case_ = slow.next snake_case_ = slow.next snake_case_ = None # Don't forget here! But forget still works! # reverse the second part snake_case_ = None while second: snake_case_ = second.next snake_case_ = node snake_case_ = second snake_case_ = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False snake_case_ = node.next snake_case_ = head.next return True def UpperCamelCase_( snake_case : Optional[int] ): '''simple docstring''' if not head or not head.next: return True # 1. Get the midpoint (slow) snake_case_ = snake_case_ = snake_case_ = head while fast and fast.next: snake_case_ , snake_case_ = fast.next.next, slow.next # 2. Push the second half into the stack snake_case_ = [slow.val] while slow.next: snake_case_ = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False snake_case_ = cur.next return True def UpperCamelCase_( snake_case : Optional[Any] ): '''simple docstring''' if not head or not head.next: return True snake_case_ = {} snake_case_ = 0 while head: if head.val in d: d[head.val].append(snake_case ) else: snake_case_ = [pos] snake_case_ = head.next pos += 1 snake_case_ = pos - 1 snake_case_ = 0 for v in d.values(): if len(snake_case ) % 2 != 0: middle += 1 else: snake_case_ = 0 for i in range(0 , len(snake_case ) ): if v[i] + v[len(snake_case ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
85
'''simple docstring''' from __future__ import annotations import requests def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case ).json() def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' snake_case_ = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" snake_case_ = requests.get(snake_case ).json()[:max_stories] return [get_hackernews_story(snake_case ) for story_id in story_ids] def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' snake_case_ = hackernews_top_stories(snake_case ) return "\n".join("* [{title}]({url})".format(**snake_case ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
85
1
'''simple docstring''' from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow 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 TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _snake_case : def __init__( self , a__ , a__=13 , a__=30 , a__=2 , a__=3 , a__=True , a__=True , a__=32 , a__=2 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.0_2 , a__=3 , a__=0.6 , a__=None , ) -> List[str]: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = is_training snake_case_ = use_labels snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = mask_ratio snake_case_ = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) snake_case_ = (image_size // patch_size) ** 2 snake_case_ = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = TFViTMAEModel(config=a__ ) snake_case_ = model(a__ , training=a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = TFViTMAEForPreTraining(a__ ) snake_case_ = model(a__ , training=a__ ) # expected sequence length = num_patches snake_case_ = (self.image_size // self.patch_size) ** 2 snake_case_ = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images snake_case_ = 1 snake_case_ = TFViTMAEForPreTraining(a__ ) snake_case_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ = model(a__ , training=a__ ) snake_case_ = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() ((snake_case_) , (snake_case_) , (snake_case_)) = config_and_inputs snake_case_ = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : Optional[int] = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () lowerCAmelCase_ : Optional[int] = {"feature-extraction": TFViTMAEModel} if is_tf_available() else {} lowerCAmelCase_ : Union[str, Any] = False lowerCAmelCase_ : Union[str, Any] = False lowerCAmelCase_ : Optional[Any] = False lowerCAmelCase_ : Any = False def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = TFViTMAEModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="ViTMAE does not use inputs_embeds" ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) snake_case_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , tf.keras.layers.Layer ) ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' np.random.seed(2 ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = int((config.image_size // config.patch_size) ** 2 ) snake_case_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = self._prepare_for_class(a__ , a__ ) snake_case_ = model(a__ , noise=a__ ) snake_case_ = copy.deepcopy(self._prepare_for_class(a__ , a__ ) ) snake_case_ = model(**a__ , noise=a__ ) snake_case_ = outputs_dict[0].numpy() snake_case_ = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1e-6 ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' np.random.seed(2 ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = int((config.image_size // config.patch_size) ** 2 ) snake_case_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(a__ ): snake_case_ = {} for k, v in inputs_dict.items(): if tf.is_tensor(a__ ): snake_case_ = v.numpy() else: snake_case_ = np.array(a__ ) return inputs_np_dict for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = self._prepare_for_class(a__ , a__ ) snake_case_ = prepare_numpy_arrays(a__ ) snake_case_ = model(a__ , noise=a__ ) snake_case_ = model(**a__ , noise=a__ ) self.assert_outputs_same(a__ , a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> Any: '''simple docstring''' np.random.seed(2 ) snake_case_ = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) snake_case_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) snake_case_ = tf.constant(a__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument snake_case_ = tf_noise super().check_pt_tf_models(a__ , a__ , a__ ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' np.random.seed(2 ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(a__ ) if module_member_name.endswith("MainLayer" ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len("MainLayer" )] == model_class.__name__[: -len("Model" )] for module_member in (getattr(a__ , a__ ),) if isinstance(a__ , a__ ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(a__ , "_keras_serializable" , a__ ) } snake_case_ = int((config.image_size // config.patch_size) ** 2 ) snake_case_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) snake_case_ = tf.convert_to_tensor(a__ ) inputs_dict.update({"noise": noise} ) for main_layer_class in tf_main_layer_classes: snake_case_ = main_layer_class(a__ ) snake_case_ = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } snake_case_ = tf.keras.Model(a__ , outputs=main_layer(a__ ) ) snake_case_ = model(a__ ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(a__ , "keras_model.h5" ) model.save(a__ ) snake_case_ = tf.keras.models.load_model( a__ , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(a__ , tf.keras.Model ) snake_case_ = model(a__ ) self.assert_outputs_same(a__ , a__ ) @slow def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' np.random.seed(2 ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = int((config.image_size // config.patch_size) ** 2 ) snake_case_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = self._prepare_for_class(a__ , a__ ) snake_case_ = model(a__ , noise=a__ ) if model_class.__name__ == "TFViTMAEModel": snake_case_ = outputs.last_hidden_state.numpy() snake_case_ = 0 else: snake_case_ = outputs.logits.numpy() snake_case_ = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a__ , saved_model=a__ ) snake_case_ = model_class.from_pretrained(a__ ) snake_case_ = model(a__ , noise=a__ ) if model_class.__name__ == "TFViTMAEModel": snake_case_ = after_outputs["last_hidden_state"].numpy() snake_case_ = 0 else: snake_case_ = after_outputs["logits"].numpy() snake_case_ = 0 snake_case_ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a__ , 1e-5 ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' np.random.seed(2 ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = int((config.image_size // config.patch_size) ** 2 ) snake_case_ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = self._prepare_for_class(a__ , a__ ) snake_case_ = model(a__ , noise=a__ ) snake_case_ = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(a__ ) snake_case_ = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config snake_case_ = model_class.from_config(model.config ) snake_case_ = new_model(a__ ) # Build model new_model.set_weights(model.get_weights() ) snake_case_ = new_model(a__ , noise=a__ ) self.assert_outputs_same(a__ , a__ ) @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' pass @unittest.skip(reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load" ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' pass @slow def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = TFViTMAEModel.from_pretrained("google/vit-base-patch16-224" ) self.assertIsNotNone(a__ ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class _snake_case ( unittest.TestCase ): @cached_property def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' return ViTImageProcessor.from_pretrained("facebook/vit-mae-base" ) if is_vision_available() else None @slow def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' np.random.seed(2 ) snake_case_ = TFViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base" ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(images=a__ , return_tensors="tf" ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) snake_case_ = ViTMAEConfig() snake_case_ = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) snake_case_ = np.random.uniform(size=(1, num_patches) ) # forward pass snake_case_ = model(**a__ , noise=a__ ) # verify the logits snake_case_ = tf.convert_to_tensor([1, 196, 768] ) self.assertEqual(outputs.logits.shape , a__ ) snake_case_ = tf.convert_to_tensor( [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , a__ , atol=1e-4 )
85
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : Optional[Any] = MODEL_FOR_CAUSAL_LM_MAPPING lowerCAmelCase_ : Optional[Any] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="pt" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ], [ { "generated_text": ( "This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy" " oscope. oscope. FiliFili@@" ) } ], ] , ) snake_case_ = text_generator("This is a test" , do_sample=a__ , num_return_sequences=2 , return_tensors=a__ ) self.assertEqual( a__ , [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ] , ) snake_case_ = text_generator.model.config.eos_token_id snake_case_ = "<pad>" snake_case_ = text_generator( ["This is a test", "This is a second test"] , do_sample=a__ , num_return_sequences=2 , batch_size=2 , return_tensors=a__ , ) self.assertEqual( a__ , [ [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], ] , ) @require_tf def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="tf" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] , do_sample=a__ ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ], [ { "generated_text": ( "This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes" " Cannes 閲閲Cannes Cannes Cannes 攵 please," ) } ], ] , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> str: '''simple docstring''' snake_case_ = TextGenerationPipeline(model=a__ , tokenizer=a__ ) return text_generator, ["This is a test", "Another test"] def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "Hello I believe in" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) snake_case_ = text_generator(a__ ) self.assertEqual( a__ , [{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}] , ) snake_case_ = text_generator(a__ , stop_sequence=" fe" ) self.assertEqual(a__ , [{"generated_text": "Hello I believe in fe"}] ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Tuple: '''simple docstring''' snake_case_ = text_generator.model snake_case_ = text_generator.tokenizer snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = pipeline(task="text-generation" , model=a__ , tokenizer=a__ , return_full_text=a__ ) snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) if text_generator.tokenizer.pad_token is not None: snake_case_ = text_generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_text=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_tensors=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_text=a__ , return_tensors=a__ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): snake_case_ = text_generator("" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): snake_case_ = text_generator("" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. snake_case_ = ["RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM"] if ( tokenizer.model_max_length < 10_000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("This is a test" * 500 , max_new_tokens=20 ) snake_case_ = text_generator("This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(a__ ): text_generator( "This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' import torch # Classic `model_kwargs` snake_case_ = pipeline( model="hf-internal-testing/tiny-random-bloom" , model_kwargs={"device_map": "auto", "torch_dtype": torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) @require_torch @require_torch_gpu def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device=0 , torch_dtype=torch.floataa ) pipe("This is a test" ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.floataa ) pipe("This is a test" , do_sample=a__ , top_p=0.5 ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "Hello world" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) if text_generator.model.framework == "tf": snake_case_ = logging.get_logger("transformers.generation.tf_utils" ) else: snake_case_ = logging.get_logger("transformers.generation.utils" ) snake_case_ = "Both `max_new_tokens`" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 , max_new_tokens=1 ) self.assertIn(a__ , cl.out ) # The user only sets one -> no warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_new_tokens=1 ) self.assertNotIn(a__ , cl.out ) with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 ) self.assertNotIn(a__ , cl.out )
85
1
'''simple docstring''' 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_( snake_case : str ): '''simple docstring''' snake_case_ = filter(lambda snake_case : p.requires_grad , model.parameters() ) snake_case_ = sum([np.prod(p.size() ) for p in model_parameters] ) return params _SCREAMING_SNAKE_CASE : int = logging.getLogger(__name__) def UpperCamelCase_( snake_case : int , snake_case : str ): '''simple docstring''' if metric == "rouge2": snake_case_ = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": snake_case_ = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": snake_case_ = "{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." ) snake_case_ = ModelCheckpoint( dirpath=snake_case , filename=snake_case , monitor=f'val_{metric}' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def UpperCamelCase_( snake_case : Dict , snake_case : Union[str, Any] ): '''simple docstring''' return EarlyStopping( monitor=f'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=snake_case , verbose=snake_case , ) class _snake_case ( pl.Callback ): def lowerCAmelCase__ ( self , a__ , a__ ) -> Tuple: '''simple docstring''' snake_case_ = {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 lowerCAmelCase__ ( self , a__ , a__ , a__ , a__=True ) -> None: '''simple docstring''' logger.info(F'***** {type_path} results at step {trainer.global_step:05d} *****' ) snake_case_ = 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 snake_case_ = Path(pl_module.hparams.output_dir ) if type_path == "test": snake_case_ = od / "test_results.txt" snake_case_ = 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. snake_case_ = od / F'{type_path}_results/{trainer.global_step:05d}.txt' snake_case_ = 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 snake_case_ = metrics[key] if isinstance(a__ , torch.Tensor ): snake_case_ = val.item() snake_case_ = F'{key}: {val:.6f}\n' writer.write(a__ ) if not save_generations: return if "preds" in metrics: snake_case_ = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(a__ ) @rank_zero_only def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[Any]: '''simple docstring''' try: snake_case_ = pl_module.model.model.num_parameters() except AttributeError: snake_case_ = pl_module.model.num_parameters() snake_case_ = 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 lowerCAmelCase__ ( self , a__ , a__ ) -> Tuple: '''simple docstring''' save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(a__ , a__ , "test" ) @rank_zero_only def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[Any]: '''simple docstring''' save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
85
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , lowercase_ ): def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = load_tool("text-classification" ) self.tool.setup() snake_case_ = load_tool("text-classification" , remote=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" )
85
1
'''simple docstring''' from __future__ import annotations import collections import pprint from pathlib import Path def UpperCamelCase_( snake_case : str ): '''simple docstring''' return "".join(sorted(snake_case ) ) def UpperCamelCase_( snake_case : str ): '''simple docstring''' return word_by_signature[signature(snake_case )] _SCREAMING_SNAKE_CASE : str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8") _SCREAMING_SNAKE_CASE : List[Any] = sorted({word.strip().lower() for word in data.splitlines()}) _SCREAMING_SNAKE_CASE : List[str] = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : List[str] = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open("anagrams.txt", "w") as file: file.write("all_anagrams = \n ") file.write(pprint.pformat(all_anagrams))
85
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Dict = { "BridgeTower/bridgetower-base": "https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json", "BridgeTower/bridgetower-base-itm-mlm": ( "https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json" ), } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Dict = "bridgetower_vision_model" def __init__( self , a__=768 , a__=12 , a__=3 , a__=16 , a__=288 , a__=1 , a__=1e-05 , a__=False , a__=True , a__=False , **a__ , ) -> int: '''simple docstring''' super().__init__(**a__ ) snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_channels snake_case_ = patch_size snake_case_ = image_size snake_case_ = initializer_factor snake_case_ = layer_norm_eps snake_case_ = stop_gradient snake_case_ = share_layernorm snake_case_ = remove_last_layer @classmethod def lowerCAmelCase__ ( cls , a__ , **a__ ) -> "PretrainedConfig": '''simple docstring''' snake_case_ , snake_case_ = cls.get_config_dict(a__ , **a__ ) if config_dict.get("model_type" ) == "bridgetower": snake_case_ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a__ , **a__ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "bridgetower_text_model" def __init__( self , a__=50_265 , a__=768 , a__=12 , a__=12 , a__=1 , a__=3_072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=514 , a__=1 , a__=1e-05 , a__=1 , a__=0 , a__=2 , a__="absolute" , a__=True , **a__ , ) -> Optional[int]: '''simple docstring''' super().__init__(**a__ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = initializer_factor snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = layer_norm_eps snake_case_ = position_embedding_type snake_case_ = use_cache snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id @classmethod def lowerCAmelCase__ ( cls , a__ , **a__ ) -> "PretrainedConfig": '''simple docstring''' snake_case_ , snake_case_ = cls.get_config_dict(a__ , **a__ ) if config_dict.get("model_type" ) == "bridgetower": snake_case_ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a__ , **a__ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Union[str, Any] = "bridgetower" def __init__( self , a__=True , a__="gelu" , a__=768 , a__=1 , a__=1e-05 , a__=False , a__="add" , a__=12 , a__=6 , a__=False , a__=False , a__=None , a__=None , **a__ , ) -> int: '''simple docstring''' snake_case_ = kwargs.pop("text_config_dict" , a__ ) snake_case_ = kwargs.pop("vision_config_dict" , a__ ) super().__init__(**a__ ) snake_case_ = share_cross_modal_transformer_layers snake_case_ = hidden_act snake_case_ = hidden_size snake_case_ = initializer_factor snake_case_ = layer_norm_eps snake_case_ = share_link_tower_layers snake_case_ = link_tower_type snake_case_ = num_attention_heads snake_case_ = num_hidden_layers snake_case_ = tie_word_embeddings snake_case_ = init_layernorm_from_vision_encoder if text_config is None: snake_case_ = {} logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values." ) if vision_config is None: snake_case_ = {} logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values." ) snake_case_ = BridgeTowerTextConfig(**a__ ) snake_case_ = BridgeTowerVisionConfig(**a__ ) @classmethod def lowerCAmelCase__ ( cls , a__ , a__ , **a__ ) -> List[Any]: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.text_config.to_dict() snake_case_ = self.vision_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. snake_case_ = min(snake_case , snake_case ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
85
'''simple docstring''' from __future__ import annotations def UpperCamelCase_( snake_case : list[int] ): '''simple docstring''' return len(set(snake_case ) ) == len(snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
85
1
'''simple docstring''' import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _snake_case ( lowercase_ ): def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(a__ , "width_multiplier" ) ) class _snake_case : def __init__( self , a__ , a__=13 , a__=64 , a__=2 , a__=3 , a__="swish" , a__=3 , a__=32 , a__=0.1 , a__=0.0_2 , a__=True , a__=True , a__=10 , a__=None , a__=0.2_5 , a__=0.0 , a__=0.0 , ) -> Dict: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = make_divisible(512 * width_multiplier , divisor=8 ) snake_case_ = hidden_act snake_case_ = conv_kernel_size snake_case_ = output_stride snake_case_ = classifier_dropout_prob snake_case_ = use_labels snake_case_ = is_training snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = scope snake_case_ = width_multiplier snake_case_ = ffn_dropout snake_case_ = attn_dropout def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels, pixel_labels def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> int: '''simple docstring''' snake_case_ = MobileViTVaModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = MobileViTVaForImageClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> List[str]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = MobileViTVaForSemanticSegmentation(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) snake_case_ = model(a__ , labels=a__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : int = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) lowerCAmelCase_ : Dict = ( { "feature-extraction": MobileViTVaModel, "image-classification": MobileViTVaForImageClassification, "image-segmentation": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) lowerCAmelCase_ : Dict = False lowerCAmelCase_ : List[Any] = False lowerCAmelCase_ : List[Any] = False lowerCAmelCase_ : int = False def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = MobileViTVaModelTester(self ) snake_case_ = MobileViTVaConfigTester(self , config_class=a__ , has_text_modality=a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="MobileViTV2 does not use inputs_embeds" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' pass @unittest.skip(reason="MobileViTV2 does not support input and output embeddings" ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason="MobileViTV2 does not output attentions" ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run." ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' def check_hidden_states_output(a__ , a__ , a__ ): snake_case_ = model_class(a__ ) model.to(a__ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(a__ , a__ ) ) snake_case_ = outputs.hidden_states snake_case_ = 5 self.assertEqual(len(a__ ) , a__ ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. snake_case_ = 2 for i in range(len(a__ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(a__ , a__ , a__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(a__ , a__ , a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*a__ ) @slow def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = MobileViTVaModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _snake_case ( unittest.TestCase ): @cached_property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return ( MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256" ) if is_vision_available() else None ) @slow def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256" ).to( a__ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(images=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , a__ ) snake_case_ = torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) ) @slow def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" ) snake_case_ = model.to(a__ ) snake_case_ = MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" ) snake_case_ = prepare_img() snake_case_ = image_processor(images=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) snake_case_ = outputs.logits # verify the logits snake_case_ = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , a__ ) snake_case_ = torch.tensor( [ [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]], [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]], [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]], ] , device=a__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , a__ , atol=1e-4 ) ) @slow def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" ) snake_case_ = model.to(a__ ) snake_case_ = MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" ) snake_case_ = prepare_img() snake_case_ = image_processor(images=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) snake_case_ = outputs.logits.detach().cpu() snake_case_ = image_processor.post_process_semantic_segmentation(outputs=a__ , target_sizes=[(50, 60)] ) snake_case_ = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , a__ ) snake_case_ = image_processor.post_process_semantic_segmentation(outputs=a__ ) snake_case_ = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , a__ )
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = False try: _SCREAMING_SNAKE_CASE : Optional[Any] = _is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class _snake_case : def __init__( self , a__ = None , a__ = [] ) -> List[str]: '''simple docstring''' snake_case_ = 0 snake_case_ = choices snake_case_ = prompt if sys.platform == "win32": snake_case_ = "*" else: snake_case_ = "➔ " def lowerCAmelCase__ ( self , a__ , a__ = "" ) -> int: '''simple docstring''' if sys.platform != "win32": writeColor(self.choices[index] , 32 , a__ ) else: forceWrite(self.choices[index] , a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a__ ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def lowerCAmelCase__ ( self , a__ , a__ = 1 ) -> List[str]: '''simple docstring''' snake_case_ = 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 lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a__ )] for number in range(10 )] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = int(chr(self.current_selection ) ) snake_case_ = 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 lowerCAmelCase__ ( self , a__ = 0 ) -> List[str]: '''simple docstring''' 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" ) snake_case_ = 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: snake_case_ = int(builtins.input() ) except ValueError: snake_case_ = default_choice else: snake_case_ = 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
85
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
85
'''simple docstring''' import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def UpperCamelCase_( snake_case : Optional[int] ): '''simple docstring''' return EnvironmentCommand() class _snake_case ( lowercase_ ): @staticmethod def lowerCAmelCase__ ( a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = parser.add_parser("env" ) download_parser.set_defaults(func=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = huggingface_hub.__version__ snake_case_ = "not installed" snake_case_ = "NA" if is_torch_available(): import torch snake_case_ = torch.__version__ snake_case_ = torch.cuda.is_available() snake_case_ = "not installed" if is_transformers_available(): import transformers snake_case_ = transformers.__version__ snake_case_ = "not installed" if is_accelerate_available(): import accelerate snake_case_ = accelerate.__version__ snake_case_ = "not installed" if is_xformers_available(): import xformers snake_case_ = xformers.__version__ snake_case_ = { "`diffusers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "PyTorch version (GPU?)": F'{pt_version} ({pt_cuda_available})', "Huggingface_hub version": hub_version, "Transformers version": transformers_version, "Accelerate version": accelerate_version, "xFormers version": xformers_version, "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(a__ ) ) return info @staticmethod def lowerCAmelCase__ ( a__ ) -> str: '''simple docstring''' return "\n".join([F'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
85
1
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Any class _snake_case : def __init__( self , a__ ) -> str: '''simple docstring''' snake_case_ = data snake_case_ = None class _snake_case : def __init__( self ) -> List[str]: '''simple docstring''' snake_case_ = None snake_case_ = None def __iter__( self ) -> Iterator[Any]: '''simple docstring''' snake_case_ = self.head while self.head: yield node.data snake_case_ = node.next if node == self.head: break def __len__( self ) -> int: '''simple docstring''' return sum(1 for _ in self ) def __repr__( self ) -> Optional[Any]: '''simple docstring''' return "->".join(str(a__ ) for item in iter(self ) ) def lowerCAmelCase__ ( self , a__ ) -> None: '''simple docstring''' self.insert_nth(len(self ) , a__ ) def lowerCAmelCase__ ( self , a__ ) -> None: '''simple docstring''' self.insert_nth(0 , a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> None: '''simple docstring''' if index < 0 or index > len(self ): raise IndexError("list index out of range." ) snake_case_ = Node(a__ ) if self.head is None: snake_case_ = new_node # first node points itself snake_case_ = snake_case_ = new_node elif index == 0: # insert at head snake_case_ = self.head snake_case_ = snake_case_ = new_node else: snake_case_ = self.head for _ in range(index - 1 ): snake_case_ = temp.next snake_case_ = temp.next snake_case_ = new_node if index == len(self ) - 1: # insert at tail snake_case_ = new_node def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' return self.delete_nth(0 ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def lowerCAmelCase__ ( self , a__ = 0 ) -> Any: '''simple docstring''' if not 0 <= index < len(self ): raise IndexError("list index out of range." ) snake_case_ = self.head if self.head == self.tail: # just one node snake_case_ = snake_case_ = None elif index == 0: # delete head node snake_case_ = self.tail.next.next snake_case_ = self.head.next else: snake_case_ = self.head for _ in range(index - 1 ): snake_case_ = temp.next snake_case_ = temp.next snake_case_ = temp.next.next if index == len(self ) - 1: # delete at tail snake_case_ = temp return delete_node.data def lowerCAmelCase__ ( self ) -> bool: '''simple docstring''' return len(self ) == 0 def UpperCamelCase_( ): '''simple docstring''' snake_case_ = CircularLinkedList() assert len(snake_case ) == 0 assert circular_linked_list.is_empty() is True assert str(snake_case ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(snake_case ) == i circular_linked_list.insert_nth(snake_case , i + 1 ) assert str(snake_case ) == "->".join(str(snake_case ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(snake_case ) == "->".join(str(snake_case ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(snake_case ) == "->".join(str(snake_case ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(snake_case ) == "->".join(str(snake_case ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(snake_case ) == "->".join(str(snake_case ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' import os _SCREAMING_SNAKE_CASE : int = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = 0 snake_case_ = 0 while index < len(snake_case ) - 1: snake_case_ = SYMBOLS[numerals[index]] snake_case_ = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = "" snake_case_ = num // 1_0_0_0 numerals += m_count * "M" num %= 1_0_0_0 snake_case_ = num // 1_0_0 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_0_0 snake_case_ = num // 1_0 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 1_0 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def UpperCamelCase_( snake_case : str = "/p089_roman.txt" ): '''simple docstring''' snake_case_ = 0 with open(os.path.dirname(snake_case ) + roman_numerals_filename ) as filea: snake_case_ = filea.readlines() for line in lines: snake_case_ = line.strip() snake_case_ = parse_roman_numerals(snake_case ) snake_case_ = generate_roman_numerals(snake_case ) savings += len(snake_case ) - len(snake_case ) return savings if __name__ == "__main__": print(F"{solution() = }")
85
1
'''simple docstring''' import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = "| <pad> <unk> <s> </s> a b c d e f g h i j k".split() snake_case_ = dict(zip(a__ , range(len(a__ ) ) ) ) snake_case_ = { "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>", } snake_case_ = { "feature_size": 1, "padding_value": 0.0, "sampling_rate": 16_000, "return_attention_mask": False, "do_normalize": True, } snake_case_ = tempfile.mkdtemp() snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) snake_case_ = os.path.join(self.tmpdirname , a__ ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(a__ ) + "\n" ) with open(self.feature_extraction_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(a__ ) + "\n" ) # load decoder from hub snake_case_ = "hf-internal-testing/ngram-beam-search-decoder" def lowerCAmelCase__ ( self , **a__ ) -> Tuple: '''simple docstring''' snake_case_ = self.add_kwargs_tokens_map.copy() kwargs.update(a__ ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **a__ ) def lowerCAmelCase__ ( self , **a__ ) -> int: '''simple docstring''' return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **a__ ) def lowerCAmelCase__ ( self , **a__ ) -> Optional[int]: '''simple docstring''' return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.get_tokenizer() snake_case_ = self.get_feature_extractor() snake_case_ = self.get_decoder() snake_case_ = WavaVecaProcessorWithLM(tokenizer=a__ , feature_extractor=a__ , decoder=a__ ) processor.save_pretrained(self.tmpdirname ) snake_case_ = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , a__ ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , a__ ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , a__ ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match snake_case_ = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(["xx"] ) with self.assertRaisesRegex(a__ , "include" ): WavaVecaProcessorWithLM( tokenizer=a__ , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.get_feature_extractor() snake_case_ = self.get_tokenizer() snake_case_ = self.get_decoder() snake_case_ = WavaVecaProcessorWithLM(tokenizer=a__ , feature_extractor=a__ , decoder=a__ ) snake_case_ = floats_list((3, 1_000) ) snake_case_ = feature_extractor(a__ , return_tensors="np" ) snake_case_ = processor(a__ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.get_feature_extractor() snake_case_ = self.get_tokenizer() snake_case_ = self.get_decoder() snake_case_ = WavaVecaProcessorWithLM(tokenizer=a__ , feature_extractor=a__ , decoder=a__ ) snake_case_ = "This is a test string" snake_case_ = processor(text=a__ ) snake_case_ = tokenizer(a__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCAmelCase__ ( self , a__=(2, 10, 16) , a__=77 ) -> Union[str, Any]: '''simple docstring''' np.random.seed(a__ ) return np.random.rand(*a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.get_feature_extractor() snake_case_ = self.get_tokenizer() snake_case_ = self.get_decoder() snake_case_ = WavaVecaProcessorWithLM(tokenizer=a__ , feature_extractor=a__ , decoder=a__ ) snake_case_ = self._get_dummy_logits(shape=(10, 16) , seed=13 ) snake_case_ = processor.decode(a__ ) snake_case_ = decoder.decode_beams(a__ )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual("</s> <s> </s>" , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ["fork"], ["spawn"]] ) def lowerCAmelCase__ ( self , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = self.get_feature_extractor() snake_case_ = self.get_tokenizer() snake_case_ = self.get_decoder() snake_case_ = WavaVecaProcessorWithLM(tokenizer=a__ , feature_extractor=a__ , decoder=a__ ) snake_case_ = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: snake_case_ = processor.batch_decode(a__ ) else: with get_context(a__ ).Pool() as pool: snake_case_ = processor.batch_decode(a__ , a__ ) snake_case_ = list(a__ ) with get_context("fork" ).Pool() as p: snake_case_ = decoder.decode_beams_batch(a__ , a__ ) snake_case_ , snake_case_ , snake_case_ = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(a__ , decoded_processor.text ) self.assertListEqual(["<s> <s> </s>", "<s> <s> <s>"] , decoded_processor.text ) self.assertListEqual(a__ , decoded_processor.logit_score ) self.assertListEqual(a__ , decoded_processor.lm_score ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.get_feature_extractor() snake_case_ = self.get_tokenizer() snake_case_ = self.get_decoder() snake_case_ = WavaVecaProcessorWithLM(tokenizer=a__ , feature_extractor=a__ , decoder=a__ ) snake_case_ = self._get_dummy_logits() snake_case_ = 15 snake_case_ = -2_0.0 snake_case_ = -4.0 snake_case_ = processor.batch_decode( a__ , beam_width=a__ , beam_prune_logp=a__ , token_min_logp=a__ , ) snake_case_ = decoded_processor_out.text snake_case_ = list(a__ ) with get_context("fork" ).Pool() as pool: snake_case_ = decoder.decode_beams_batch( a__ , a__ , beam_width=a__ , beam_prune_logp=a__ , token_min_logp=a__ , ) snake_case_ = [d[0][0] for d in decoded_decoder_out] snake_case_ = [d[0][2] for d in decoded_decoder_out] snake_case_ = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(a__ , a__ ) self.assertListEqual(["</s> <s> <s>", "<s> <s> <s>"] , a__ ) self.assertTrue(np.array_equal(a__ , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-2_0.0_5_4, -1_8.4_4_7] , a__ , atol=1e-3 ) ) self.assertTrue(np.array_equal(a__ , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-1_5.5_5_4, -1_3.9_4_7_4] , a__ , atol=1e-3 ) ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.get_feature_extractor() snake_case_ = self.get_tokenizer() snake_case_ = self.get_decoder() snake_case_ = WavaVecaProcessorWithLM(tokenizer=a__ , feature_extractor=a__ , decoder=a__ ) snake_case_ = self._get_dummy_logits() snake_case_ = 2.0 snake_case_ = 5.0 snake_case_ = -2_0.0 snake_case_ = True snake_case_ = processor.batch_decode( a__ , alpha=a__ , beta=a__ , unk_score_offset=a__ , lm_score_boundary=a__ , ) snake_case_ = decoded_processor_out.text snake_case_ = list(a__ ) decoder.reset_params( alpha=a__ , beta=a__ , unk_score_offset=a__ , lm_score_boundary=a__ , ) with get_context("fork" ).Pool() as pool: snake_case_ = decoder.decode_beams_batch( a__ , a__ , ) snake_case_ = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(a__ , a__ ) self.assertListEqual(["<s> </s> <s> </s> </s>", "</s> </s> <s> </s> </s>"] , a__ ) snake_case_ = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -2_0.0 ) self.assertEqual(lm_model.score_boundary , a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) snake_case_ = processor.decoder.model_container[processor.decoder._model_key] snake_case_ = Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute() snake_case_ = os.listdir(a__ ) snake_case_ = ["alphabet.json", "language_model"] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = snapshot_download("hf-internal-testing/processor_with_lm" ) snake_case_ = WavaVecaProcessorWithLM.from_pretrained(a__ ) snake_case_ = processor.decoder.model_container[processor.decoder._model_key] snake_case_ = Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute() snake_case_ = os.listdir(a__ ) snake_case_ = os.listdir(a__ ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) snake_case_ = AutoProcessor.from_pretrained("hf-internal-testing/processor_with_lm" ) snake_case_ = floats_list((3, 1_000) ) snake_case_ = processor_wavaveca(a__ , return_tensors="np" ) snake_case_ = processor_auto(a__ , return_tensors="np" ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1e-2 ) snake_case_ = self._get_dummy_logits() snake_case_ = processor_wavaveca.batch_decode(a__ ) snake_case_ = processor_auto.batch_decode(a__ ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.get_feature_extractor() snake_case_ = self.get_tokenizer() snake_case_ = self.get_decoder() snake_case_ = WavaVecaProcessorWithLM(tokenizer=a__ , feature_extractor=a__ , decoder=a__ ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , ) @staticmethod def lowerCAmelCase__ ( a__ , a__ ) -> int: '''simple docstring''' snake_case_ = [d[key] for d in offsets] return retrieved_list def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) snake_case_ = self._get_dummy_logits()[0] snake_case_ = processor.decode(a__ , output_word_offsets=a__ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("text" in outputs ) self.assertTrue("word_offsets" in outputs ) self.assertTrue(isinstance(a__ , a__ ) ) self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"] , "word" ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "word" ) , ["<s>", "<s>", "</s>"] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "start_offset" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "end_offset" ) , [1, 3, 5] ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) snake_case_ = self._get_dummy_logits() snake_case_ = processor.batch_decode(a__ , output_word_offsets=a__ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("text" in outputs ) self.assertTrue("word_offsets" in outputs ) self.assertTrue(isinstance(a__ , a__ ) ) self.assertListEqual( [" ".join(self.get_from_offsets(a__ , "word" ) ) for o in outputs["word_offsets"]] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "word" ) , ["<s>", "<s>", "</s>"] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "start_offset" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "end_offset" ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' import torch snake_case_ = load_dataset("common_voice" , "en" , split="train" , streaming=a__ ) snake_case_ = ds.cast_column("audio" , datasets.Audio(sampling_rate=16_000 ) ) snake_case_ = iter(a__ ) snake_case_ = next(a__ ) snake_case_ = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" ) snake_case_ = WavaVecaForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train snake_case_ = processor(sample["audio"]["array"] , return_tensors="pt" ).input_values with torch.no_grad(): snake_case_ = model(a__ ).logits.cpu().numpy() snake_case_ = processor.decode(logits[0] , output_word_offsets=a__ ) snake_case_ = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate snake_case_ = [ { "start_time": d["start_offset"] * time_offset, "end_time": d["end_offset"] * time_offset, "word": d["word"], } for d in output["word_offsets"] ] snake_case_ = "WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL" # output words self.assertEqual(" ".join(self.get_from_offsets(a__ , "word" ) ) , a__ ) self.assertEqual(" ".join(self.get_from_offsets(a__ , "word" ) ) , output.text ) # output times snake_case_ = torch.tensor(self.get_from_offsets(a__ , "start_time" ) ) snake_case_ = torch.tensor(self.get_from_offsets(a__ , "end_time" ) ) # fmt: off snake_case_ = torch.tensor([1.4_1_9_9, 1.6_5_9_9, 2.2_5_9_9, 3.0, 3.2_4, 3.5_9_9_9, 3.7_9_9_9, 4.0_9_9_9, 4.2_6, 4.9_4, 5.2_8, 5.6_5_9_9, 5.7_8, 5.9_4, 6.3_2, 6.5_3_9_9, 6.6_5_9_9] ) snake_case_ = torch.tensor([1.5_3_9_9, 1.8_9_9_9, 2.9, 3.1_6, 3.5_3_9_9, 3.7_2, 4.0_1_9_9, 4.1_7_9_9, 4.7_6, 5.1_5_9_9, 5.5_5_9_9, 5.6_9_9_9, 5.8_6, 6.1_9_9_9, 6.3_8, 6.6_1_9_9, 6.9_4] ) # fmt: on self.assertTrue(torch.allclose(a__ , a__ , atol=0.0_1 ) ) self.assertTrue(torch.allclose(a__ , a__ , atol=0.0_1 ) )
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _SCREAMING_SNAKE_CASE : int = { "configuration_clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig", ], "processing_clip": ["CLIPProcessor"], "tokenization_clip": ["CLIPTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = ["CLIPTokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = ["CLIPFeatureExtractor"] _SCREAMING_SNAKE_CASE : Dict = ["CLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : int , snake_case : int ): '''simple docstring''' return int((input_a, input_a).count(1 ) != 0 ) def UpperCamelCase_( ): '''simple docstring''' 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))
85
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE : Union[str, Any] = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } _SCREAMING_SNAKE_CASE : int = { "gpt-neox-20b": 2048, } class _snake_case ( lowercase_ ): lowerCAmelCase_ : str = VOCAB_FILES_NAMES lowerCAmelCase_ : Tuple = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ : str = ["input_ids", "attention_mask"] def __init__( self , a__=None , a__=None , a__=None , a__="<|endoftext|>" , a__="<|endoftext|>" , a__="<|endoftext|>" , a__=False , **a__ , ) -> Tuple: '''simple docstring''' super().__init__( a__ , a__ , tokenizer_file=a__ , unk_token=a__ , bos_token=a__ , eos_token=a__ , add_prefix_space=a__ , **a__ , ) snake_case_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , a__ ) != add_prefix_space: snake_case_ = getattr(a__ , pre_tok_state.pop("type" ) ) snake_case_ = add_prefix_space snake_case_ = pre_tok_class(**a__ ) snake_case_ = add_prefix_space def lowerCAmelCase__ ( self , a__ , a__ = None ) -> Tuple[str]: '''simple docstring''' snake_case_ = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ ) def lowerCAmelCase__ ( self , a__ ) -> List[int]: '''simple docstring''' snake_case_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(a__ , add_special_tokens=a__ ) + [self.eos_token_id] ) if len(a__ ) > self.model_max_length: snake_case_ = input_ids[-self.model_max_length :] return input_ids
85
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : Union[str, Any] = StableDiffusionLDMaDPipeline lowerCAmelCase_ : int = TEXT_TO_IMAGE_PARAMS lowerCAmelCase_ : str = TEXT_TO_IMAGE_BATCH_PARAMS lowerCAmelCase_ : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) snake_case_ = 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 ) snake_case_ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=6 , out_channels=6 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) snake_case_ = CLIPTextModel(a__ ) snake_case_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) snake_case_ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def lowerCAmelCase__ ( self , a__ , a__=0 ) -> List[str]: '''simple docstring''' if str(a__ ).startswith("mps" ): snake_case_ = torch.manual_seed(a__ ) else: snake_case_ = torch.Generator(device=a__ ).manual_seed(a__ ) snake_case_ = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case_ = self.get_dummy_components() snake_case_ = StableDiffusionLDMaDPipeline(**a__ ) snake_case_ = ldmad_pipe.to(a__ ) ldmad_pipe.set_progress_bar_config(disable=a__ ) snake_case_ = self.get_dummy_inputs(a__ ) snake_case_ = ldmad_pipe(**a__ ) snake_case_ , snake_case_ = output.rgb, output.depth snake_case_ = rgb[0, -3:, -3:, -1] snake_case_ = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) snake_case_ = np.array( [0.3_7_3_3_8_1_7_6, 0.7_0_2_4_7, 0.7_4_2_0_3_1_9_3, 0.5_1_6_4_3_6_0_4, 0.5_8_2_5_6_7_9_3, 0.6_0_9_3_2_1_3_6, 0.4_1_8_1_0_9_5, 0.4_8_3_5_5_8_7_7, 0.4_6_5_3_5_2_6_2] ) snake_case_ = np.array([1_0_3.4_6_7_2_7, 8_5.8_1_2_0_0_4, 8_7.8_4_9_2_3_6] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1e-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1e-2 def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.get_dummy_components() snake_case_ = StableDiffusionLDMaDPipeline(**a__ ) snake_case_ = ldmad_pipe.to(a__ ) ldmad_pipe.set_progress_bar_config(disable=a__ ) snake_case_ = self.get_dummy_inputs(a__ ) snake_case_ = 3 * [inputs["prompt"]] # forward snake_case_ = ldmad_pipe(**a__ ) snake_case_ , snake_case_ = output.rgb, output.depth snake_case_ = rgb_slice_a[0, -3:, -3:, -1] snake_case_ = depth_slice_a[0, -3:, -1] snake_case_ = self.get_dummy_inputs(a__ ) snake_case_ = 3 * [inputs.pop("prompt" )] snake_case_ = ldmad_pipe.tokenizer( a__ , padding="max_length" , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=a__ , return_tensors="pt" , ) snake_case_ = text_inputs["input_ids"].to(a__ ) snake_case_ = ldmad_pipe.text_encoder(a__ )[0] snake_case_ = prompt_embeds # forward snake_case_ = ldmad_pipe(**a__ ) snake_case_ , snake_case_ = output.rgb, output.depth snake_case_ = rgb_slice_a[0, -3:, -3:, -1] snake_case_ = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1e-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1e-4 def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case_ = self.get_dummy_components() snake_case_ = PNDMScheduler(skip_prk_steps=a__ ) snake_case_ = StableDiffusionLDMaDPipeline(**a__ ) snake_case_ = ldmad_pipe.to(a__ ) ldmad_pipe.set_progress_bar_config(disable=a__ ) snake_case_ = self.get_dummy_inputs(a__ ) snake_case_ = "french fries" snake_case_ = ldmad_pipe(**a__ , negative_prompt=a__ ) snake_case_ , snake_case_ = output.rgb, output.depth snake_case_ = rgb[0, -3:, -3:, -1] snake_case_ = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) snake_case_ = np.array( [0.3_7_0_4_4, 0.7_1_8_1_1_5_0_3, 0.7_2_2_3_2_5_1, 0.4_8_6_0_3_6_7_5, 0.5_6_3_8_3_9_1, 0.6_3_6_4_9_4_8, 0.4_2_8_3_3_7_0_4, 0.4_9_0_1_3_1_5, 0.4_7_9_2_6_2_1_7] ) snake_case_ = np.array([1_0_7.8_4_7_3_8, 8_4.6_2_8_0_2, 8_9.9_6_2_1_3_5] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1e-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1e-2 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self , a__ , a__="cpu" , a__=torch.floataa , a__=0 ) -> Optional[Any]: '''simple docstring''' snake_case_ = torch.Generator(device=a__ ).manual_seed(a__ ) snake_case_ = np.random.RandomState(a__ ).standard_normal((1, 4, 64, 64) ) snake_case_ = torch.from_numpy(a__ ).to(device=a__ , dtype=a__ ) snake_case_ = { "prompt": "a photograph of an astronaut riding a horse", "latents": latents, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" ) snake_case_ = ldmad_pipe.to(a__ ) ldmad_pipe.set_progress_bar_config(disable=a__ ) snake_case_ = self.get_inputs(a__ ) snake_case_ = ldmad_pipe(**a__ ) snake_case_ , snake_case_ = output.rgb, output.depth snake_case_ = rgb[0, -3:, -3:, -1].flatten() snake_case_ = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) snake_case_ = np.array( [0.5_3_8_0_5_4_6_5, 0.5_6_7_0_7_3_0_5, 0.5_4_8_6_5_1_5, 0.5_7_0_1_2_2_3_6, 0.5_8_1_4_5_1_1, 0.5_6_2_5_3_4_8_7, 0.5_4_8_4_3_0_1_4, 0.5_5_0_9_2_2_6_3, 0.6_4_5_9_7_0_6] ) snake_case_ = np.array( [0.9_2_6_3_7_8_1, 0.6_6_7_8_6_7_2, 0.5_4_8_6_5_1_5, 0.9_2_2_0_2_1_4_5, 0.6_7_8_3_1_1_3_5, 0.5_6_2_5_3_4_8_7, 0.9_2_4_1_6_9_4, 0.7_5_5_1_4_7_8, 0.6_4_5_9_7_0_6] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3e-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3e-3 @nightly @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self , a__ , a__="cpu" , a__=torch.floataa , a__=0 ) -> Union[str, Any]: '''simple docstring''' snake_case_ = torch.Generator(device=a__ ).manual_seed(a__ ) snake_case_ = np.random.RandomState(a__ ).standard_normal((1, 4, 64, 64) ) snake_case_ = torch.from_numpy(a__ ).to(device=a__ , dtype=a__ ) snake_case_ = { "prompt": "a photograph of an astronaut riding a horse", "latents": latents, "generator": generator, "num_inference_steps": 50, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" ).to(a__ ) ldmad_pipe.set_progress_bar_config(disable=a__ ) snake_case_ = self.get_inputs(a__ ) snake_case_ = ldmad_pipe(**a__ ) snake_case_ , snake_case_ = output.rgb, output.depth snake_case_ = 0.4_9_5_5_8_6 snake_case_ = 0.3_3_7_9_5_5_1_5 snake_case_ = 1_1_2.4_8_5_1_8 snake_case_ = 9_8.4_8_9_7_4_6 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3 assert np.abs(expected_depth_std - depth.std() ) < 1e-3 def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d-4c" ).to(a__ ) ldmad_pipe.set_progress_bar_config(disable=a__ ) snake_case_ = self.get_inputs(a__ ) snake_case_ = ldmad_pipe(**a__ ) snake_case_ , snake_case_ = output.rgb, output.depth snake_case_ = 0.4_1_9_4_1_2_7 snake_case_ = 0.3_5_3_7_5_5_8_6 snake_case_ = 0.5_6_3_8_5_0_2 snake_case_ = 0.3_4_6_8_6_1_0_3 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3 assert np.abs(expected_depth_std - depth.std() ) < 1e-3
85
'''simple docstring''' import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def UpperCamelCase_( snake_case : Tuple ): '''simple docstring''' snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = 0.01 with locka.acquire(): with pytest.raises(snake_case ): snake_case_ = time.time() locka.acquire(snake_case ) assert time.time() - _start > timeout def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = "a" * 1_0_0_0 + ".lock" snake_case_ = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(snake_case ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 snake_case_ = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case ): locka.acquire(0 )
85
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Tuple = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE : str = { "vocab_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt" ), "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt", "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt" ), }, "tokenizer_file": { "squeezebert/squeezebert-uncased": ( "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli": ( "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json" ), "squeezebert/squeezebert-mnli-headless": ( "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json" ), }, } _SCREAMING_SNAKE_CASE : List[Any] = { "squeezebert/squeezebert-uncased": 512, "squeezebert/squeezebert-mnli": 512, "squeezebert/squeezebert-mnli-headless": 512, } _SCREAMING_SNAKE_CASE : str = { "squeezebert/squeezebert-uncased": {"do_lower_case": True}, "squeezebert/squeezebert-mnli": {"do_lower_case": True}, "squeezebert/squeezebert-mnli-headless": {"do_lower_case": True}, } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Tuple = VOCAB_FILES_NAMES lowerCAmelCase_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ : Dict = SqueezeBertTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ) -> Dict: '''simple docstring''' super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) snake_case_ = 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 ): snake_case_ = getattr(a__ , normalizer_state.pop("type" ) ) snake_case_ = do_lower_case snake_case_ = strip_accents snake_case_ = tokenize_chinese_chars snake_case_ = normalizer_class(**a__ ) snake_case_ = do_lower_case def lowerCAmelCase__ ( self , a__ , a__=None ) -> Union[str, Any]: '''simple docstring''' snake_case_ = [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 lowerCAmelCase__ ( self , a__ , a__ = None ) -> List[int]: '''simple docstring''' snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase__ ( self , a__ , a__ = None ) -> Tuple[str]: '''simple docstring''' snake_case_ = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _snake_case ( datasets.BuilderConfig ): lowerCAmelCase_ : Optional[datasets.Features] = None def UpperCamelCase_( snake_case : "pyspark.sql.DataFrame" , snake_case : List[int] , ): '''simple docstring''' import pyspark def generate_fn(): snake_case_ = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: snake_case_ = df_with_partition_id.select("*" ).where(f'part_id = {partition_id}' ).drop("part_id" ) snake_case_ = partition_df.collect() snake_case_ = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class _snake_case ( _BaseExamplesIterable ): def __init__( self , a__ , a__=None , ) -> Any: '''simple docstring''' snake_case_ = df snake_case_ = partition_order or range(self.df.rdd.getNumPartitions() ) snake_case_ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Union[str, Any]: '''simple docstring''' yield from self.generate_examples_fn() def lowerCAmelCase__ ( self , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = self.split_shard_indices_by_worker(a__ , a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) @property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return len(self.partition_order ) class _snake_case ( datasets.DatasetBuilder ): lowerCAmelCase_ : Dict = SparkConfig def __init__( self , a__ , a__ = None , a__ = None , **a__ , ) -> str: '''simple docstring''' import pyspark snake_case_ = pyspark.sql.SparkSession.builder.getOrCreate() snake_case_ = df snake_case_ = working_dir super().__init__( cache_dir=a__ , config_name=str(self.df.semanticHash() ) , **a__ , ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' def create_cache_and_write_probe(a__ ): # 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__ ) snake_case_ = 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: snake_case_ = ( 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 lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' import pyspark def get_arrow_batch_size(a__ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) snake_case_ = self.df.count() snake_case_ = 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. snake_case_ = ( 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 ) snake_case_ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. snake_case_ = min(a__ , int(approx_total_size / max_shard_size ) ) snake_case_ = self.df.repartition(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: '''simple docstring''' import pyspark snake_case_ = ParquetWriter if file_format == "parquet" else ArrowWriter snake_case_ = os.path.join(self._working_dir , os.path.basename(a__ ) ) if self._working_dir else fpath snake_case_ = 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. snake_case_ = self.config.features snake_case_ = self._writer_batch_size snake_case_ = self._fs.storage_options def write_arrow(a__ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. snake_case_ = pyspark.TaskContext().taskAttemptId() snake_case_ = 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"] , ) snake_case_ = 0 snake_case_ = 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__ , ) snake_case_ = 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: snake_case_ , snake_case_ = 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 snake_case_ = 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__ , ) snake_case_ = pa.Table.from_batches([batch] ) writer.write_table(a__ ) if writer._num_bytes > 0: snake_case_ , snake_case_ = 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__ ) ): snake_case_ = os.path.join(os.path.dirname(a__ ) , os.path.basename(a__ ) ) shutil.move(a__ , a__ ) snake_case_ = ( 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 lowerCAmelCase__ ( self , a__ , a__ = "arrow" , a__ = None , a__ = None , **a__ , ) -> int: '''simple docstring''' self._validate_cache_dir() snake_case_ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a__ ) snake_case_ = not is_remote_filesystem(self._fs ) snake_case_ = os.path.join if is_local else posixpath.join snake_case_ = "-TTTTT-SSSSS-of-NNNNN" snake_case_ = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' snake_case_ = path_join(self._output_dir , a__ ) snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = [] snake_case_ = [] for task_id, content in self._prepare_split_single(a__ , a__ , a__ ): ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = 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__ ) snake_case_ = total_num_examples snake_case_ = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: snake_case_ = 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. snake_case_ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a__ , a__ , a__ , ): 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}' ) , ) snake_case_ = [] snake_case_ = 0 for i in range(len(a__ ) ): snake_case_ , snake_case_ = 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 snake_case_ = 0 snake_case_ = 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 lowerCAmelCase__ ( self , a__ , ) -> SparkExamplesIterable: '''simple docstring''' return SparkExamplesIterable(self.df )
85
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[int] = { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/config.json", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/config.json", "funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json", "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/config.json", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json", "funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json", } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Optional[int] = "funnel" lowerCAmelCase_ : Tuple = { "hidden_size": "d_model", "num_attention_heads": "n_head", } def __init__( self , a__=30_522 , a__=[4, 4, 4] , a__=None , a__=2 , a__=768 , a__=12 , a__=64 , a__=3_072 , a__="gelu_new" , a__=0.1 , a__=0.1 , a__=0.0 , a__=0.1 , a__=None , a__=1e-9 , a__="mean" , a__="relative_shift" , a__=True , a__=True , a__=True , **a__ , ) -> Optional[int]: '''simple docstring''' snake_case_ = vocab_size snake_case_ = block_sizes snake_case_ = [1] * len(a__ ) if block_repeats is None else block_repeats assert len(a__ ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." snake_case_ = num_decoder_layers snake_case_ = d_model snake_case_ = n_head snake_case_ = d_head snake_case_ = d_inner snake_case_ = hidden_act snake_case_ = hidden_dropout snake_case_ = attention_dropout snake_case_ = activation_dropout snake_case_ = initializer_range snake_case_ = initializer_std snake_case_ = layer_norm_eps assert pooling_type in [ "mean", "max", ], F'Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.' snake_case_ = pooling_type assert attention_type in [ "relative_shift", "factorized", ], F'Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.' snake_case_ = attention_type snake_case_ = separate_cls snake_case_ = truncate_seq snake_case_ = pool_q_only super().__init__(**a__ ) @property def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return sum(self.block_sizes ) @num_hidden_layers.setter def lowerCAmelCase__ ( self , a__ ) -> List[Any]: '''simple docstring''' raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`." ) @property def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' return len(self.block_sizes ) @num_blocks.setter def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' raise NotImplementedError("This model does not support the setting of `num_blocks`. Please set `block_sizes`." )
85
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB 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 typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : List[str] = { "configuration_cpmant": ["CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CpmAntConfig"], "tokenization_cpmant": ["CpmAntTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST", "CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _snake_case : @staticmethod def lowerCAmelCase__ ( *a__ , **a__ ) -> List[str]: '''simple docstring''' pass @is_pipeline_test @require_vision @require_timm @require_torch class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : str = MODEL_FOR_OBJECT_DETECTION_MAPPING def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> Tuple: '''simple docstring''' snake_case_ = ObjectDetectionPipeline(model=a__ , image_processor=a__ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def lowerCAmelCase__ ( self , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png" , threshold=0.0 ) self.assertGreater(len(a__ ) , 0 ) for detected_object in outputs: self.assertEqual( a__ , { "score": ANY(a__ ), "label": ANY(a__ ), "box": {"xmin": ANY(a__ ), "ymin": ANY(a__ ), "xmax": ANY(a__ ), "ymax": ANY(a__ )}, } , ) import datasets snake_case_ = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test" ) snake_case_ = [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ), "http://images.cocodataset.org/val2017/000000039769.jpg", # RGBA dataset[0]["file"], # LA dataset[1]["file"], # L dataset[2]["file"], ] snake_case_ = object_detector(a__ , threshold=0.0 ) self.assertEqual(len(a__ ) , len(a__ ) ) for outputs in batch_outputs: self.assertGreater(len(a__ ) , 0 ) for detected_object in outputs: self.assertEqual( a__ , { "score": ANY(a__ ), "label": ANY(a__ ), "box": {"xmin": ANY(a__ ), "ymin": ANY(a__ ), "xmax": ANY(a__ ), "ymax": ANY(a__ )}, } , ) @require_tf @unittest.skip("Object detection not implemented in TF" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' pass @require_torch def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = "hf-internal-testing/tiny-detr-mobilenetsv3" snake_case_ = AutoModelForObjectDetection.from_pretrained(a__ ) snake_case_ = AutoFeatureExtractor.from_pretrained(a__ ) snake_case_ = ObjectDetectionPipeline(model=a__ , feature_extractor=a__ ) snake_case_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=0.0 ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ] , ) snake_case_ = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ], [ {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, {"score": 0.3_3_7_6, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, ], ] , ) @require_torch @slow def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "facebook/detr-resnet-50" snake_case_ = AutoModelForObjectDetection.from_pretrained(a__ ) snake_case_ = AutoFeatureExtractor.from_pretrained(a__ ) snake_case_ = ObjectDetectionPipeline(model=a__ , feature_extractor=a__ ) snake_case_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) snake_case_ = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], ] , ) @require_torch @slow def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "facebook/detr-resnet-50" snake_case_ = pipeline("object-detection" , model=a__ ) snake_case_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) snake_case_ = object_detector( [ "http://images.cocodataset.org/val2017/000000039769.jpg", "http://images.cocodataset.org/val2017/000000039769.jpg", ] ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], [ {"score": 0.9_9_8_2, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, {"score": 0.9_9_6_0, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, {"score": 0.9_9_5_5, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ], ] , ) @require_torch @slow def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = 0.9_9_8_5 snake_case_ = "facebook/detr-resnet-50" snake_case_ = pipeline("object-detection" , model=a__ ) snake_case_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=a__ ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.9_9_8_8, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, {"score": 0.9_9_8_7, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, ] , ) @require_torch @require_pytesseract @slow def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "Narsil/layoutlmv3-finetuned-funsd" snake_case_ = 0.9_9_9_3 snake_case_ = pipeline("object-detection" , model=a__ , threshold=a__ ) snake_case_ = object_detector( "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png" ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {"score": 0.9_9_9_3, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}}, {"score": 0.9_9_9_3, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}}, ] , )
85
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu _SCREAMING_SNAKE_CASE : Union[str, Any] = False class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return 32 @property def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 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 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(a__ ) @property def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 12 snake_case_ = 12 snake_case_ = { "attention_bias": True, "cross_attention_dim": 32, "attention_head_dim": height * width, "num_attention_heads": 1, "num_vector_embeds": self.num_embed, "num_embeds_ada_norm": self.num_embeds_ada_norm, "norm_num_groups": 32, "sample_size": width, "activation_fn": "geglu-approximate", } snake_case_ = TransformeraDModel(**a__ ) return model def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings(learnable=a__ ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_5_5_1, 0.6_1_6_8, 0.5_0_0_8, 0.5_6_7_6, 0.5_6_5_9, 0.4_2_9_5, 0.6_0_7_3, 0.5_5_9_9, 0.4_9_9_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings( learnable=a__ , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_6_9_3, 0.6_0_7_5, 0.4_9_5_9, 0.5_7_0_1, 0.5_5_8_3, 0.4_3_3_3, 0.6_1_7_1, 0.5_6_8_4, 0.4_9_8_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy" ) snake_case_ = VQDiffusionPipeline.from_pretrained("microsoft/vq-diffusion-ithq" ) snake_case_ = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipeline( "teddy bear playing in the pool" , num_images_per_prompt=1 , generator=a__ , output_type="np" , ) snake_case_ = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
85
1
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = logging.get_logger() # the current default level is logging.WARNING snake_case_ = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = logging.get_verbosity() snake_case_ = logging.get_logger("transformers.models.bart.tokenization_bart" ) snake_case_ = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(a__ ) as cl: logger.warning(a__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(a__ ) as cl: logger.warning(a__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(a__ ) as cl: logger.warning(a__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(a__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' transformers.utils.logging._reset_library_root_logger() # this action activates the env var snake_case_ = logging.get_logger("transformers.models.bart.tokenization_bart" ) snake_case_ = os.getenv("TRANSFORMERS_VERBOSITY" , a__ ) snake_case_ = logging.log_levels[env_level_str] snake_case_ = logging.get_verbosity() self.assertEqual( a__ , a__ , F'TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}' , ) # restore to the original level snake_case_ = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' transformers.utils.logging._reset_library_root_logger() snake_case_ = logging.logging.getLogger() with CaptureLogger(a__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' transformers.utils.logging._reset_library_root_logger() snake_case_ = logging.get_logger("transformers.models.bart.tokenization_bart" ) snake_case_ = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(a__ ) as cl: logger.warning_advice(a__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(a__ ) as cl: logger.warning_advice(a__ ) self.assertEqual(cl.out , msg + "\n" ) def UpperCamelCase_( ): '''simple docstring''' disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
85
'''simple docstring''' from statistics import mean, stdev def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = min(snake_case ) snake_case_ = max(snake_case ) # normalize data return [round((x - x_min) / (x_max - x_min) , snake_case ) for x in data] def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = mean(snake_case ) snake_case_ = stdev(snake_case ) # standardize data return [round((x - mu) / (sigma) , snake_case ) for x in data]
85
1
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , lowercase_ ): def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = load_tool("text-classification" ) self.tool.setup() snake_case_ = load_tool("text-classification" , remote=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" )
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : str = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
85
1
'''simple docstring''' from __future__ import annotations _SCREAMING_SNAKE_CASE : Optional[Any] = 8.988e9 # units = N * m^s * C^-2 def UpperCamelCase_( snake_case : float , snake_case : float , snake_case : float , snake_case : float ): '''simple docstring''' snake_case_ = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if distance < 0: raise ValueError("Distance cannot be negative" ) if force == 0: snake_case_ = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: snake_case_ = abs(snake_case ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: snake_case_ = abs(snake_case ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: snake_case_ = (COULOMBS_CONSTANT * charge_product / abs(snake_case )) ** 0.5 return {"distance": distance} raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. snake_case_ = min(snake_case , snake_case ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
85
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _SCREAMING_SNAKE_CASE : Dict = { "configuration_rag": ["RagConfig"], "retrieval_rag": ["RagRetriever"], "tokenization_rag": ["RagTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = [ "RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = [ "TFRagModel", "TFRagPreTrainedModel", "TFRagSequenceForGeneration", "TFRagTokenForGeneration", ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys _SCREAMING_SNAKE_CASE : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE : Tuple = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConditionalDetrConfig", "ConditionalDetrOnnxConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = ["ConditionalDetrFeatureExtractor"] _SCREAMING_SNAKE_CASE : List[Any] = ["ConditionalDetrImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Dict = [ "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "ConditionalDetrForObjectDetection", "ConditionalDetrForSegmentation", "ConditionalDetrModel", "ConditionalDetrPreTrainedModel", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : Any = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = ["EncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = ["TFEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = ["FlaxEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--txt2img_unclip", default="kakaobrain/karlo-v1-alpha", type=str, required=False, help="The pretrained txt2img unclip.", ) _SCREAMING_SNAKE_CASE : int = parser.parse_args() _SCREAMING_SNAKE_CASE : List[Any] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor() _SCREAMING_SNAKE_CASE : str = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") _SCREAMING_SNAKE_CASE : int = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
85
1
'''simple docstring''' _SCREAMING_SNAKE_CASE : str = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] _SCREAMING_SNAKE_CASE : Dict = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] _SCREAMING_SNAKE_CASE : Optional[Any] = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def UpperCamelCase_( snake_case : int , snake_case : int , snake_case : int ): '''simple docstring''' assert len(str(snake_case ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 1_2, "month should be between 1 to 12" assert 1 <= day <= 3_1, "day should be between 1 to 31" # Doomsday algorithm: snake_case_ = year // 1_0_0 snake_case_ = (5 * (century % 4) + 2) % 7 snake_case_ = year % 1_0_0 snake_case_ = centurian % 1_2 snake_case_ = ( (centurian // 1_2) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 snake_case_ = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_0_0) == 0) else DOOMSDAY_LEAP[month - 1] ) snake_case_ = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "upernet" def __init__( self , a__=None , a__=512 , a__=0.0_2 , a__=[1, 2, 3, 6] , a__=True , a__=0.4 , a__=384 , a__=256 , a__=1 , a__=False , a__=255 , **a__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**a__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) snake_case_ = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a__ , a__ ): snake_case_ = backbone_config.get("model_type" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(a__ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = False try: _SCREAMING_SNAKE_CASE : Optional[Any] = _is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class _snake_case : def __init__( self , a__ = None , a__ = [] ) -> List[str]: '''simple docstring''' snake_case_ = 0 snake_case_ = choices snake_case_ = prompt if sys.platform == "win32": snake_case_ = "*" else: snake_case_ = "➔ " def lowerCAmelCase__ ( self , a__ , a__ = "" ) -> int: '''simple docstring''' if sys.platform != "win32": writeColor(self.choices[index] , 32 , a__ ) else: forceWrite(self.choices[index] , a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a__ ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def lowerCAmelCase__ ( self , a__ , a__ = 1 ) -> List[str]: '''simple docstring''' snake_case_ = 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 lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a__ )] for number in range(10 )] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = int(chr(self.current_selection ) ) snake_case_ = 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 lowerCAmelCase__ ( self , a__ = 0 ) -> List[str]: '''simple docstring''' 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" ) snake_case_ = 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: snake_case_ = int(builtins.input() ) except ValueError: snake_case_ = default_choice else: snake_case_ = 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
85
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def UpperCamelCase_( snake_case : Any ): '''simple docstring''' if ( (cp >= 0X4E00 and cp <= 0X9FFF) or (cp >= 0X3400 and cp <= 0X4DBF) # or (cp >= 0X2_0000 and cp <= 0X2_A6DF) # or (cp >= 0X2_A700 and cp <= 0X2_B73F) # or (cp >= 0X2_B740 and cp <= 0X2_B81F) # or (cp >= 0X2_B820 and cp <= 0X2_CEAF) # or (cp >= 0XF900 and cp <= 0XFAFF) or (cp >= 0X2_F800 and cp <= 0X2_FA1F) # ): # return True return False def UpperCamelCase_( snake_case : str ): '''simple docstring''' for char in word: snake_case_ = ord(snake_case ) if not _is_chinese_char(snake_case ): return 0 return 1 def UpperCamelCase_( snake_case : List[str] ): '''simple docstring''' snake_case_ = set() for token in tokens: snake_case_ = len(snake_case ) > 1 and is_chinese(snake_case ) if chinese_word: word_set.add(snake_case ) snake_case_ = list(snake_case ) return word_list def UpperCamelCase_( snake_case : List[str] , snake_case : set() ): '''simple docstring''' if not chinese_word_set: return bert_tokens snake_case_ = max([len(snake_case ) for w in chinese_word_set] ) snake_case_ = bert_tokens snake_case_ , snake_case_ = 0, len(snake_case ) while start < end: snake_case_ = True if is_chinese(bert_word[start] ): snake_case_ = min(end - start , snake_case ) for i in range(snake_case , 1 , -1 ): snake_case_ = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): snake_case_ = "##" + bert_word[j] snake_case_ = start + i snake_case_ = False break if single_word: start += 1 return bert_word def UpperCamelCase_( snake_case : List[str] , snake_case : LTP , snake_case : BertTokenizer ): '''simple docstring''' snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = ltp_tokenizer.pipeline(lines[i : i + 1_0_0] , tasks=["cws"] ).cws snake_case_ = [get_chinese_word(snake_case ) for r in res] ltp_res.extend(snake_case ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=snake_case , truncation=snake_case , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for input_ids, chinese_word in zip(snake_case , snake_case ): snake_case_ = [] for id in input_ids: snake_case_ = bert_tokenizer._convert_id_to_token(snake_case ) input_tokens.append(snake_case ) snake_case_ = add_sub_symbol(snake_case , snake_case ) snake_case_ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(snake_case ): if token[:2] == "##": snake_case_ = token[2:] # save chinese tokens' pos if len(snake_case ) == 1 and _is_chinese_char(ord(snake_case ) ): ref_id.append(snake_case ) ref_ids.append(snake_case ) assert len(snake_case ) == len(snake_case ) return ref_ids def UpperCamelCase_( snake_case : Any ): '''simple docstring''' with open(args.file_name , "r" , encoding="utf-8" ) as f: snake_case_ = f.readlines() snake_case_ = [line.strip() for line in data if len(snake_case ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' snake_case_ = LTP(args.ltp ) # faster in GPU device snake_case_ = BertTokenizer.from_pretrained(args.bert ) snake_case_ = prepare_ref(snake_case , snake_case , snake_case ) with open(args.save_path , "w" , encoding="utf-8" ) as f: snake_case_ = [json.dumps(snake_case ) + "\n" for ref in ref_ids] f.writelines(snake_case ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", required=False, type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", required=False, type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path", ) parser.add_argument( "--bert", required=False, type=str, default="./resources/robert", help="resources for Bert tokenizer", ) parser.add_argument( "--save_path", required=False, type=str, default="./resources/ref.txt", help="path to save res", ) _SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() main(args)
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : int = 5_0 ): '''simple docstring''' snake_case_ = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"{solution() = }")
85
'''simple docstring''' import warnings from functools import wraps from typing import Callable def UpperCamelCase_( snake_case : Callable ): '''simple docstring''' @wraps(snake_case ) def _inner_fn(*snake_case : Optional[int] , **snake_case : List[Any] ): warnings.warn( (f'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , snake_case , ) return fn(*snake_case , **snake_case ) return _inner_fn
85
1
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _snake_case ( datasets.BuilderConfig ): lowerCAmelCase_ : Optional[datasets.Features] = None def UpperCamelCase_( snake_case : "pyspark.sql.DataFrame" , snake_case : List[int] , ): '''simple docstring''' import pyspark def generate_fn(): snake_case_ = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: snake_case_ = df_with_partition_id.select("*" ).where(f'part_id = {partition_id}' ).drop("part_id" ) snake_case_ = partition_df.collect() snake_case_ = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class _snake_case ( _BaseExamplesIterable ): def __init__( self , a__ , a__=None , ) -> Any: '''simple docstring''' snake_case_ = df snake_case_ = partition_order or range(self.df.rdd.getNumPartitions() ) snake_case_ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Union[str, Any]: '''simple docstring''' yield from self.generate_examples_fn() def lowerCAmelCase__ ( self , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = self.split_shard_indices_by_worker(a__ , a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) @property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return len(self.partition_order ) class _snake_case ( datasets.DatasetBuilder ): lowerCAmelCase_ : Dict = SparkConfig def __init__( self , a__ , a__ = None , a__ = None , **a__ , ) -> str: '''simple docstring''' import pyspark snake_case_ = pyspark.sql.SparkSession.builder.getOrCreate() snake_case_ = df snake_case_ = working_dir super().__init__( cache_dir=a__ , config_name=str(self.df.semanticHash() ) , **a__ , ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' def create_cache_and_write_probe(a__ ): # 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__ ) snake_case_ = 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: snake_case_ = ( 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 lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' import pyspark def get_arrow_batch_size(a__ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) snake_case_ = self.df.count() snake_case_ = 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. snake_case_ = ( 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 ) snake_case_ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. snake_case_ = min(a__ , int(approx_total_size / max_shard_size ) ) snake_case_ = self.df.repartition(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: '''simple docstring''' import pyspark snake_case_ = ParquetWriter if file_format == "parquet" else ArrowWriter snake_case_ = os.path.join(self._working_dir , os.path.basename(a__ ) ) if self._working_dir else fpath snake_case_ = 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. snake_case_ = self.config.features snake_case_ = self._writer_batch_size snake_case_ = self._fs.storage_options def write_arrow(a__ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. snake_case_ = pyspark.TaskContext().taskAttemptId() snake_case_ = 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"] , ) snake_case_ = 0 snake_case_ = 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__ , ) snake_case_ = 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: snake_case_ , snake_case_ = 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 snake_case_ = 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__ , ) snake_case_ = pa.Table.from_batches([batch] ) writer.write_table(a__ ) if writer._num_bytes > 0: snake_case_ , snake_case_ = 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__ ) ): snake_case_ = os.path.join(os.path.dirname(a__ ) , os.path.basename(a__ ) ) shutil.move(a__ , a__ ) snake_case_ = ( 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 lowerCAmelCase__ ( self , a__ , a__ = "arrow" , a__ = None , a__ = None , **a__ , ) -> int: '''simple docstring''' self._validate_cache_dir() snake_case_ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a__ ) snake_case_ = not is_remote_filesystem(self._fs ) snake_case_ = os.path.join if is_local else posixpath.join snake_case_ = "-TTTTT-SSSSS-of-NNNNN" snake_case_ = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' snake_case_ = path_join(self._output_dir , a__ ) snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = [] snake_case_ = [] for task_id, content in self._prepare_split_single(a__ , a__ , a__ ): ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = 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__ ) snake_case_ = total_num_examples snake_case_ = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: snake_case_ = 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. snake_case_ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a__ , a__ , a__ , ): 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}' ) , ) snake_case_ = [] snake_case_ = 0 for i in range(len(a__ ) ): snake_case_ , snake_case_ = 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 snake_case_ = 0 snake_case_ = 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 lowerCAmelCase__ ( self , a__ , ) -> SparkExamplesIterable: '''simple docstring''' return SparkExamplesIterable(self.df )
85
'''simple docstring''' from __future__ import annotations import requests def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case ).json() def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' snake_case_ = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" snake_case_ = requests.get(snake_case ).json()[:max_stories] return [get_hackernews_story(snake_case ) for story_id in story_ids] def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' snake_case_ = hackernews_top_stories(snake_case ) return "\n".join("* [{title}]({url})".format(**snake_case ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
85
1
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def UpperCamelCase_( snake_case : Dict , snake_case : str , snake_case : List[str] ): '''simple docstring''' if isinstance(snake_case , torch.Tensor ): return image elif isinstance(snake_case , PIL.Image.Image ): snake_case_ = [image] if isinstance(image[0] , PIL.Image.Image ): snake_case_ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] snake_case_ = np.concatenate(snake_case , axis=0 ) snake_case_ = np.array(snake_case ).astype(np.floataa ) / 255.0 snake_case_ = image.transpose(0 , 3 , 1 , 2 ) snake_case_ = 2.0 * image - 1.0 snake_case_ = torch.from_numpy(snake_case ) elif isinstance(image[0] , torch.Tensor ): snake_case_ = torch.cat(snake_case , dim=0 ) return image def UpperCamelCase_( snake_case : Tuple , snake_case : str , snake_case : Union[str, Any] , snake_case : Any=0.9995 ): '''simple docstring''' if not isinstance(snake_case , np.ndarray ): snake_case_ = True snake_case_ = va.device snake_case_ = va.cpu().numpy() snake_case_ = va.cpu().numpy() snake_case_ = np.sum(va * va / (np.linalg.norm(snake_case ) * np.linalg.norm(snake_case )) ) if np.abs(snake_case ) > DOT_THRESHOLD: snake_case_ = (1 - t) * va + t * va else: snake_case_ = np.arccos(snake_case ) snake_case_ = np.sin(snake_case ) snake_case_ = theta_a * t snake_case_ = np.sin(snake_case ) snake_case_ = np.sin(theta_a - theta_t ) / sin_theta_a snake_case_ = sin_theta_t / sin_theta_a snake_case_ = sa * va + sa * va if inputs_are_torch: snake_case_ = torch.from_numpy(snake_case ).to(snake_case ) return va def UpperCamelCase_( snake_case : Tuple , snake_case : Any ): '''simple docstring''' snake_case_ = F.normalize(snake_case , dim=-1 ) snake_case_ = F.normalize(snake_case , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def UpperCamelCase_( snake_case : Optional[Any] , snake_case : Optional[Any] ): '''simple docstring''' for param in model.parameters(): snake_case_ = value class _snake_case ( lowercase_ ): def __init__( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__=None , a__=None , a__=None , ) -> Tuple: '''simple docstring''' super().__init__() self.register_modules( vae=a__ , text_encoder=a__ , clip_model=a__ , tokenizer=a__ , unet=a__ , scheduler=a__ , feature_extractor=a__ , coca_model=a__ , coca_tokenizer=a__ , coca_transform=a__ , ) snake_case_ = ( feature_extractor.size if isinstance(feature_extractor.size , a__ ) else feature_extractor.size["shortest_edge"] ) snake_case_ = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , a__ ) set_requires_grad(self.clip_model , a__ ) def lowerCAmelCase__ ( self , a__ = "auto" ) -> int: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory snake_case_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' self.enable_attention_slicing(a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' set_requires_grad(self.vae , a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' set_requires_grad(self.vae , a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' set_requires_grad(self.unet , a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' set_requires_grad(self.unet , a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = min(int(num_inference_steps * strength ) , a__ ) snake_case_ = max(num_inference_steps - init_timestep , 0 ) snake_case_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__=None ) -> int: '''simple docstring''' if not isinstance(a__ , torch.Tensor ): raise ValueError(F'`image` has to be of type `torch.Tensor` but is {type(a__ )}' ) snake_case_ = image.to(device=a__ , dtype=a__ ) if isinstance(a__ , a__ ): snake_case_ = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(a__ ) ] snake_case_ = torch.cat(a__ , dim=0 ) else: snake_case_ = self.vae.encode(a__ ).latent_dist.sample(a__ ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case_ = 0.1_8_2_1_5 * init_latents snake_case_ = init_latents.repeat_interleave(a__ , dim=0 ) snake_case_ = randn_tensor(init_latents.shape , generator=a__ , device=a__ , dtype=a__ ) # get latents snake_case_ = self.scheduler.add_noise(a__ , a__ , a__ ) snake_case_ = init_latents return latents def lowerCAmelCase__ ( self , a__ ) -> Any: '''simple docstring''' snake_case_ = self.coca_transform(a__ ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): snake_case_ = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) snake_case_ = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split("<end_of_text>" )[0].replace("<start_of_text>" , "" ).rstrip(" .," ) def lowerCAmelCase__ ( self , a__ , a__ ) -> int: '''simple docstring''' snake_case_ = self.feature_extractor.preprocess(a__ ) snake_case_ = torch.from_numpy(clip_image_input["pixel_values"][0] ).unsqueeze(0 ).to(self.device ).half() snake_case_ = self.clip_model.get_image_features(a__ ) snake_case_ = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=a__ ) snake_case_ = image_embeddings_clip.repeat_interleave(a__ , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> Optional[int]: '''simple docstring''' snake_case_ = latents.detach().requires_grad_() snake_case_ = self.scheduler.scale_model_input(a__ , a__ ) # predict the noise residual snake_case_ = self.unet(a__ , a__ , encoder_hidden_states=a__ ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): snake_case_ = self.scheduler.alphas_cumprod[timestep] snake_case_ = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf snake_case_ = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 snake_case_ = torch.sqrt(a__ ) snake_case_ = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , a__ ): snake_case_ = self.scheduler.sigmas[index] snake_case_ = latents - sigma * noise_pred else: raise ValueError(F'scheduler type {type(self.scheduler )} not supported' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case_ = 1 / 0.1_8_2_1_5 * sample snake_case_ = self.vae.decode(a__ ).sample snake_case_ = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ = transforms.Resize(self.feature_extractor_size )(a__ ) snake_case_ = self.normalize(a__ ).to(latents.dtype ) snake_case_ = self.clip_model.get_image_features(a__ ) snake_case_ = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=a__ ) snake_case_ = spherical_dist_loss(a__ , a__ ).mean() * clip_guidance_scale snake_case_ = -torch.autograd.grad(a__ , a__ )[0] if isinstance(self.scheduler , a__ ): snake_case_ = latents.detach() + grads * (sigma**2) snake_case_ = noise_pred_original else: snake_case_ = noise_pred_original - torch.sqrt(a__ ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , a__ , a__ , a__ = None , a__ = None , a__ = 512 , a__ = 512 , a__ = 0.6 , a__ = 50 , a__ = 7.5 , a__ = 1 , a__ = 0.0 , a__ = 100 , a__ = None , a__ = "pil" , a__ = True , a__ = 0.8 , a__ = 0.1 , a__ = 0.1 , ) -> Tuple: '''simple docstring''' if isinstance(a__ , a__ ) and len(a__ ) != batch_size: raise ValueError(F'You have passed {batch_size} batch_size, but only {len(a__ )} generators.' ) 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 isinstance(a__ , torch.Generator ) and batch_size > 1: snake_case_ = [generator] + [None] * (batch_size - 1) snake_case_ = [ ("model", self.coca_model is None), ("tokenizer", self.coca_tokenizer is None), ("transform", self.coca_transform is None), ] snake_case_ = [x[0] for x in coca_is_none if x[1]] snake_case_ = ", ".join(a__ ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(a__ ): raise ValueError( F'Content prompt is None and CoCa [{coca_is_none_str}] is None.' F'Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' ) snake_case_ = self.get_image_description(a__ ) if style_prompt is None: if len(a__ ): raise ValueError( F'Style prompt is None and CoCa [{coca_is_none_str}] is None.' F' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' ) snake_case_ = self.get_image_description(a__ ) # get prompt text embeddings for content and style snake_case_ = self.tokenizer( a__ , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=a__ , return_tensors="pt" , ) snake_case_ = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] snake_case_ = self.tokenizer( a__ , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=a__ , return_tensors="pt" , ) snake_case_ = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] snake_case_ = slerp(a__ , a__ , a__ ) # duplicate text embeddings for each generation per prompt snake_case_ = text_embeddings.repeat_interleave(a__ , dim=0 ) # set timesteps snake_case_ = "offset" in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) snake_case_ = {} if accepts_offset: snake_case_ = 1 self.scheduler.set_timesteps(a__ , **a__ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) snake_case_ , snake_case_ = self.get_timesteps(a__ , a__ , self.device ) snake_case_ = timesteps[:1].repeat(a__ ) # Preprocess image snake_case_ = preprocess(a__ , a__ , a__ ) snake_case_ = self.prepare_latents( a__ , a__ , a__ , text_embeddings.dtype , self.device , a__ ) snake_case_ = preprocess(a__ , a__ , a__ ) snake_case_ = self.prepare_latents( a__ , a__ , a__ , text_embeddings.dtype , self.device , a__ ) snake_case_ = slerp(a__ , a__ , a__ ) if clip_guidance_scale > 0: snake_case_ = self.get_clip_image_embeddings(a__ , a__ ) snake_case_ = self.get_clip_image_embeddings(a__ , a__ ) snake_case_ = slerp( a__ , a__ , a__ ) # 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. snake_case_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: snake_case_ = content_text_input.input_ids.shape[-1] snake_case_ = self.tokenizer([""] , padding="max_length" , max_length=a__ , return_tensors="pt" ) snake_case_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt snake_case_ = uncond_embeddings.repeat_interleave(a__ , dim=0 ) # 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 snake_case_ = 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`. snake_case_ = (batch_size, self.unet.config.in_channels, height // 8, width // 8) snake_case_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps snake_case_ = torch.randn(a__ , generator=a__ , device="cpu" , dtype=a__ ).to( self.device ) else: snake_case_ = torch.randn(a__ , generator=a__ , device=self.device , dtype=a__ ) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) snake_case_ = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case_ = 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] snake_case_ = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case_ = {} if accepts_eta: snake_case_ = eta # check if the scheduler accepts generator snake_case_ = "generator" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: snake_case_ = generator with self.progress_bar(total=a__ ): for i, t in enumerate(a__ ): # expand the latents if we are doing classifier free guidance snake_case_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case_ = self.scheduler.scale_model_input(a__ , a__ ) # predict the noise residual snake_case_ = self.unet(a__ , a__ , encoder_hidden_states=a__ ).sample # perform classifier free guidance if do_classifier_free_guidance: snake_case_ , snake_case_ = noise_pred.chunk(2 ) snake_case_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: snake_case_ = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) snake_case_ , snake_case_ = self.cond_fn( a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) # compute the previous noisy sample x_t -> x_t-1 snake_case_ = self.scheduler.step(a__ , a__ , a__ , **a__ ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case_ = 1 / 0.1_8_2_1_5 * latents snake_case_ = self.vae.decode(a__ ).sample snake_case_ = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case_ = self.numpy_to_pil(a__ ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=a__ , nsfw_content_detected=a__ )
85
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : Optional[Any] = MODEL_FOR_CAUSAL_LM_MAPPING lowerCAmelCase_ : Optional[Any] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="pt" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ], [ { "generated_text": ( "This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy" " oscope. oscope. FiliFili@@" ) } ], ] , ) snake_case_ = text_generator("This is a test" , do_sample=a__ , num_return_sequences=2 , return_tensors=a__ ) self.assertEqual( a__ , [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ] , ) snake_case_ = text_generator.model.config.eos_token_id snake_case_ = "<pad>" snake_case_ = text_generator( ["This is a test", "This is a second test"] , do_sample=a__ , num_return_sequences=2 , batch_size=2 , return_tensors=a__ , ) self.assertEqual( a__ , [ [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], ] , ) @require_tf def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="tf" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] , do_sample=a__ ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ], [ { "generated_text": ( "This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes" " Cannes 閲閲Cannes Cannes Cannes 攵 please," ) } ], ] , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> str: '''simple docstring''' snake_case_ = TextGenerationPipeline(model=a__ , tokenizer=a__ ) return text_generator, ["This is a test", "Another test"] def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "Hello I believe in" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) snake_case_ = text_generator(a__ ) self.assertEqual( a__ , [{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}] , ) snake_case_ = text_generator(a__ , stop_sequence=" fe" ) self.assertEqual(a__ , [{"generated_text": "Hello I believe in fe"}] ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Tuple: '''simple docstring''' snake_case_ = text_generator.model snake_case_ = text_generator.tokenizer snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = pipeline(task="text-generation" , model=a__ , tokenizer=a__ , return_full_text=a__ ) snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) if text_generator.tokenizer.pad_token is not None: snake_case_ = text_generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_text=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_tensors=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_text=a__ , return_tensors=a__ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): snake_case_ = text_generator("" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): snake_case_ = text_generator("" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. snake_case_ = ["RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM"] if ( tokenizer.model_max_length < 10_000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("This is a test" * 500 , max_new_tokens=20 ) snake_case_ = text_generator("This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(a__ ): text_generator( "This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' import torch # Classic `model_kwargs` snake_case_ = pipeline( model="hf-internal-testing/tiny-random-bloom" , model_kwargs={"device_map": "auto", "torch_dtype": torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) @require_torch @require_torch_gpu def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device=0 , torch_dtype=torch.floataa ) pipe("This is a test" ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.floataa ) pipe("This is a test" , do_sample=a__ , top_p=0.5 ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "Hello world" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) if text_generator.model.framework == "tf": snake_case_ = logging.get_logger("transformers.generation.tf_utils" ) else: snake_case_ = logging.get_logger("transformers.generation.utils" ) snake_case_ = "Both `max_new_tokens`" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 , max_new_tokens=1 ) self.assertIn(a__ , cl.out ) # The user only sets one -> no warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_new_tokens=1 ) self.assertNotIn(a__ , cl.out ) with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 ) self.assertNotIn(a__ , cl.out )
85
1
'''simple docstring''' from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = prime_factors(snake_case ) if is_square_free(snake_case ): return -1 if len(snake_case ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , lowercase_ ): def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = load_tool("text-classification" ) self.tool.setup() snake_case_ = load_tool("text-classification" , remote=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" )
85
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[int] = {"vocab_file": "sentencepiece.model"} _SCREAMING_SNAKE_CASE : Dict = { "vocab_file": { "google/rembert": "https://huggingface.co/google/rembert/resolve/main/sentencepiece.model", }, } _SCREAMING_SNAKE_CASE : str = { "google/rembert": 256, } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Union[str, Any] = VOCAB_FILES_NAMES lowerCAmelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , a__ , a__=False , a__=True , a__=True , a__="[CLS]" , a__="[SEP]" , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , **a__ , ) -> Tuple: '''simple docstring''' super().__init__( do_lower_case=a__ , remove_space=a__ , keep_accents=a__ , bos_token=a__ , eos_token=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , **a__ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor() self.sp_model.Load(a__ ) @property def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return len(self.sp_model ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = {self.convert_ids_to_tokens(a__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self , a__ ) -> Optional[Any]: '''simple docstring''' snake_case_ = d snake_case_ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def lowerCAmelCase__ ( self , a__ , a__=False ) -> int: '''simple docstring''' snake_case_ = self.sp_model.EncodeAsPieces(a__ ) return pieces def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' return self.sp_model.PieceToId(a__ ) def lowerCAmelCase__ ( self , a__ ) -> List[Any]: '''simple docstring''' return self.sp_model.IdToPiece(a__ ) def lowerCAmelCase__ ( self , a__ ) -> List[str]: '''simple docstring''' snake_case_ = self.sp_model.decode_pieces(a__ ) return out_string def lowerCAmelCase__ ( self , a__ , a__ = None ) -> List[int]: '''simple docstring''' snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase__ ( self , a__ , a__ = None , a__ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(a__ )) + [1] + ([0] * len(a__ )) + [1] return [1] + ([0] * len(a__ )) + [1] def lowerCAmelCase__ ( self , a__ , a__ = None ) -> List[int]: '''simple docstring''' snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase__ ( self , a__ , a__ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(a__ ): logger.error("Vocabulary path ({}) should be a directory".format(a__ ) ) return snake_case_ = os.path.join( a__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a__ ): copyfile(self.vocab_file , a__ ) return (out_vocab_file,)
85
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Dict = { "BridgeTower/bridgetower-base": "https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json", "BridgeTower/bridgetower-base-itm-mlm": ( "https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json" ), } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Dict = "bridgetower_vision_model" def __init__( self , a__=768 , a__=12 , a__=3 , a__=16 , a__=288 , a__=1 , a__=1e-05 , a__=False , a__=True , a__=False , **a__ , ) -> int: '''simple docstring''' super().__init__(**a__ ) snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_channels snake_case_ = patch_size snake_case_ = image_size snake_case_ = initializer_factor snake_case_ = layer_norm_eps snake_case_ = stop_gradient snake_case_ = share_layernorm snake_case_ = remove_last_layer @classmethod def lowerCAmelCase__ ( cls , a__ , **a__ ) -> "PretrainedConfig": '''simple docstring''' snake_case_ , snake_case_ = cls.get_config_dict(a__ , **a__ ) if config_dict.get("model_type" ) == "bridgetower": snake_case_ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a__ , **a__ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "bridgetower_text_model" def __init__( self , a__=50_265 , a__=768 , a__=12 , a__=12 , a__=1 , a__=3_072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=514 , a__=1 , a__=1e-05 , a__=1 , a__=0 , a__=2 , a__="absolute" , a__=True , **a__ , ) -> Optional[int]: '''simple docstring''' super().__init__(**a__ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = initializer_factor snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = layer_norm_eps snake_case_ = position_embedding_type snake_case_ = use_cache snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id @classmethod def lowerCAmelCase__ ( cls , a__ , **a__ ) -> "PretrainedConfig": '''simple docstring''' snake_case_ , snake_case_ = cls.get_config_dict(a__ , **a__ ) if config_dict.get("model_type" ) == "bridgetower": snake_case_ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a__ , **a__ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Union[str, Any] = "bridgetower" def __init__( self , a__=True , a__="gelu" , a__=768 , a__=1 , a__=1e-05 , a__=False , a__="add" , a__=12 , a__=6 , a__=False , a__=False , a__=None , a__=None , **a__ , ) -> int: '''simple docstring''' snake_case_ = kwargs.pop("text_config_dict" , a__ ) snake_case_ = kwargs.pop("vision_config_dict" , a__ ) super().__init__(**a__ ) snake_case_ = share_cross_modal_transformer_layers snake_case_ = hidden_act snake_case_ = hidden_size snake_case_ = initializer_factor snake_case_ = layer_norm_eps snake_case_ = share_link_tower_layers snake_case_ = link_tower_type snake_case_ = num_attention_heads snake_case_ = num_hidden_layers snake_case_ = tie_word_embeddings snake_case_ = init_layernorm_from_vision_encoder if text_config is None: snake_case_ = {} logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values." ) if vision_config is None: snake_case_ = {} logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values." ) snake_case_ = BridgeTowerTextConfig(**a__ ) snake_case_ = BridgeTowerVisionConfig(**a__ ) @classmethod def lowerCAmelCase__ ( cls , a__ , a__ , **a__ ) -> List[Any]: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.text_config.to_dict() snake_case_ = self.vision_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1
'''simple docstring''' from statistics import mean, stdev def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = min(snake_case ) snake_case_ = max(snake_case ) # normalize data return [round((x - x_min) / (x_max - x_min) , snake_case ) for x in data] def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = mean(snake_case ) snake_case_ = stdev(snake_case ) # standardize data return [round((x - mu) / (sigma) , snake_case ) for x in data]
85
'''simple docstring''' from __future__ import annotations def UpperCamelCase_( snake_case : list[int] ): '''simple docstring''' return len(set(snake_case ) ) == len(snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
85
1
'''simple docstring''' from math import ceil def UpperCamelCase_( snake_case : List[Any] , snake_case : Dict ): '''simple docstring''' snake_case_ = list(range(0 , snake_case ) ) snake_case_ = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check snake_case_ = [] for i in device_map_blocks: if device_map_blocks.count(snake_case ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(snake_case ) # Missing blocks snake_case_ = [i for i in blocks if i not in device_map_blocks] snake_case_ = [i for i in device_map_blocks if i not in blocks] if len(snake_case ) != 0: raise ValueError( "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device." " These attention blocks were specified more than once: " + str(snake_case ) ) if len(snake_case ) != 0: raise ValueError( "There are attention blocks for this model that are not specified in the device_map. Add these attention " "blocks to a device on the device_map: " + str(snake_case ) ) if len(snake_case ) != 0: raise ValueError( "The device_map contains more attention blocks than this model has. Remove these from the device_map:" + str(snake_case ) ) def UpperCamelCase_( snake_case : str , snake_case : Optional[Any] ): '''simple docstring''' snake_case_ = list(range(snake_case ) ) snake_case_ = int(ceil(n_layers / len(snake_case ) ) ) snake_case_ = [layers[i : i + n_blocks] for i in range(0 , snake_case , snake_case )] return dict(zip(snake_case , snake_case ) )
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = False try: _SCREAMING_SNAKE_CASE : Optional[Any] = _is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class _snake_case : def __init__( self , a__ = None , a__ = [] ) -> List[str]: '''simple docstring''' snake_case_ = 0 snake_case_ = choices snake_case_ = prompt if sys.platform == "win32": snake_case_ = "*" else: snake_case_ = "➔ " def lowerCAmelCase__ ( self , a__ , a__ = "" ) -> int: '''simple docstring''' if sys.platform != "win32": writeColor(self.choices[index] , 32 , a__ ) else: forceWrite(self.choices[index] , a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a__ ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def lowerCAmelCase__ ( self , a__ , a__ = 1 ) -> List[str]: '''simple docstring''' snake_case_ = 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 lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a__ )] for number in range(10 )] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = int(chr(self.current_selection ) ) snake_case_ = 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 lowerCAmelCase__ ( self , a__ = 0 ) -> List[str]: '''simple docstring''' 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" ) snake_case_ = 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: snake_case_ = int(builtins.input() ) except ValueError: snake_case_ = default_choice else: snake_case_ = 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
85
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : Optional[Any] = IFInpaintingPipeline lowerCAmelCase_ : Tuple = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} lowerCAmelCase_ : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase_ : Optional[int] = PipelineTesterMixin.required_optional_params - {"latents"} def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' return self._get_dummy_components() def lowerCAmelCase__ ( self , a__ , a__=0 ) -> Dict: '''simple docstring''' if str(a__ ).startswith("mps" ): snake_case_ = torch.manual_seed(a__ ) else: snake_case_ = torch.Generator(device=a__ ).manual_seed(a__ ) snake_case_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ ) snake_case_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ ) snake_case_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' self._test_save_load_local() def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
85
'''simple docstring''' import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def UpperCamelCase_( snake_case : Optional[int] ): '''simple docstring''' return EnvironmentCommand() class _snake_case ( lowercase_ ): @staticmethod def lowerCAmelCase__ ( a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = parser.add_parser("env" ) download_parser.set_defaults(func=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = huggingface_hub.__version__ snake_case_ = "not installed" snake_case_ = "NA" if is_torch_available(): import torch snake_case_ = torch.__version__ snake_case_ = torch.cuda.is_available() snake_case_ = "not installed" if is_transformers_available(): import transformers snake_case_ = transformers.__version__ snake_case_ = "not installed" if is_accelerate_available(): import accelerate snake_case_ = accelerate.__version__ snake_case_ = "not installed" if is_xformers_available(): import xformers snake_case_ = xformers.__version__ snake_case_ = { "`diffusers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "PyTorch version (GPU?)": F'{pt_version} ({pt_cuda_available})', "Huggingface_hub version": hub_version, "Transformers version": transformers_version, "Accelerate version": accelerate_version, "xFormers version": xformers_version, "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(a__ ) ) return info @staticmethod def lowerCAmelCase__ ( a__ ) -> str: '''simple docstring''' return "\n".join([F'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
85
1
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable _SCREAMING_SNAKE_CASE : Tuple = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Tuple = ["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
'''simple docstring''' import os _SCREAMING_SNAKE_CASE : int = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = 0 snake_case_ = 0 while index < len(snake_case ) - 1: snake_case_ = SYMBOLS[numerals[index]] snake_case_ = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = "" snake_case_ = num // 1_0_0_0 numerals += m_count * "M" num %= 1_0_0_0 snake_case_ = num // 1_0_0 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_0_0 snake_case_ = num // 1_0 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 1_0 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def UpperCamelCase_( snake_case : str = "/p089_roman.txt" ): '''simple docstring''' snake_case_ = 0 with open(os.path.dirname(snake_case ) + roman_numerals_filename ) as filea: snake_case_ = filea.readlines() for line in lines: snake_case_ = line.strip() snake_case_ = parse_roman_numerals(snake_case ) snake_case_ = generate_roman_numerals(snake_case ) savings += len(snake_case ) - len(snake_case ) return savings if __name__ == "__main__": print(F"{solution() = }")
85
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE : Union[str, Any] = { "configuration_maskformer": ["MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "MaskFormerConfig"], "configuration_maskformer_swin": ["MaskFormerSwinConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = ["MaskFormerFeatureExtractor"] _SCREAMING_SNAKE_CASE : str = ["MaskFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = [ "MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "MaskFormerForInstanceSegmentation", "MaskFormerModel", "MaskFormerPreTrainedModel", ] _SCREAMING_SNAKE_CASE : Dict = [ "MaskFormerSwinBackbone", "MaskFormerSwinModel", "MaskFormerSwinPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : str = _LazyModule(__name__, globals()["__file__"], _import_structure)
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _SCREAMING_SNAKE_CASE : int = { "configuration_clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig", ], "processing_clip": ["CLIPProcessor"], "tokenization_clip": ["CLIPTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = ["CLIPTokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = ["CLIPFeatureExtractor"] _SCREAMING_SNAKE_CASE : Dict = ["CLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : str ): '''simple docstring''' return credit_card_number.startswith(("34", "35", "37", "4", "5", "6") ) def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = credit_card_number snake_case_ = 0 snake_case_ = len(snake_case ) - 2 for i in range(snake_case , -1 , -2 ): # double the value of every second digit snake_case_ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 1_0 digit += 1 snake_case_ = cc_number[:i] + str(snake_case ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(snake_case ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 1_0 == 0 def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = f'{credit_card_number} is an invalid credit card number because' if not credit_card_number.isdigit(): print(f'{error_message} it has nonnumerical characters.' ) return False if not 1_3 <= len(snake_case ) <= 1_6: print(f'{error_message} of its length.' ) return False if not validate_initial_digits(snake_case ): print(f'{error_message} of its first two digits.' ) return False if not luhn_validation(snake_case ): print(f'{error_message} it fails the Luhn check.' ) return False print(f'{credit_card_number} is a valid credit card number.' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number("4111111111111111") validate_credit_card_number("32323")
85
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE : Union[str, Any] = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } _SCREAMING_SNAKE_CASE : int = { "gpt-neox-20b": 2048, } class _snake_case ( lowercase_ ): lowerCAmelCase_ : str = VOCAB_FILES_NAMES lowerCAmelCase_ : Tuple = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ : str = ["input_ids", "attention_mask"] def __init__( self , a__=None , a__=None , a__=None , a__="<|endoftext|>" , a__="<|endoftext|>" , a__="<|endoftext|>" , a__=False , **a__ , ) -> Tuple: '''simple docstring''' super().__init__( a__ , a__ , tokenizer_file=a__ , unk_token=a__ , bos_token=a__ , eos_token=a__ , add_prefix_space=a__ , **a__ , ) snake_case_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , a__ ) != add_prefix_space: snake_case_ = getattr(a__ , pre_tok_state.pop("type" ) ) snake_case_ = add_prefix_space snake_case_ = pre_tok_class(**a__ ) snake_case_ = add_prefix_space def lowerCAmelCase__ ( self , a__ , a__ = None ) -> Tuple[str]: '''simple docstring''' snake_case_ = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ ) def lowerCAmelCase__ ( self , a__ ) -> List[int]: '''simple docstring''' snake_case_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(a__ , add_special_tokens=a__ ) + [self.eos_token_id] ) if len(a__ ) > self.model_max_length: snake_case_ = input_ids[-self.model_max_length :] return input_ids
85
1
'''simple docstring''' import math def UpperCamelCase_( snake_case : int = 1_0_0 ): '''simple docstring''' snake_case_ = sum(i * i for i in range(1 , n + 1 ) ) snake_case_ = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F"{solution() = }")
85
'''simple docstring''' import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def UpperCamelCase_( snake_case : Tuple ): '''simple docstring''' snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = 0.01 with locka.acquire(): with pytest.raises(snake_case ): snake_case_ = time.time() locka.acquire(snake_case ) assert time.time() - _start > timeout def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = "a" * 1_0_0_0 + ".lock" snake_case_ = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(snake_case ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 snake_case_ = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case ): locka.acquire(0 )
85
1
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def UpperCamelCase_( snake_case : str , snake_case : str ): '''simple docstring''' snake_case_ = list(snake_case ) snake_case_ = list(snake_case ) snake_case_ = 0 for i in range(len(snake_case ) ): if lista[i] != lista[i]: count += 1 snake_case_ = "_" if count > 1: return False else: return "".join(snake_case ) def UpperCamelCase_( snake_case : list[str] ): '''simple docstring''' snake_case_ = [] while True: snake_case_ = ["$"] * len(snake_case ) snake_case_ = [] for i in range(len(snake_case ) ): for j in range(i + 1 , len(snake_case ) ): snake_case_ = compare_string(binary[i] , binary[j] ) if k is False: snake_case_ = "*" snake_case_ = "*" temp.append("X" ) for i in range(len(snake_case ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case ) == 0: return pi snake_case_ = list(set(snake_case ) ) def UpperCamelCase_( snake_case : int , snake_case : Sequence[float] ): '''simple docstring''' snake_case_ = [] for minterm in minterms: snake_case_ = "" for _ in range(snake_case ): snake_case_ = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case ) return temp def UpperCamelCase_( snake_case : str , snake_case : str , snake_case : int ): '''simple docstring''' snake_case_ = list(snake_case ) snake_case_ = list(snake_case ) snake_case_ = 0 for i in range(len(snake_case ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def UpperCamelCase_( snake_case : list[list[int]] , snake_case : list[str] ): '''simple docstring''' snake_case_ = [] snake_case_ = [0] * len(snake_case ) for i in range(len(chart[0] ) ): snake_case_ = 0 snake_case_ = -1 for j in range(len(snake_case ) ): if chart[j][i] == 1: count += 1 snake_case_ = j if count == 1: snake_case_ = 1 for i in range(len(snake_case ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case ) ): snake_case_ = 0 temp.append(prime_implicants[i] ) while True: snake_case_ = 0 snake_case_ = -1 snake_case_ = 0 for i in range(len(snake_case ) ): snake_case_ = chart[i].count(1 ) if count_n > max_n: snake_case_ = count_n snake_case_ = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case ) ): snake_case_ = 0 def UpperCamelCase_( snake_case : list[str] , snake_case : list[str] ): '''simple docstring''' snake_case_ = [[0 for x in range(len(snake_case ) )] for x in range(len(snake_case ) )] for i in range(len(snake_case ) ): snake_case_ = prime_implicants[i].count("_" ) for j in range(len(snake_case ) ): if is_for_table(prime_implicants[i] , binary[j] , snake_case ): snake_case_ = 1 return chart def UpperCamelCase_( ): '''simple docstring''' snake_case_ = int(input("Enter the no. of variables\n" ) ) snake_case_ = [ float(snake_case ) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] snake_case_ = decimal_to_binary(snake_case , snake_case ) snake_case_ = check(snake_case ) print("Prime Implicants are:" ) print(snake_case ) snake_case_ = prime_implicant_chart(snake_case , snake_case ) snake_case_ = selection(snake_case , snake_case ) print("Essential Prime Implicants are:" ) print(snake_case ) if __name__ == "__main__": import doctest doctest.testmod() main()
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _snake_case ( datasets.BuilderConfig ): lowerCAmelCase_ : Optional[datasets.Features] = None def UpperCamelCase_( snake_case : "pyspark.sql.DataFrame" , snake_case : List[int] , ): '''simple docstring''' import pyspark def generate_fn(): snake_case_ = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: snake_case_ = df_with_partition_id.select("*" ).where(f'part_id = {partition_id}' ).drop("part_id" ) snake_case_ = partition_df.collect() snake_case_ = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class _snake_case ( _BaseExamplesIterable ): def __init__( self , a__ , a__=None , ) -> Any: '''simple docstring''' snake_case_ = df snake_case_ = partition_order or range(self.df.rdd.getNumPartitions() ) snake_case_ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Union[str, Any]: '''simple docstring''' yield from self.generate_examples_fn() def lowerCAmelCase__ ( self , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = self.split_shard_indices_by_worker(a__ , a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) @property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return len(self.partition_order ) class _snake_case ( datasets.DatasetBuilder ): lowerCAmelCase_ : Dict = SparkConfig def __init__( self , a__ , a__ = None , a__ = None , **a__ , ) -> str: '''simple docstring''' import pyspark snake_case_ = pyspark.sql.SparkSession.builder.getOrCreate() snake_case_ = df snake_case_ = working_dir super().__init__( cache_dir=a__ , config_name=str(self.df.semanticHash() ) , **a__ , ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' def create_cache_and_write_probe(a__ ): # 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__ ) snake_case_ = 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: snake_case_ = ( 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 lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' import pyspark def get_arrow_batch_size(a__ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) snake_case_ = self.df.count() snake_case_ = 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. snake_case_ = ( 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 ) snake_case_ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. snake_case_ = min(a__ , int(approx_total_size / max_shard_size ) ) snake_case_ = self.df.repartition(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: '''simple docstring''' import pyspark snake_case_ = ParquetWriter if file_format == "parquet" else ArrowWriter snake_case_ = os.path.join(self._working_dir , os.path.basename(a__ ) ) if self._working_dir else fpath snake_case_ = 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. snake_case_ = self.config.features snake_case_ = self._writer_batch_size snake_case_ = self._fs.storage_options def write_arrow(a__ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. snake_case_ = pyspark.TaskContext().taskAttemptId() snake_case_ = 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"] , ) snake_case_ = 0 snake_case_ = 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__ , ) snake_case_ = 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: snake_case_ , snake_case_ = 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 snake_case_ = 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__ , ) snake_case_ = pa.Table.from_batches([batch] ) writer.write_table(a__ ) if writer._num_bytes > 0: snake_case_ , snake_case_ = 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__ ) ): snake_case_ = os.path.join(os.path.dirname(a__ ) , os.path.basename(a__ ) ) shutil.move(a__ , a__ ) snake_case_ = ( 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 lowerCAmelCase__ ( self , a__ , a__ = "arrow" , a__ = None , a__ = None , **a__ , ) -> int: '''simple docstring''' self._validate_cache_dir() snake_case_ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a__ ) snake_case_ = not is_remote_filesystem(self._fs ) snake_case_ = os.path.join if is_local else posixpath.join snake_case_ = "-TTTTT-SSSSS-of-NNNNN" snake_case_ = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' snake_case_ = path_join(self._output_dir , a__ ) snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = [] snake_case_ = [] for task_id, content in self._prepare_split_single(a__ , a__ , a__ ): ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = 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__ ) snake_case_ = total_num_examples snake_case_ = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: snake_case_ = 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. snake_case_ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a__ , a__ , a__ , ): 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}' ) , ) snake_case_ = [] snake_case_ = 0 for i in range(len(a__ ) ): snake_case_ , snake_case_ = 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 snake_case_ = 0 snake_case_ = 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 lowerCAmelCase__ ( self , a__ , ) -> SparkExamplesIterable: '''simple docstring''' return SparkExamplesIterable(self.df )
85
1
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) _SCREAMING_SNAKE_CASE : Optional[Any] = logging.getLogger() def UpperCamelCase_( snake_case : Path , snake_case : list ): '''simple docstring''' snake_case_ = "\n".join(snake_case ) Path(snake_case ).open("w" ).writelines(snake_case ) _SCREAMING_SNAKE_CASE : List[str] = "patrickvonplaten/t5-tiny-random" _SCREAMING_SNAKE_CASE : str = "sshleifer/bart-tiny-random" _SCREAMING_SNAKE_CASE : Optional[int] = "sshleifer/tiny-mbart" _SCREAMING_SNAKE_CASE : Dict = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class _snake_case ( lowercase_ ): def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' snake_case_ = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" snake_case_ = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() snake_case_ = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(a__ , a__ ) snake_case_ = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) snake_case_ = "translation_en_to_de" if model == T5_TINY else "summarization" snake_case_ = F'\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n '.split() with patch.object(a__ , "argv" , a__ ): run_generate() assert Path(a__ ).exists() # os.remove(Path(output_file_name)) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' self.run_eval_tester(a__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' self.run_eval_tester(a__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def lowerCAmelCase__ ( self , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" snake_case_ = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() snake_case_ = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } snake_case_ = Path(self.get_auto_remove_tmp_dir() ) snake_case_ = str(tmp_dir / "scores.json" ) snake_case_ = str(tmp_dir / "val.target" ) _dump_articles(a__ , text["en"] ) _dump_articles(a__ , text["de"] ) snake_case_ = "translation_en_to_de" if model == T5_TINY else "summarization" snake_case_ = F'\n run_eval_search.py\n {model}\n {str(a__ )}\n {str(a__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n '.split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(a__ , "argv" , a__ ): with CaptureStdout() as cs: run_search() snake_case_ = [" num_beams | length_penalty", model, "Best score args"] snake_case_ = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(a__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(a__ ).exists() os.remove(Path(a__ ) )
85
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB 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 typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : List[str] = { "configuration_cpmant": ["CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CpmAntConfig"], "tokenization_cpmant": ["CpmAntTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST", "CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : str = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' snake_case_ = set() # Replace all the whitespace in our sentence snake_case_ = input_str.replace(" " , "" ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(snake_case ) == 2_6 def UpperCamelCase_( snake_case : str = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' snake_case_ = [False] * 2_6 for char in input_str: if char.islower(): snake_case_ = True elif char.isupper(): snake_case_ = True return all(snake_case ) def UpperCamelCase_( snake_case : str = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()} ) == 2_6 def UpperCamelCase_( ): '''simple docstring''' from timeit import timeit snake_case_ = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=snake_case ) ) print(timeit("is_pangram_faster()" , setup=snake_case ) ) print(timeit("is_pangram_fastest()" , setup=snake_case ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
85
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu _SCREAMING_SNAKE_CASE : Union[str, Any] = False class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return 32 @property def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 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 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(a__ ) @property def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 12 snake_case_ = 12 snake_case_ = { "attention_bias": True, "cross_attention_dim": 32, "attention_head_dim": height * width, "num_attention_heads": 1, "num_vector_embeds": self.num_embed, "num_embeds_ada_norm": self.num_embeds_ada_norm, "norm_num_groups": 32, "sample_size": width, "activation_fn": "geglu-approximate", } snake_case_ = TransformeraDModel(**a__ ) return model def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings(learnable=a__ ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_5_5_1, 0.6_1_6_8, 0.5_0_0_8, 0.5_6_7_6, 0.5_6_5_9, 0.4_2_9_5, 0.6_0_7_3, 0.5_5_9_9, 0.4_9_9_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings( learnable=a__ , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_6_9_3, 0.6_0_7_5, 0.4_9_5_9, 0.5_7_0_1, 0.5_5_8_3, 0.4_3_3_3, 0.6_1_7_1, 0.5_6_8_4, 0.4_9_8_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy" ) snake_case_ = VQDiffusionPipeline.from_pretrained("microsoft/vq-diffusion-ithq" ) snake_case_ = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipeline( "teddy bear playing in the pool" , num_images_per_prompt=1 , generator=a__ , output_type="np" , ) snake_case_ = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
85
1
'''simple docstring''' from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class _snake_case ( lowercase_ ): lowerCAmelCase_ : torch.FloatTensor class _snake_case ( lowercase_ , lowercase_ ): @register_to_config def __init__( self , a__ = 32 , a__ = 64 , a__ = 20 , a__ = 768 , a__=77 , a__=4 , a__ = 0.0 , a__ = "silu" , a__ = None , a__ = None , a__ = "linear" , a__ = "prd" , a__ = None , a__ = None , a__ = None , ) -> Tuple: '''simple docstring''' super().__init__() snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = num_attention_heads * attention_head_dim snake_case_ = additional_embeddings snake_case_ = time_embed_dim or inner_dim snake_case_ = embedding_proj_dim or embedding_dim snake_case_ = clip_embed_dim or embedding_dim snake_case_ = Timesteps(a__ , a__ , 0 ) snake_case_ = TimestepEmbedding(a__ , a__ , out_dim=a__ , act_fn=a__ ) snake_case_ = nn.Linear(a__ , a__ ) if embedding_proj_norm_type is None: snake_case_ = None elif embedding_proj_norm_type == "layer": snake_case_ = nn.LayerNorm(a__ ) else: raise ValueError(F'unsupported embedding_proj_norm_type: {embedding_proj_norm_type}' ) snake_case_ = nn.Linear(a__ , a__ ) if encoder_hid_proj_type is None: snake_case_ = None elif encoder_hid_proj_type == "linear": snake_case_ = nn.Linear(a__ , a__ ) else: raise ValueError(F'unsupported encoder_hid_proj_type: {encoder_hid_proj_type}' ) snake_case_ = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , a__ ) ) if added_emb_type == "prd": snake_case_ = nn.Parameter(torch.zeros(1 , 1 , a__ ) ) elif added_emb_type is None: snake_case_ = None else: raise ValueError( F'`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.' ) snake_case_ = nn.ModuleList( [ BasicTransformerBlock( a__ , a__ , a__ , dropout=a__ , activation_fn="gelu" , attention_bias=a__ , ) for d in range(a__ ) ] ) if norm_in_type == "layer": snake_case_ = nn.LayerNorm(a__ ) elif norm_in_type is None: snake_case_ = None else: raise ValueError(F'Unsupported norm_in_type: {norm_in_type}.' ) snake_case_ = nn.LayerNorm(a__ ) snake_case_ = nn.Linear(a__ , a__ ) snake_case_ = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -1_0_0_0_0.0 ) causal_attention_mask.triu_(1 ) snake_case_ = causal_attention_mask[None, ...] self.register_buffer("causal_attention_mask" , a__ , persistent=a__ ) snake_case_ = nn.Parameter(torch.zeros(1 , a__ ) ) snake_case_ = nn.Parameter(torch.zeros(1 , a__ ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def lowerCAmelCase__ ( self ) -> Dict[str, AttentionProcessor]: '''simple docstring''' snake_case_ = {} def fn_recursive_add_processors(a__ , a__ , a__ ): if hasattr(a__ , "set_processor" ): snake_case_ = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'{name}.{sub_name}' , a__ , a__ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(a__ , a__ , a__ ) return processors def lowerCAmelCase__ ( self , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = len(self.attn_processors.keys() ) if isinstance(a__ , a__ ) and len(a__ ) != count: raise ValueError( F'A dict of processors was passed, but the number of processors {len(a__ )} does not match the' F' number of attention layers: {count}. Please make sure to pass {count} processor classes.' ) def fn_recursive_attn_processor(a__ , a__ , a__ ): if hasattr(a__ , "set_processor" ): if not isinstance(a__ , a__ ): module.set_processor(a__ ) else: module.set_processor(processor.pop(F'{name}.processor' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'{name}.{sub_name}' , a__ , a__ ) for name, module in self.named_children(): fn_recursive_attn_processor(a__ , a__ , a__ ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ = None , a__ = None , a__ = True , ) -> Dict: '''simple docstring''' snake_case_ = hidden_states.shape[0] snake_case_ = timestep if not torch.is_tensor(a__ ): snake_case_ = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(a__ ) and len(timesteps.shape ) == 0: snake_case_ = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML snake_case_ = timesteps * torch.ones(a__ , dtype=timesteps.dtype , device=timesteps.device ) snake_case_ = self.time_proj(a__ ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. snake_case_ = timesteps_projected.to(dtype=self.dtype ) snake_case_ = self.time_embedding(a__ ) if self.embedding_proj_norm is not None: snake_case_ = self.embedding_proj_norm(a__ ) snake_case_ = self.embedding_proj(a__ ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: snake_case_ = self.encoder_hidden_states_proj(a__ ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set" ) snake_case_ = self.proj_in(a__ ) snake_case_ = self.positional_embedding.to(hidden_states.dtype ) snake_case_ = [] snake_case_ = 0 if encoder_hidden_states is not None: additional_embeds.append(a__ ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: snake_case_ = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: snake_case_ = hidden_states[:, None, :] snake_case_ = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: snake_case_ = self.prd_embedding.to(hidden_states.dtype ).expand(a__ , -1 , -1 ) additional_embeds.append(a__ ) snake_case_ = torch.cat( a__ , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens snake_case_ = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: snake_case_ = F.pad( a__ , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) snake_case_ = hidden_states + positional_embeddings if attention_mask is not None: snake_case_ = (1 - attention_mask.to(hidden_states.dtype )) * -1_0_0_0_0.0 snake_case_ = F.pad(a__ , (0, self.additional_embeddings) , value=0.0 ) snake_case_ = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) snake_case_ = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: snake_case_ = self.norm_in(a__ ) for block in self.transformer_blocks: snake_case_ = block(a__ , attention_mask=a__ ) snake_case_ = self.norm_out(a__ ) if self.prd_embedding is not None: snake_case_ = hidden_states[:, -1] else: snake_case_ = hidden_states[:, additional_embeddings_len:] snake_case_ = self.proj_to_clip_embeddings(a__ ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=a__ ) def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' snake_case_ = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
85
'''simple docstring''' from statistics import mean, stdev def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = min(snake_case ) snake_case_ = max(snake_case ) # normalize data return [round((x - x_min) / (x_max - x_min) , snake_case ) for x in data] def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = mean(snake_case ) snake_case_ = stdev(snake_case ) # standardize data return [round((x - mu) / (sigma) , snake_case ) for x in data]
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : str , snake_case : int ): '''simple docstring''' snake_case_ = word.split() def justify(snake_case : list , snake_case : int , snake_case : int ) -> str: snake_case_ = max_width - width snake_case_ = len(snake_case ) if len(snake_case ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: snake_case_ = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] snake_case_ = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] snake_case_ = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(snake_case ): num_spaces_between_words_list[i] += 1 snake_case_ = [] for i in range(snake_case ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " " ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(snake_case ) snake_case_ = [] snake_case_ = [] snake_case_ = 0 for word in words: if width + len(snake_case ) + len(snake_case ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(snake_case ) width += len(snake_case ) else: # justify the line and add it to result answer.append(justify(snake_case , snake_case , snake_case ) ) # reset new line and new width snake_case_ , snake_case_ = [word], len(snake_case ) snake_case_ = max_width - width - len(snake_case ) answer.append(" ".join(snake_case ) + (remaining_spaces + 1) * " " ) return answer if __name__ == "__main__": from doctest import testmod testmod()
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : str = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
85
1
'''simple docstring''' from __future__ import annotations def UpperCamelCase_( snake_case : int , snake_case : int ): '''simple docstring''' snake_case_ = [] create_all_state(1 , snake_case , snake_case , [] , snake_case ) return result def UpperCamelCase_( snake_case : int , snake_case : int , snake_case : int , snake_case : list[int] , snake_case : list[list[int]] , ): '''simple docstring''' if level == 0: total_list.append(current_list[:] ) return for i in range(snake_case , total_number - level + 2 ): current_list.append(snake_case ) create_all_state(i + 1 , snake_case , level - 1 , snake_case , snake_case ) current_list.pop() def UpperCamelCase_( snake_case : list[list[int]] ): '''simple docstring''' for i in total_list: print(*snake_case ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[Any] = 4 _SCREAMING_SNAKE_CASE : List[Any] = 2 _SCREAMING_SNAKE_CASE : Dict = generate_all_combinations(n, k) print_all_state(total_list)
85
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. snake_case_ = min(snake_case , snake_case ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
85
1
'''simple docstring''' import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def UpperCamelCase_( snake_case : Optional[int] , snake_case : Dict ): '''simple docstring''' snake_case_ = torch.load(snake_case , map_location="cpu" ) snake_case_ = chkpt["model"] # We have the base model one level deeper than the original XLM repository snake_case_ = {} for k, v in state_dict.items(): if "pred_layer" in k: snake_case_ = v else: snake_case_ = v snake_case_ = chkpt["params"] snake_case_ = {n: v for n, v in config.items() if not isinstance(snake_case , (torch.FloatTensor, numpy.ndarray) )} snake_case_ = chkpt["dico_word2id"] snake_case_ = {s + "</w>" if s.find("@@" ) == -1 and i > 1_3 else s.replace("@@" , "" ): i for s, i in vocab.items()} # Save pytorch-model snake_case_ = pytorch_dump_folder_path + "/" + WEIGHTS_NAME snake_case_ = pytorch_dump_folder_path + "/" + CONFIG_NAME snake_case_ = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"] print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(snake_case , snake_case ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(snake_case , "w" , encoding="utf-8" ) as f: f.write(json.dumps(snake_case , indent=2 ) + "\n" ) print(f'Save vocab file to {pytorch_config_dump_path}' ) with open(snake_case , "w" , encoding="utf-8" ) as f: f.write(json.dumps(snake_case , indent=2 ) + "\n" ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE : Tuple = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConditionalDetrConfig", "ConditionalDetrOnnxConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = ["ConditionalDetrFeatureExtractor"] _SCREAMING_SNAKE_CASE : List[Any] = ["ConditionalDetrImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Dict = [ "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "ConditionalDetrForObjectDetection", "ConditionalDetrForSegmentation", "ConditionalDetrModel", "ConditionalDetrPreTrainedModel", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' _SCREAMING_SNAKE_CASE : str = { "Pillow": "Pillow<10.0.0", "accelerate": "accelerate>=0.20.3", "av": "av==9.2.0", "beautifulsoup4": "beautifulsoup4", "black": "black~=23.1", "codecarbon": "codecarbon==1.2.0", "cookiecutter": "cookiecutter==1.7.3", "dataclasses": "dataclasses", "datasets": "datasets!=2.5.0", "decord": "decord==0.6.0", "deepspeed": "deepspeed>=0.9.3", "diffusers": "diffusers", "dill": "dill<0.3.5", "evaluate": "evaluate>=0.2.0", "fairscale": "fairscale>0.3", "faiss-cpu": "faiss-cpu", "fastapi": "fastapi", "filelock": "filelock", "flax": "flax>=0.4.1,<=0.7.0", "ftfy": "ftfy", "fugashi": "fugashi>=1.0", "GitPython": "GitPython<3.1.19", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.14.1,<1.0", "importlib_metadata": "importlib_metadata", "ipadic": "ipadic>=1.0.0,<2.0", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2,<=0.4.13", "jaxlib": "jaxlib>=0.1.65,<=0.4.13", "jieba": "jieba", "kenlm": "kenlm", "keras-nlp": "keras-nlp>=0.3.1", "librosa": "librosa", "nltk": "nltk", "natten": "natten>=0.14.6", "numpy": "numpy>=1.17", "onnxconverter-common": "onnxconverter-common", "onnxruntime-tools": "onnxruntime-tools>=1.4.2", "onnxruntime": "onnxruntime>=1.4.0", "opencv-python": "opencv-python", "optuna": "optuna", "optax": "optax>=0.0.8,<=0.1.4", "packaging": "packaging>=20.0", "parameterized": "parameterized", "phonemizer": "phonemizer", "protobuf": "protobuf", "psutil": "psutil", "pyyaml": "pyyaml>=5.1", "pydantic": "pydantic<2", "pytest": "pytest>=7.2.0", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "python": "python>=3.8.0", "ray[tune]": "ray[tune]", "regex": "regex!=2019.12.17", "requests": "requests", "rhoknp": "rhoknp>=1.1.0,<1.3.1", "rjieba": "rjieba", "rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1", "ruff": "ruff>=0.0.241,<=0.0.259", "sacrebleu": "sacrebleu>=1.4.12,<2.0.0", "sacremoses": "sacremoses", "safetensors": "safetensors>=0.3.1", "sagemaker": "sagemaker>=2.31.0", "scikit-learn": "scikit-learn", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "sigopt": "sigopt", "starlette": "starlette", "sudachipy": "sudachipy>=0.6.6", "sudachidict_core": "sudachidict_core>=20220729", "tensorflow-cpu": "tensorflow-cpu>=2.6,<2.14", "tensorflow": "tensorflow>=2.6,<2.14", "tensorflow-text": "tensorflow-text<2.14", "tf2onnx": "tf2onnx", "timeout-decorator": "timeout-decorator", "timm": "timm", "tokenizers": "tokenizers>=0.11.1,!=0.11.3,<0.14", "torch": "torch>=1.9,!=1.12.0", "torchaudio": "torchaudio", "torchvision": "torchvision", "pyctcdecode": "pyctcdecode>=0.4.0", "tqdm": "tqdm>=4.27", "unidic": "unidic>=1.0.2", "unidic_lite": "unidic_lite>=1.0.7", "urllib3": "urllib3<2.0.0", "uvicorn": "uvicorn", }
85
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--txt2img_unclip", default="kakaobrain/karlo-v1-alpha", type=str, required=False, help="The pretrained txt2img unclip.", ) _SCREAMING_SNAKE_CASE : int = parser.parse_args() _SCREAMING_SNAKE_CASE : List[Any] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor() _SCREAMING_SNAKE_CASE : str = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") _SCREAMING_SNAKE_CASE : int = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
85
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[Any] = { "junnyu/roformer_chinese_small": "https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json", "junnyu/roformer_chinese_base": "https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json", "junnyu/roformer_chinese_char_small": ( "https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json" ), "junnyu/roformer_chinese_char_base": ( "https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json" ), "junnyu/roformer_small_discriminator": ( "https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json" ), "junnyu/roformer_small_generator": ( "https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Dict = "roformer" def __init__( self , a__=50_000 , a__=None , a__=768 , a__=12 , a__=12 , a__=3_072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=1_536 , a__=2 , a__=0.0_2 , a__=1e-12 , a__=0 , a__=False , a__=True , **a__ , ) -> Tuple: '''simple docstring''' super().__init__(pad_token_id=a__ , **a__ ) snake_case_ = vocab_size snake_case_ = hidden_size if embedding_size is None else embedding_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = rotary_value snake_case_ = use_cache class _snake_case ( lowercase_ ): @property def lowerCAmelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": snake_case_ = {0: "batch", 1: "choice", 2: "sequence"} else: snake_case_ = {0: "batch", 1: "sequence"} snake_case_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
85
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "upernet" def __init__( self , a__=None , a__=512 , a__=0.0_2 , a__=[1, 2, 3, 6] , a__=True , a__=0.4 , a__=384 , a__=256 , a__=1 , a__=False , a__=255 , **a__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**a__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) snake_case_ = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a__ , a__ ): snake_case_ = backbone_config.get("model_type" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(a__ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1
'''simple docstring''' import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def UpperCamelCase_( snake_case : Optional[int] ): '''simple docstring''' return EnvironmentCommand() class _snake_case ( lowercase_ ): @staticmethod def lowerCAmelCase__ ( a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = parser.add_parser("env" ) download_parser.set_defaults(func=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = huggingface_hub.__version__ snake_case_ = "not installed" snake_case_ = "NA" if is_torch_available(): import torch snake_case_ = torch.__version__ snake_case_ = torch.cuda.is_available() snake_case_ = "not installed" if is_transformers_available(): import transformers snake_case_ = transformers.__version__ snake_case_ = "not installed" if is_accelerate_available(): import accelerate snake_case_ = accelerate.__version__ snake_case_ = "not installed" if is_xformers_available(): import xformers snake_case_ = xformers.__version__ snake_case_ = { "`diffusers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "PyTorch version (GPU?)": F'{pt_version} ({pt_cuda_available})', "Huggingface_hub version": hub_version, "Transformers version": transformers_version, "Accelerate version": accelerate_version, "xFormers version": xformers_version, "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(a__ ) ) return info @staticmethod def lowerCAmelCase__ ( a__ ) -> str: '''simple docstring''' return "\n".join([F'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
85
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def UpperCamelCase_( snake_case : Any ): '''simple docstring''' if ( (cp >= 0X4E00 and cp <= 0X9FFF) or (cp >= 0X3400 and cp <= 0X4DBF) # or (cp >= 0X2_0000 and cp <= 0X2_A6DF) # or (cp >= 0X2_A700 and cp <= 0X2_B73F) # or (cp >= 0X2_B740 and cp <= 0X2_B81F) # or (cp >= 0X2_B820 and cp <= 0X2_CEAF) # or (cp >= 0XF900 and cp <= 0XFAFF) or (cp >= 0X2_F800 and cp <= 0X2_FA1F) # ): # return True return False def UpperCamelCase_( snake_case : str ): '''simple docstring''' for char in word: snake_case_ = ord(snake_case ) if not _is_chinese_char(snake_case ): return 0 return 1 def UpperCamelCase_( snake_case : List[str] ): '''simple docstring''' snake_case_ = set() for token in tokens: snake_case_ = len(snake_case ) > 1 and is_chinese(snake_case ) if chinese_word: word_set.add(snake_case ) snake_case_ = list(snake_case ) return word_list def UpperCamelCase_( snake_case : List[str] , snake_case : set() ): '''simple docstring''' if not chinese_word_set: return bert_tokens snake_case_ = max([len(snake_case ) for w in chinese_word_set] ) snake_case_ = bert_tokens snake_case_ , snake_case_ = 0, len(snake_case ) while start < end: snake_case_ = True if is_chinese(bert_word[start] ): snake_case_ = min(end - start , snake_case ) for i in range(snake_case , 1 , -1 ): snake_case_ = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): snake_case_ = "##" + bert_word[j] snake_case_ = start + i snake_case_ = False break if single_word: start += 1 return bert_word def UpperCamelCase_( snake_case : List[str] , snake_case : LTP , snake_case : BertTokenizer ): '''simple docstring''' snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = ltp_tokenizer.pipeline(lines[i : i + 1_0_0] , tasks=["cws"] ).cws snake_case_ = [get_chinese_word(snake_case ) for r in res] ltp_res.extend(snake_case ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=snake_case , truncation=snake_case , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for input_ids, chinese_word in zip(snake_case , snake_case ): snake_case_ = [] for id in input_ids: snake_case_ = bert_tokenizer._convert_id_to_token(snake_case ) input_tokens.append(snake_case ) snake_case_ = add_sub_symbol(snake_case , snake_case ) snake_case_ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(snake_case ): if token[:2] == "##": snake_case_ = token[2:] # save chinese tokens' pos if len(snake_case ) == 1 and _is_chinese_char(ord(snake_case ) ): ref_id.append(snake_case ) ref_ids.append(snake_case ) assert len(snake_case ) == len(snake_case ) return ref_ids def UpperCamelCase_( snake_case : Any ): '''simple docstring''' with open(args.file_name , "r" , encoding="utf-8" ) as f: snake_case_ = f.readlines() snake_case_ = [line.strip() for line in data if len(snake_case ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' snake_case_ = LTP(args.ltp ) # faster in GPU device snake_case_ = BertTokenizer.from_pretrained(args.bert ) snake_case_ = prepare_ref(snake_case , snake_case , snake_case ) with open(args.save_path , "w" , encoding="utf-8" ) as f: snake_case_ = [json.dumps(snake_case ) + "\n" for ref in ref_ids] f.writelines(snake_case ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", required=False, type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", required=False, type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path", ) parser.add_argument( "--bert", required=False, type=str, default="./resources/robert", help="resources for Bert tokenizer", ) parser.add_argument( "--save_path", required=False, type=str, default="./resources/ref.txt", help="path to save res", ) _SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() main(args)
85
1
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class _snake_case ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__=0.0 , a__ = None , a__ = "geglu" , a__ = None , a__ = False , a__ = False , a__ = False , a__ = False , a__ = True , a__ = "layer_norm" , a__ = False , ) -> List[str]: '''simple docstring''' super().__init__() snake_case_ = only_cross_attention snake_case_ = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" snake_case_ = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F'`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to' F' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: snake_case_ = AdaLayerNorm(a__ , a__ ) elif self.use_ada_layer_norm_zero: snake_case_ = AdaLayerNormZero(a__ , a__ ) else: snake_case_ = nn.LayerNorm(a__ , elementwise_affine=a__ ) snake_case_ = Attention( query_dim=a__ , heads=a__ , dim_head=a__ , dropout=a__ , bias=a__ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=a__ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. snake_case_ = ( AdaLayerNorm(a__ , a__ ) if self.use_ada_layer_norm else nn.LayerNorm(a__ , elementwise_affine=a__ ) ) snake_case_ = Attention( query_dim=a__ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=a__ , dim_head=a__ , dropout=a__ , bias=a__ , upcast_attention=a__ , ) # is self-attn if encoder_hidden_states is none else: snake_case_ = None snake_case_ = None # 3. Feed-forward snake_case_ = nn.LayerNorm(a__ , elementwise_affine=a__ ) snake_case_ = FeedForward(a__ , dropout=a__ , activation_fn=a__ , final_dropout=a__ ) # let chunk size default to None snake_case_ = None snake_case_ = 0 def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = chunk_size snake_case_ = dim def lowerCAmelCase__ ( self , a__ , a__ = None , a__ = None , a__ = None , a__ = None , a__ = None , a__ = None , ) -> str: '''simple docstring''' if self.use_ada_layer_norm: snake_case_ = self.norma(a__ , a__ ) elif self.use_ada_layer_norm_zero: snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.norma( a__ , a__ , a__ , hidden_dtype=hidden_states.dtype ) else: snake_case_ = self.norma(a__ ) snake_case_ = cross_attention_kwargs if cross_attention_kwargs is not None else {} snake_case_ = self.attna( a__ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=a__ , **a__ , ) if self.use_ada_layer_norm_zero: snake_case_ = gate_msa.unsqueeze(1 ) * attn_output snake_case_ = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: snake_case_ = ( self.norma(a__ , a__ ) if self.use_ada_layer_norm else self.norma(a__ ) ) snake_case_ = self.attna( a__ , encoder_hidden_states=a__ , attention_mask=a__ , **a__ , ) snake_case_ = attn_output + hidden_states # 3. Feed-forward snake_case_ = self.norma(a__ ) if self.use_ada_layer_norm_zero: snake_case_ = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F'`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.' ) snake_case_ = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size snake_case_ = torch.cat( [self.ff(a__ ) for hid_slice in norm_hidden_states.chunk(a__ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: snake_case_ = self.ff(a__ ) if self.use_ada_layer_norm_zero: snake_case_ = gate_mlp.unsqueeze(1 ) * ff_output snake_case_ = ff_output + hidden_states return hidden_states class _snake_case ( nn.Module ): def __init__( self , a__ , a__ = None , a__ = 4 , a__ = 0.0 , a__ = "geglu" , a__ = False , ) -> int: '''simple docstring''' super().__init__() snake_case_ = int(dim * mult ) snake_case_ = dim_out if dim_out is not None else dim if activation_fn == "gelu": snake_case_ = GELU(a__ , a__ ) if activation_fn == "gelu-approximate": snake_case_ = GELU(a__ , a__ , approximate="tanh" ) elif activation_fn == "geglu": snake_case_ = GEGLU(a__ , a__ ) elif activation_fn == "geglu-approximate": snake_case_ = ApproximateGELU(a__ , a__ ) snake_case_ = nn.ModuleList([] ) # project in self.net.append(a__ ) # project dropout self.net.append(nn.Dropout(a__ ) ) # project out self.net.append(nn.Linear(a__ , a__ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(a__ ) ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' for module in self.net: snake_case_ = module(a__ ) return hidden_states class _snake_case ( nn.Module ): def __init__( self , a__ , a__ , a__ = "none" ) -> str: '''simple docstring''' super().__init__() snake_case_ = nn.Linear(a__ , a__ ) snake_case_ = approximate def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' if gate.device.type != "mps": return F.gelu(a__ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def lowerCAmelCase__ ( self , a__ ) -> int: '''simple docstring''' snake_case_ = self.proj(a__ ) snake_case_ = self.gelu(a__ ) return hidden_states class _snake_case ( nn.Module ): def __init__( self , a__ , a__ ) -> int: '''simple docstring''' super().__init__() snake_case_ = nn.Linear(a__ , dim_out * 2 ) def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' if gate.device.type != "mps": return F.gelu(a__ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def lowerCAmelCase__ ( self , a__ ) -> List[str]: '''simple docstring''' snake_case_ , snake_case_ = self.proj(a__ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(a__ ) class _snake_case ( nn.Module ): def __init__( self , a__ , a__ ) -> int: '''simple docstring''' super().__init__() snake_case_ = nn.Linear(a__ , a__ ) def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' snake_case_ = self.proj(a__ ) return x * torch.sigmoid(1.7_0_2 * x ) class _snake_case ( nn.Module ): def __init__( self , a__ , a__ ) -> List[str]: '''simple docstring''' super().__init__() snake_case_ = nn.Embedding(a__ , a__ ) snake_case_ = nn.SiLU() snake_case_ = nn.Linear(a__ , embedding_dim * 2 ) snake_case_ = nn.LayerNorm(a__ , elementwise_affine=a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.linear(self.silu(self.emb(a__ ) ) ) snake_case_ , snake_case_ = torch.chunk(a__ , 2 ) snake_case_ = self.norm(a__ ) * (1 + scale) + shift return x class _snake_case ( nn.Module ): def __init__( self , a__ , a__ ) -> List[Any]: '''simple docstring''' super().__init__() snake_case_ = CombinedTimestepLabelEmbeddings(a__ , a__ ) snake_case_ = nn.SiLU() snake_case_ = nn.Linear(a__ , 6 * embedding_dim , bias=a__ ) snake_case_ = nn.LayerNorm(a__ , elementwise_affine=a__ , eps=1e-6 ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__=None ) -> Tuple: '''simple docstring''' snake_case_ = self.linear(self.silu(self.emb(a__ , a__ , hidden_dtype=a__ ) ) ) snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = emb.chunk(6 , dim=1 ) snake_case_ = self.norm(a__ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class _snake_case ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = None , a__ = 1e-5 ) -> int: '''simple docstring''' super().__init__() snake_case_ = num_groups snake_case_ = eps if act_fn is None: snake_case_ = None else: snake_case_ = get_activation(a__ ) snake_case_ = nn.Linear(a__ , out_dim * 2 ) def lowerCAmelCase__ ( self , a__ , a__ ) -> List[str]: '''simple docstring''' if self.act: snake_case_ = self.act(a__ ) snake_case_ = self.linear(a__ ) snake_case_ = emb[:, :, None, None] snake_case_ , snake_case_ = emb.chunk(2 , dim=1 ) snake_case_ = F.group_norm(a__ , self.num_groups , eps=self.eps ) snake_case_ = x * (1 + scale) + shift return x
85
'''simple docstring''' import warnings from functools import wraps from typing import Callable def UpperCamelCase_( snake_case : Callable ): '''simple docstring''' @wraps(snake_case ) def _inner_fn(*snake_case : Optional[int] , **snake_case : List[Any] ): warnings.warn( (f'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , snake_case , ) return fn(*snake_case , **snake_case ) return _inner_fn
85
1
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=lowercase_ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : str = field(default="language-modeling" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCAmelCase_ : ClassVar[Features] = Features({"text": Value("string" )} ) lowerCAmelCase_ : ClassVar[Features] = Features({} ) lowerCAmelCase_ : str = "text" @property def lowerCAmelCase__ ( self ) -> Dict[str, str]: '''simple docstring''' return {self.text_column: "text"}
85
'''simple docstring''' from __future__ import annotations import requests def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case ).json() def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' snake_case_ = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" snake_case_ = requests.get(snake_case ).json()[:max_stories] return [get_hackernews_story(snake_case ) for story_id in story_ids] def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' snake_case_ = hackernews_top_stories(snake_case ) return "\n".join("* [{title}]({url})".format(**snake_case ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
85
1
'''simple docstring''' from __future__ import annotations import numpy as np def UpperCamelCase_( snake_case : list[float] ): '''simple docstring''' return np.maximum(0 , snake_case ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
85
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : Optional[Any] = MODEL_FOR_CAUSAL_LM_MAPPING lowerCAmelCase_ : Optional[Any] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="pt" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ], [ { "generated_text": ( "This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy" " oscope. oscope. FiliFili@@" ) } ], ] , ) snake_case_ = text_generator("This is a test" , do_sample=a__ , num_return_sequences=2 , return_tensors=a__ ) self.assertEqual( a__ , [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ] , ) snake_case_ = text_generator.model.config.eos_token_id snake_case_ = "<pad>" snake_case_ = text_generator( ["This is a test", "This is a second test"] , do_sample=a__ , num_return_sequences=2 , batch_size=2 , return_tensors=a__ , ) self.assertEqual( a__ , [ [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], ] , ) @require_tf def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="tf" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] , do_sample=a__ ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ], [ { "generated_text": ( "This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes" " Cannes 閲閲Cannes Cannes Cannes 攵 please," ) } ], ] , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> str: '''simple docstring''' snake_case_ = TextGenerationPipeline(model=a__ , tokenizer=a__ ) return text_generator, ["This is a test", "Another test"] def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "Hello I believe in" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) snake_case_ = text_generator(a__ ) self.assertEqual( a__ , [{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}] , ) snake_case_ = text_generator(a__ , stop_sequence=" fe" ) self.assertEqual(a__ , [{"generated_text": "Hello I believe in fe"}] ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Tuple: '''simple docstring''' snake_case_ = text_generator.model snake_case_ = text_generator.tokenizer snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = pipeline(task="text-generation" , model=a__ , tokenizer=a__ , return_full_text=a__ ) snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) if text_generator.tokenizer.pad_token is not None: snake_case_ = text_generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_text=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_tensors=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_text=a__ , return_tensors=a__ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): snake_case_ = text_generator("" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): snake_case_ = text_generator("" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. snake_case_ = ["RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM"] if ( tokenizer.model_max_length < 10_000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("This is a test" * 500 , max_new_tokens=20 ) snake_case_ = text_generator("This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(a__ ): text_generator( "This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' import torch # Classic `model_kwargs` snake_case_ = pipeline( model="hf-internal-testing/tiny-random-bloom" , model_kwargs={"device_map": "auto", "torch_dtype": torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) @require_torch @require_torch_gpu def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device=0 , torch_dtype=torch.floataa ) pipe("This is a test" ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.floataa ) pipe("This is a test" , do_sample=a__ , top_p=0.5 ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "Hello world" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) if text_generator.model.framework == "tf": snake_case_ = logging.get_logger("transformers.generation.tf_utils" ) else: snake_case_ = logging.get_logger("transformers.generation.utils" ) snake_case_ = "Both `max_new_tokens`" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 , max_new_tokens=1 ) self.assertIn(a__ , cl.out ) # The user only sets one -> no warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_new_tokens=1 ) self.assertNotIn(a__ , cl.out ) with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 ) self.assertNotIn(a__ , cl.out )
85
1
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _SCREAMING_SNAKE_CASE : Tuple = logging.getLogger(__name__) def UpperCamelCase_( snake_case : List[str] , snake_case : List[str] ): '''simple docstring''' return (preds == labels).mean() @dataclass class _snake_case : lowerCAmelCase_ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) lowerCAmelCase_ : Optional[str] = field( default=lowercase_ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) lowerCAmelCase_ : Optional[str] = field( default=lowercase_ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) lowerCAmelCase_ : Optional[str] = field( default=lowercase_ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class _snake_case : lowerCAmelCase_ : str = field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys() )} ) lowerCAmelCase_ : str = field(metadata={"help": "Should contain the data files for the task."} ) lowerCAmelCase_ : int = 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." ) } , ) lowerCAmelCase_ : bool = field( default=lowercase_ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) snake_case_ , snake_case_ , snake_case_ = 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 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" , snake_case ) # Set seed set_seed(training_args.seed ) try: snake_case_ = processors[data_args.task_name]() snake_case_ = processor.get_labels() snake_case_ = len(snake_case ) except KeyError: raise ValueError("Task not found: %s" % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=snake_case , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) snake_case_ = 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 , ) snake_case_ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=snake_case , cache_dir=model_args.cache_dir , ) # Get datasets snake_case_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=snake_case , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) snake_case_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=snake_case , task=data_args.task_name , 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 compute_metrics(snake_case : EvalPrediction ) -> Dict: snake_case_ = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(snake_case , p.label_ids )} # Data collator snake_case_ = DataCollatorWithPadding(snake_case , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer snake_case_ = Trainer( model=snake_case , args=snake_case , train_dataset=snake_case , eval_dataset=snake_case , compute_metrics=snake_case , data_collator=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_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation snake_case_ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) snake_case_ = trainer.evaluate() snake_case_ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_master(): with open(snake_case , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , snake_case , snake_case ) writer.write("%s = %s\n" % (key, value) ) results.update(snake_case ) return results def UpperCamelCase_( snake_case : Union[str, Any] ): '''simple docstring''' main() if __name__ == "__main__": main()
85
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , lowercase_ ): def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = load_tool("text-classification" ) self.tool.setup() snake_case_ = load_tool("text-classification" , remote=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" )
85
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _snake_case ( lowercase_ ): lowerCAmelCase_ : List[str] = "facebook/bart-large-mnli" lowerCAmelCase_ : Optional[int] = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) lowerCAmelCase_ : Optional[int] = "text_classifier" lowerCAmelCase_ : Optional[Any] = AutoTokenizer lowerCAmelCase_ : Optional[int] = AutoModelForSequenceClassification lowerCAmelCase_ : int = ["text", ["text"]] lowerCAmelCase_ : List[Any] = ["text"] def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' super().setup() snake_case_ = self.model.config snake_case_ = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): snake_case_ = int(a__ ) if self.entailment_id == -1: raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = labels return self.pre_processor( [text] * len(a__ ) , [F'This example is {label}' for label in labels] , return_tensors="pt" , padding="max_length" , ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' snake_case_ = outputs.logits snake_case_ = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
85
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Dict = { "BridgeTower/bridgetower-base": "https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json", "BridgeTower/bridgetower-base-itm-mlm": ( "https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json" ), } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Dict = "bridgetower_vision_model" def __init__( self , a__=768 , a__=12 , a__=3 , a__=16 , a__=288 , a__=1 , a__=1e-05 , a__=False , a__=True , a__=False , **a__ , ) -> int: '''simple docstring''' super().__init__(**a__ ) snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_channels snake_case_ = patch_size snake_case_ = image_size snake_case_ = initializer_factor snake_case_ = layer_norm_eps snake_case_ = stop_gradient snake_case_ = share_layernorm snake_case_ = remove_last_layer @classmethod def lowerCAmelCase__ ( cls , a__ , **a__ ) -> "PretrainedConfig": '''simple docstring''' snake_case_ , snake_case_ = cls.get_config_dict(a__ , **a__ ) if config_dict.get("model_type" ) == "bridgetower": snake_case_ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a__ , **a__ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "bridgetower_text_model" def __init__( self , a__=50_265 , a__=768 , a__=12 , a__=12 , a__=1 , a__=3_072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=514 , a__=1 , a__=1e-05 , a__=1 , a__=0 , a__=2 , a__="absolute" , a__=True , **a__ , ) -> Optional[int]: '''simple docstring''' super().__init__(**a__ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = initializer_factor snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = layer_norm_eps snake_case_ = position_embedding_type snake_case_ = use_cache snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id @classmethod def lowerCAmelCase__ ( cls , a__ , **a__ ) -> "PretrainedConfig": '''simple docstring''' snake_case_ , snake_case_ = cls.get_config_dict(a__ , **a__ ) if config_dict.get("model_type" ) == "bridgetower": snake_case_ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a__ , **a__ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Union[str, Any] = "bridgetower" def __init__( self , a__=True , a__="gelu" , a__=768 , a__=1 , a__=1e-05 , a__=False , a__="add" , a__=12 , a__=6 , a__=False , a__=False , a__=None , a__=None , **a__ , ) -> int: '''simple docstring''' snake_case_ = kwargs.pop("text_config_dict" , a__ ) snake_case_ = kwargs.pop("vision_config_dict" , a__ ) super().__init__(**a__ ) snake_case_ = share_cross_modal_transformer_layers snake_case_ = hidden_act snake_case_ = hidden_size snake_case_ = initializer_factor snake_case_ = layer_norm_eps snake_case_ = share_link_tower_layers snake_case_ = link_tower_type snake_case_ = num_attention_heads snake_case_ = num_hidden_layers snake_case_ = tie_word_embeddings snake_case_ = init_layernorm_from_vision_encoder if text_config is None: snake_case_ = {} logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values." ) if vision_config is None: snake_case_ = {} logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values." ) snake_case_ = BridgeTowerTextConfig(**a__ ) snake_case_ = BridgeTowerVisionConfig(**a__ ) @classmethod def lowerCAmelCase__ ( cls , a__ , a__ , **a__ ) -> List[Any]: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.text_config.to_dict() snake_case_ = self.vision_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1
'''simple docstring''' import os from pathlib import Path def UpperCamelCase_( ): '''simple docstring''' from torch.utils.cpp_extension import load snake_case_ = Path(snake_case ).resolve().parent.parent.parent / "kernels" / "deformable_detr" snake_case_ = [ root / filename for filename in [ "vision.cpp", os.path.join("cpu" , "ms_deform_attn_cpu.cpp" ), os.path.join("cuda" , "ms_deform_attn_cuda.cu" ), ] ] load( "MultiScaleDeformableAttention" , snake_case , with_cuda=snake_case , extra_include_paths=[str(snake_case )] , extra_cflags=["-DWITH_CUDA=1"] , extra_cuda_cflags=[ "-DCUDA_HAS_FP16=1", "-D__CUDA_NO_HALF_OPERATORS__", "-D__CUDA_NO_HALF_CONVERSIONS__", "-D__CUDA_NO_HALF2_OPERATORS__", ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
85
'''simple docstring''' from __future__ import annotations def UpperCamelCase_( snake_case : list[int] ): '''simple docstring''' return len(set(snake_case ) ) == len(snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
85
1
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin _SCREAMING_SNAKE_CASE : List[Any] = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right _SCREAMING_SNAKE_CASE : int = 25_0004 _SCREAMING_SNAKE_CASE : List[str] = 25_0020 @require_sentencepiece @require_tokenizers class _snake_case ( lowercase_ , unittest.TestCase ): lowerCAmelCase_ : str = MBartTokenizer lowerCAmelCase_ : List[Any] = MBartTokenizerFast lowerCAmelCase_ : Tuple = True lowerCAmelCase_ : Any = True def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing snake_case_ = MBartTokenizer(a__ , keep_accents=a__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = MBartTokenizer(a__ , keep_accents=a__ ) snake_case_ = tokenizer.tokenize("This is a test" ) self.assertListEqual(a__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) snake_case_ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) snake_case_ = tokenizer.convert_tokens_to_ids(a__ ) self.assertListEqual( a__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) snake_case_ = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual( a__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return snake_case_ = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): snake_case_ = self.rust_tokenizer_class.from_pretrained(a__ , **a__ ) snake_case_ = self.tokenizer_class.from_pretrained(a__ , **a__ ) snake_case_ = tempfile.mkdtemp() snake_case_ = tokenizer_r.save_pretrained(a__ ) snake_case_ = tokenizer_p.save_pretrained(a__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) snake_case_ = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(a__ , a__ ) # Checks everything loads correctly in the same way snake_case_ = tokenizer_r.from_pretrained(a__ ) snake_case_ = tokenizer_p.from_pretrained(a__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a__ , a__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(a__ ) # Save tokenizer rust, legacy_format=True snake_case_ = tempfile.mkdtemp() snake_case_ = tokenizer_r.save_pretrained(a__ , legacy_format=a__ ) snake_case_ = tokenizer_p.save_pretrained(a__ ) # Checks it save with the same files self.assertSequenceEqual(a__ , a__ ) # Checks everything loads correctly in the same way snake_case_ = tokenizer_r.from_pretrained(a__ ) snake_case_ = tokenizer_p.from_pretrained(a__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a__ , a__ ) ) shutil.rmtree(a__ ) # Save tokenizer rust, legacy_format=False snake_case_ = tempfile.mkdtemp() snake_case_ = tokenizer_r.save_pretrained(a__ , legacy_format=a__ ) snake_case_ = tokenizer_p.save_pretrained(a__ ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way snake_case_ = tokenizer_r.from_pretrained(a__ ) snake_case_ = tokenizer_p.from_pretrained(a__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a__ , a__ ) ) shutil.rmtree(a__ ) @require_torch @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : Optional[Any] = "facebook/mbart-large-en-ro" lowerCAmelCase_ : List[Any] = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase_ : Any = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase_ : Optional[Any] = [8274, 12_7873, 2_5916, 7, 8622, 2071, 438, 6_7485, 53, 18_7895, 23, 5_1712, 2, EN_CODE] @classmethod def lowerCAmelCase__ ( cls ) -> int: '''simple docstring''' snake_case_ = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) snake_case_ = 1 return cls def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 250_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 250_004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 250_020 ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' self.assertIn(a__ , self.tokenizer.all_special_ids ) snake_case_ = [RO_CODE, 884, 9_019, 96, 9, 916, 86_792, 36, 18_743, 15_596, 5, 2] snake_case_ = self.tokenizer.decode(a__ , skip_special_tokens=a__ ) snake_case_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=a__ ) self.assertEqual(a__ , a__ ) self.assertNotIn(self.tokenizer.eos_token , a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , a__ ) snake_case_ = 10 snake_case_ = self.tokenizer(a__ , max_length=a__ , truncation=a__ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , a__ ) self.assertEqual(len(a__ ) , a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [250_026, 250_001] ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = tempfile.mkdtemp() snake_case_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(a__ ) snake_case_ = MBartTokenizer.from_pretrained(a__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , a__ ) @require_torch def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=a__ , return_tensors="pt" ) snake_case_ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=a__ , truncation=a__ , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) snake_case_ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(a__ , a__ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) snake_case_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , a__ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.tokenizer(self.src_text , padding=a__ , truncation=a__ , max_length=3 , return_tensors="pt" ) snake_case_ = self.tokenizer( text_target=self.tgt_text , padding=a__ , truncation=a__ , max_length=10 , return_tensors="pt" ) snake_case_ = targets["input_ids"] snake_case_ = shift_tokens_right(a__ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(a__ ) , { # A, test, EOS, en_XX "input_ids": [[62, 3_034, 2, 250_004]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 250_001, } , )
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = False try: _SCREAMING_SNAKE_CASE : Optional[Any] = _is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class _snake_case : def __init__( self , a__ = None , a__ = [] ) -> List[str]: '''simple docstring''' snake_case_ = 0 snake_case_ = choices snake_case_ = prompt if sys.platform == "win32": snake_case_ = "*" else: snake_case_ = "➔ " def lowerCAmelCase__ ( self , a__ , a__ = "" ) -> int: '''simple docstring''' if sys.platform != "win32": writeColor(self.choices[index] , 32 , a__ ) else: forceWrite(self.choices[index] , a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a__ ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def lowerCAmelCase__ ( self , a__ , a__ = 1 ) -> List[str]: '''simple docstring''' snake_case_ = 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 lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a__ )] for number in range(10 )] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = int(chr(self.current_selection ) ) snake_case_ = 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 lowerCAmelCase__ ( self , a__ = 0 ) -> List[str]: '''simple docstring''' 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" ) snake_case_ = 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: snake_case_ = int(builtins.input() ) except ValueError: snake_case_ = default_choice else: snake_case_ = 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
85
1
'''simple docstring''' import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin _SCREAMING_SNAKE_CASE : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") class _snake_case ( lowercase_ , unittest.TestCase ): lowerCAmelCase_ : List[str] = BartphoTokenizer lowerCAmelCase_ : Dict = False lowerCAmelCase_ : str = True def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' super().setUp() snake_case_ = ["▁This", "▁is", "▁a", "▁t", "est"] snake_case_ = dict(zip(a__ , range(len(a__ ) ) ) ) snake_case_ = {"unk_token": "<unk>"} snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["monolingual_vocab_file"] ) with open(self.monolingual_vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(F'{token} {vocab_tokens[token]}\n' ) snake_case_ = BartphoTokenizer(a__ , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase__ ( self , **a__ ) -> Any: '''simple docstring''' kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **a__ ) def lowerCAmelCase__ ( self , a__ ) -> int: '''simple docstring''' snake_case_ = "This is a là test" snake_case_ = "This is a<unk><unk> test" return input_text, output_text def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = BartphoTokenizer(a__ , self.monolingual_vocab_file , **self.special_tokens_map ) snake_case_ = "This is a là test" snake_case_ = "▁This ▁is ▁a ▁l à ▁t est".split() snake_case_ = tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = tokens + [tokenizer.unk_token] snake_case_ = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , a__ )
85
'''simple docstring''' import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def UpperCamelCase_( snake_case : Optional[int] ): '''simple docstring''' return EnvironmentCommand() class _snake_case ( lowercase_ ): @staticmethod def lowerCAmelCase__ ( a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = parser.add_parser("env" ) download_parser.set_defaults(func=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = huggingface_hub.__version__ snake_case_ = "not installed" snake_case_ = "NA" if is_torch_available(): import torch snake_case_ = torch.__version__ snake_case_ = torch.cuda.is_available() snake_case_ = "not installed" if is_transformers_available(): import transformers snake_case_ = transformers.__version__ snake_case_ = "not installed" if is_accelerate_available(): import accelerate snake_case_ = accelerate.__version__ snake_case_ = "not installed" if is_xformers_available(): import xformers snake_case_ = xformers.__version__ snake_case_ = { "`diffusers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "PyTorch version (GPU?)": F'{pt_version} ({pt_cuda_available})', "Huggingface_hub version": hub_version, "Transformers version": transformers_version, "Accelerate version": accelerate_version, "xFormers version": xformers_version, "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(a__ ) ) return info @staticmethod def lowerCAmelCase__ ( a__ ) -> str: '''simple docstring''' return "\n".join([F'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
85
1
'''simple docstring''' _SCREAMING_SNAKE_CASE : Any = 0 # The first color of the flag. _SCREAMING_SNAKE_CASE : Dict = 1 # The second color of the flag. _SCREAMING_SNAKE_CASE : Tuple = 2 # The third color of the flag. _SCREAMING_SNAKE_CASE : Union[str, Any] = (red, white, blue) def UpperCamelCase_( snake_case : list ): '''simple docstring''' if not sequence: return [] if len(snake_case ) == 1: return list(snake_case ) snake_case_ = 0 snake_case_ = len(snake_case ) - 1 snake_case_ = 0 while mid <= high: if sequence[mid] == colors[0]: snake_case_ , snake_case_ = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: snake_case_ , snake_case_ = sequence[high], sequence[mid] high -= 1 else: snake_case_ = f'The elements inside the sequence must contains only {colors} values' raise ValueError(snake_case ) return sequence if __name__ == "__main__": import doctest doctest.testmod() _SCREAMING_SNAKE_CASE : Optional[int] = input("Enter numbers separated by commas:\n").strip() _SCREAMING_SNAKE_CASE : Tuple = [int(item.strip()) for item in user_input.split(",")] print(F"{dutch_national_flag_sort(unsorted)}")
85
'''simple docstring''' import os _SCREAMING_SNAKE_CASE : int = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = 0 snake_case_ = 0 while index < len(snake_case ) - 1: snake_case_ = SYMBOLS[numerals[index]] snake_case_ = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = "" snake_case_ = num // 1_0_0_0 numerals += m_count * "M" num %= 1_0_0_0 snake_case_ = num // 1_0_0 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_0_0 snake_case_ = num // 1_0 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 1_0 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def UpperCamelCase_( snake_case : str = "/p089_roman.txt" ): '''simple docstring''' snake_case_ = 0 with open(os.path.dirname(snake_case ) + roman_numerals_filename ) as filea: snake_case_ = filea.readlines() for line in lines: snake_case_ = line.strip() snake_case_ = parse_roman_numerals(snake_case ) snake_case_ = generate_roman_numerals(snake_case ) savings += len(snake_case ) - len(snake_case ) return savings if __name__ == "__main__": print(F"{solution() = }")
85
1
'''simple docstring''' import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _SCREAMING_SNAKE_CASE : Dict = "\\n Text data.\n Second line of data." _SCREAMING_SNAKE_CASE : Union[str, Any] = "file" @pytest.fixture(scope="session" ) def UpperCamelCase_( snake_case : Any ): '''simple docstring''' snake_case_ = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") snake_case_ = bytes(snake_case , "utf-8" ) with zstd.open(snake_case , "wb" ) as f: f.write(snake_case ) return path @pytest.fixture def UpperCamelCase_( snake_case : Dict ): '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , snake_case ) , "w" ) as f: f.write(snake_case ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def UpperCamelCase_( snake_case : Tuple , snake_case : Optional[int] , snake_case : int , snake_case : Optional[int] , snake_case : int , snake_case : Tuple ): '''simple docstring''' snake_case_ = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} snake_case_ = input_paths[compression_format] snake_case_ = tmp_path / "cache" snake_case_ = DownloadConfig(cache_dir=snake_case , extract_compressed_file=snake_case ) snake_case_ = cached_path(snake_case , download_config=snake_case ) with open(snake_case ) as f: snake_case_ = f.read() with open(snake_case ) as f: snake_case_ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def UpperCamelCase_( snake_case : Optional[Any] , snake_case : Dict , snake_case : Tuple , snake_case : List[Any] , snake_case : Tuple ): '''simple docstring''' snake_case_ = "custom_cache" snake_case_ = "custom_extracted_dir" snake_case_ = tmp_path / "custom_extracted_path" if default_extracted: snake_case_ = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , snake_case ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(snake_case ) ) snake_case_ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) snake_case_ = xz_file snake_case_ = ( DownloadConfig(extract_compressed_file=snake_case ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=snake_case ) ) snake_case_ = cached_path(snake_case , download_config=snake_case ) assert Path(snake_case ).parent.parts[-2:] == expected def UpperCamelCase_( snake_case : Optional[Any] ): '''simple docstring''' snake_case_ = str(Path(snake_case ).resolve() ) assert cached_path(snake_case ) == text_file # relative path snake_case_ = str(Path(snake_case ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(snake_case ) == text_file def UpperCamelCase_( snake_case : Tuple ): '''simple docstring''' snake_case_ = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(snake_case ): cached_path(snake_case ) # relative path snake_case_ = "./__missing_file__.txt" with pytest.raises(snake_case ): cached_path(snake_case ) def UpperCamelCase_( snake_case : Union[str, Any] ): '''simple docstring''' snake_case_ = get_from_cache(f'tmp://{tmpfs_file}' ) with open(snake_case ) as f: snake_case_ = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , snake_case ) def UpperCamelCase_( ): '''simple docstring''' with pytest.raises(snake_case ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , snake_case ) def UpperCamelCase_( snake_case : Union[str, Any] ): '''simple docstring''' snake_case_ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(snake_case ): http_get("https://huggingface.co" , temp_file=snake_case ) with pytest.raises(snake_case ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , snake_case ) def UpperCamelCase_( snake_case : Any ): '''simple docstring''' snake_case_ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(snake_case ): ftp_get("ftp://huggingface.co" , temp_file=snake_case ) with pytest.raises(snake_case ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , snake_case ) def UpperCamelCase_( snake_case : List[str] ): '''simple docstring''' snake_case_ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(snake_case ): fsspec_get("s3://huggingface.co" , temp_file=snake_case ) with pytest.raises(snake_case ): fsspec_head("s3://huggingface.co" )
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _SCREAMING_SNAKE_CASE : int = { "configuration_clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig", ], "processing_clip": ["CLIPProcessor"], "tokenization_clip": ["CLIPTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = ["CLIPTokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = ["CLIPFeatureExtractor"] _SCREAMING_SNAKE_CASE : Dict = ["CLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' import heapq import sys import numpy as np _SCREAMING_SNAKE_CASE : Optional[int] = tuple[int, int] class _snake_case : def __init__( self ) -> List[Any]: '''simple docstring''' snake_case_ = [] snake_case_ = set() def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float("inf" ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' return len(self.elements ) == 0 def lowerCAmelCase__ ( self , a__ , a__ ) -> List[str]: '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(a__ ) else: # update # print("update", item) snake_case_ = [] ((snake_case_) , (snake_case_)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((snake_case_) , (snake_case_)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def lowerCAmelCase__ ( self , a__ ) -> int: '''simple docstring''' if item in self.set: self.set.remove(a__ ) snake_case_ = [] ((snake_case_) , (snake_case_)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((snake_case_) , (snake_case_)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' return self.elements[0][1] def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' ((snake_case_) , (snake_case_)) = heapq.heappop(self.elements ) self.set.remove(a__ ) return (priority, item) def UpperCamelCase_( snake_case : TPos , snake_case : TPos ): '''simple docstring''' snake_case_ = np.array(snake_case ) snake_case_ = np.array(snake_case ) return np.linalg.norm(a - b ) def UpperCamelCase_( snake_case : TPos , snake_case : TPos ): '''simple docstring''' return consistent_heuristic(snake_case , snake_case ) // t def UpperCamelCase_( snake_case : TPos , snake_case : TPos ): '''simple docstring''' return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def UpperCamelCase_( snake_case : TPos , snake_case : int , snake_case : TPos , snake_case : dict[TPos, float] ): '''simple docstring''' snake_case_ = g_function[start] + Wa * heuristics[i](snake_case , snake_case ) return ans def UpperCamelCase_( snake_case : List[Any] , snake_case : List[Any] , snake_case : int ): '''simple docstring''' snake_case_ = np.chararray((n, n) ) for i in range(snake_case ): for j in range(snake_case ): snake_case_ = "*" for i in range(snake_case ): for j in range(snake_case ): if (j, (n - 1) - i) in blocks: snake_case_ = "#" snake_case_ = "-" snake_case_ = back_pointer[goal] while x != start: ((snake_case_) , (snake_case_)) = x # print(x) snake_case_ = "-" snake_case_ = back_pointer[x] snake_case_ = "-" for i in range(snake_case ): for j in range(snake_case ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) snake_case_ = back_pointer[goal] while x != start: print(snake_case , end=" " ) snake_case_ = back_pointer[x] print(snake_case ) sys.exit() def UpperCamelCase_( snake_case : TPos ): '''simple docstring''' if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def UpperCamelCase_( snake_case : List[Any] , snake_case : int , snake_case : Tuple , snake_case : int , snake_case : List[str] , snake_case : Tuple , snake_case : Dict , snake_case : Dict , ): '''simple docstring''' for itera in range(snake_case ): open_list[itera].remove_element(snake_case ) # print("s", s) # print("j", j) ((snake_case_) , (snake_case_)) = s snake_case_ = (x - 1, y) snake_case_ = (x + 1, y) snake_case_ = (x, y + 1) snake_case_ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(snake_case ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(snake_case ) snake_case_ = -1 snake_case_ = float("inf" ) if valid(snake_case ) and g_function[neighbours] > g_function[s] + 1: snake_case_ = g_function[s] + 1 snake_case_ = s if neighbours not in close_list_anchor: open_list[0].put(snake_case , key(snake_case , 0 , snake_case , snake_case ) ) if neighbours not in close_list_inad: for var in range(1 , snake_case ): if key(snake_case , snake_case , snake_case , snake_case ) <= Wa * key( snake_case , 0 , snake_case , snake_case ): open_list[j].put( snake_case , key(snake_case , snake_case , snake_case , snake_case ) ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(1_5 , 2_0 ): some_list.append((x, 1_7) ) for x in range(1_0 , 1_9 ): for y in range(1 , 1_5 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(1_2 , 1_9 ): some_list.append((x, y) ) for x in range(3 , 1_3 ): for y in range(1_6 , 1_9 ): some_list.append((x, y) ) return some_list _SCREAMING_SNAKE_CASE : Optional[int] = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} _SCREAMING_SNAKE_CASE : int = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] _SCREAMING_SNAKE_CASE : Optional[int] = make_common_ground() _SCREAMING_SNAKE_CASE : List[str] = blocks_blk # hyper parameters _SCREAMING_SNAKE_CASE : Tuple = 1 _SCREAMING_SNAKE_CASE : Optional[int] = 1 _SCREAMING_SNAKE_CASE : int = 20 _SCREAMING_SNAKE_CASE : Tuple = 3 # one consistent and two other inconsistent # start and end destination _SCREAMING_SNAKE_CASE : List[str] = (0, 0) _SCREAMING_SNAKE_CASE : Optional[int] = (n - 1, n - 1) _SCREAMING_SNAKE_CASE : Tuple = 1 def UpperCamelCase_( snake_case : TPos , snake_case : TPos , snake_case : int ): '''simple docstring''' snake_case_ = {start: 0, goal: float("inf" )} snake_case_ = {start: -1, goal: -1} snake_case_ = [] snake_case_ = set() for i in range(snake_case ): open_list.append(PriorityQueue() ) open_list[i].put(snake_case , key(snake_case , snake_case , snake_case , snake_case ) ) snake_case_ = [] snake_case_ = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , snake_case ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(snake_case , snake_case , snake_case ) else: snake_case_ , snake_case_ = open_list[i].top_show() visited.add(snake_case ) expand_state( snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ) close_list_inad.append(snake_case ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(snake_case , snake_case , snake_case ) else: snake_case_ = open_list[0].top_show() visited.add(snake_case ) expand_state( snake_case , 0 , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ) close_list_anchor.append(snake_case ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(snake_case ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
85
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE : Union[str, Any] = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } _SCREAMING_SNAKE_CASE : int = { "gpt-neox-20b": 2048, } class _snake_case ( lowercase_ ): lowerCAmelCase_ : str = VOCAB_FILES_NAMES lowerCAmelCase_ : Tuple = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ : str = ["input_ids", "attention_mask"] def __init__( self , a__=None , a__=None , a__=None , a__="<|endoftext|>" , a__="<|endoftext|>" , a__="<|endoftext|>" , a__=False , **a__ , ) -> Tuple: '''simple docstring''' super().__init__( a__ , a__ , tokenizer_file=a__ , unk_token=a__ , bos_token=a__ , eos_token=a__ , add_prefix_space=a__ , **a__ , ) snake_case_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , a__ ) != add_prefix_space: snake_case_ = getattr(a__ , pre_tok_state.pop("type" ) ) snake_case_ = add_prefix_space snake_case_ = pre_tok_class(**a__ ) snake_case_ = add_prefix_space def lowerCAmelCase__ ( self , a__ , a__ = None ) -> Tuple[str]: '''simple docstring''' snake_case_ = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ ) def lowerCAmelCase__ ( self , a__ ) -> List[int]: '''simple docstring''' snake_case_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(a__ , add_special_tokens=a__ ) + [self.eos_token_id] ) if len(a__ ) > self.model_max_length: snake_case_ = input_ids[-self.model_max_length :] return input_ids
85
1
'''simple docstring''' from collections import namedtuple _SCREAMING_SNAKE_CASE : Optional[Any] = namedtuple("from_to", "from_ to") _SCREAMING_SNAKE_CASE : Dict = { "cubicmeter": from_to(1, 1), "litre": from_to(0.0_0_1, 1000), "kilolitre": from_to(1, 1), "gallon": from_to(0.0_0_4_5_4, 2_6_4.1_7_2), "cubicyard": from_to(0.7_6_4_5_5, 1.3_0_7_9_5), "cubicfoot": from_to(0.0_2_8, 3_5.3_1_4_7), "cup": from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def UpperCamelCase_( snake_case : float , snake_case : str , snake_case : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( f'Invalid \'from_type\' value: {from_type!r} Supported values are:\n' + ", ".join(snake_case ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f'Invalid \'to_type\' value: {to_type!r}. Supported values are:\n' + ", ".join(snake_case ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def UpperCamelCase_( snake_case : Tuple ): '''simple docstring''' snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = 0.01 with locka.acquire(): with pytest.raises(snake_case ): snake_case_ = time.time() locka.acquire(snake_case ) assert time.time() - _start > timeout def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = "a" * 1_0_0_0 + ".lock" snake_case_ = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(snake_case ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 snake_case_ = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case ): locka.acquire(0 )
85
1
'''simple docstring''' # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar _SCREAMING_SNAKE_CASE : List[str] = TypeVar("T") class _snake_case ( Generic[T] ): def __init__( self , a__ = True ) -> None: '''simple docstring''' snake_case_ = {} # dictionary of lists snake_case_ = directed def lowerCAmelCase__ ( self , a__ , a__ ) -> GraphAdjacencyList[T]: '''simple docstring''' if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(a__ ) self.adj_list[destination_vertex].append(a__ ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(a__ ) snake_case_ = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(a__ ) snake_case_ = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: snake_case_ = [destination_vertex] snake_case_ = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(a__ ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(a__ ) snake_case_ = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: snake_case_ = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: snake_case_ = [destination_vertex] snake_case_ = [] return self def __repr__( self ) -> str: '''simple docstring''' return pformat(self.adj_list )
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _snake_case ( datasets.BuilderConfig ): lowerCAmelCase_ : Optional[datasets.Features] = None def UpperCamelCase_( snake_case : "pyspark.sql.DataFrame" , snake_case : List[int] , ): '''simple docstring''' import pyspark def generate_fn(): snake_case_ = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: snake_case_ = df_with_partition_id.select("*" ).where(f'part_id = {partition_id}' ).drop("part_id" ) snake_case_ = partition_df.collect() snake_case_ = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class _snake_case ( _BaseExamplesIterable ): def __init__( self , a__ , a__=None , ) -> Any: '''simple docstring''' snake_case_ = df snake_case_ = partition_order or range(self.df.rdd.getNumPartitions() ) snake_case_ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Union[str, Any]: '''simple docstring''' yield from self.generate_examples_fn() def lowerCAmelCase__ ( self , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = self.split_shard_indices_by_worker(a__ , a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) @property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return len(self.partition_order ) class _snake_case ( datasets.DatasetBuilder ): lowerCAmelCase_ : Dict = SparkConfig def __init__( self , a__ , a__ = None , a__ = None , **a__ , ) -> str: '''simple docstring''' import pyspark snake_case_ = pyspark.sql.SparkSession.builder.getOrCreate() snake_case_ = df snake_case_ = working_dir super().__init__( cache_dir=a__ , config_name=str(self.df.semanticHash() ) , **a__ , ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' def create_cache_and_write_probe(a__ ): # 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__ ) snake_case_ = 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: snake_case_ = ( 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 lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' import pyspark def get_arrow_batch_size(a__ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) snake_case_ = self.df.count() snake_case_ = 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. snake_case_ = ( 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 ) snake_case_ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. snake_case_ = min(a__ , int(approx_total_size / max_shard_size ) ) snake_case_ = self.df.repartition(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: '''simple docstring''' import pyspark snake_case_ = ParquetWriter if file_format == "parquet" else ArrowWriter snake_case_ = os.path.join(self._working_dir , os.path.basename(a__ ) ) if self._working_dir else fpath snake_case_ = 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. snake_case_ = self.config.features snake_case_ = self._writer_batch_size snake_case_ = self._fs.storage_options def write_arrow(a__ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. snake_case_ = pyspark.TaskContext().taskAttemptId() snake_case_ = 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"] , ) snake_case_ = 0 snake_case_ = 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__ , ) snake_case_ = 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: snake_case_ , snake_case_ = 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 snake_case_ = 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__ , ) snake_case_ = pa.Table.from_batches([batch] ) writer.write_table(a__ ) if writer._num_bytes > 0: snake_case_ , snake_case_ = 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__ ) ): snake_case_ = os.path.join(os.path.dirname(a__ ) , os.path.basename(a__ ) ) shutil.move(a__ , a__ ) snake_case_ = ( 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 lowerCAmelCase__ ( self , a__ , a__ = "arrow" , a__ = None , a__ = None , **a__ , ) -> int: '''simple docstring''' self._validate_cache_dir() snake_case_ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a__ ) snake_case_ = not is_remote_filesystem(self._fs ) snake_case_ = os.path.join if is_local else posixpath.join snake_case_ = "-TTTTT-SSSSS-of-NNNNN" snake_case_ = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' snake_case_ = path_join(self._output_dir , a__ ) snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = [] snake_case_ = [] for task_id, content in self._prepare_split_single(a__ , a__ , a__ ): ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = 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__ ) snake_case_ = total_num_examples snake_case_ = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: snake_case_ = 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. snake_case_ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a__ , a__ , a__ , ): 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}' ) , ) snake_case_ = [] snake_case_ = 0 for i in range(len(a__ ) ): snake_case_ , snake_case_ = 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 snake_case_ = 0 snake_case_ = 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 lowerCAmelCase__ ( self , a__ , ) -> SparkExamplesIterable: '''simple docstring''' return SparkExamplesIterable(self.df )
85
1
'''simple docstring''' from heapq import heappop, heappush import numpy as np def UpperCamelCase_( snake_case : np.ndarray , snake_case : tuple[int, int] , snake_case : tuple[int, int] , snake_case : bool , ): '''simple docstring''' snake_case_ , snake_case_ = grid.shape snake_case_ = [-1, 1, 0, 0] snake_case_ = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] snake_case_ , snake_case_ = [(0, source)], set() snake_case_ = np.full((rows, cols) , np.inf ) snake_case_ = 0 snake_case_ = np.empty((rows, cols) , dtype=snake_case ) snake_case_ = None while queue: ((snake_case_) , (snake_case_)) = heappop(snake_case ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: snake_case_ = [] while (x, y) != source: path.append((x, y) ) snake_case_ , snake_case_ = predecessors[x, y] path.append(snake_case ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(snake_case ) ): snake_case_ , snake_case_ = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: snake_case_ = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(snake_case , (dist + 1, (nx, ny)) ) snake_case_ = dist + 1 snake_case_ = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB 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 typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : List[str] = { "configuration_cpmant": ["CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CpmAntConfig"], "tokenization_cpmant": ["CpmAntTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST", "CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) snake_case_ = Vector() def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(a__ ) , "(0,0,0,0,0,1)" ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 2, 3, 4] ) self.assertEqual(len(a__ ) , 4 ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 2] ) snake_case_ = Vector([1, 2, 3, 4, 5] ) snake_case_ = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) snake_case_ = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.2_3_6 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.4_1_6 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.6_1_6 , 3 ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 2, 3] ) snake_case_ = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 2, 3] ) snake_case_ = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 2, 3] ) snake_case_ = Vector([2, -1, 4] ) # for test of dot product snake_case_ = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , "(3.0,6.0,9.0)" ) self.assertEqual((a * b) , 0 ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' self.assertEqual(str(zero_vector(10 ) ).count("0" ) , 10 ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , "(0,1,0)" ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 2, 3] ) snake_case_ = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , a__ , a__ ) ) , "(3,4,7)" ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 0, 0, 0, 0, 0] ) snake_case_ = x.copy() self.assertEqual(str(a__ ) , str(a__ ) ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(a__ ) , "(0,1,0)" ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n" , str(a__ ) ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) snake_case_ = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(a__ , a__ ) ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) snake_case_ = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(a__ , a__ ) ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) snake_case_ = Vector([1, 2, 3] ) self.assertEqual("(14,32,50)" , str(a * x ) ) self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n" , str(a * 2 ) ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n" , str(a__ ) ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.0_1 ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) snake_case_ = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n" , str(a + b ) ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' snake_case_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) snake_case_ = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n" , str(a - b ) ) def lowerCAmelCase__ ( self ) -> None: '''simple docstring''' self.assertEqual( "|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n" , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
85
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu _SCREAMING_SNAKE_CASE : Union[str, Any] = False class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return 32 @property def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 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 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(a__ ) @property def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 12 snake_case_ = 12 snake_case_ = { "attention_bias": True, "cross_attention_dim": 32, "attention_head_dim": height * width, "num_attention_heads": 1, "num_vector_embeds": self.num_embed, "num_embeds_ada_norm": self.num_embeds_ada_norm, "norm_num_groups": 32, "sample_size": width, "activation_fn": "geglu-approximate", } snake_case_ = TransformeraDModel(**a__ ) return model def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings(learnable=a__ ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_5_5_1, 0.6_1_6_8, 0.5_0_0_8, 0.5_6_7_6, 0.5_6_5_9, 0.4_2_9_5, 0.6_0_7_3, 0.5_5_9_9, 0.4_9_9_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings( learnable=a__ , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_6_9_3, 0.6_0_7_5, 0.4_9_5_9, 0.5_7_0_1, 0.5_5_8_3, 0.4_3_3_3, 0.6_1_7_1, 0.5_6_8_4, 0.4_9_8_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy" ) snake_case_ = VQDiffusionPipeline.from_pretrained("microsoft/vq-diffusion-ithq" ) snake_case_ = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipeline( "teddy bear playing in the pool" , num_images_per_prompt=1 , generator=a__ , output_type="np" , ) snake_case_ = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
85
1
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer _SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Tuple = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE : Dict = { "vocab_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json" }, "merges_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt" }, } _SCREAMING_SNAKE_CASE : Optional[int] = {"allegro/herbert-base-cased": 514} _SCREAMING_SNAKE_CASE : Any = {} class _snake_case ( lowercase_ ): lowerCAmelCase_ : Optional[int] = VOCAB_FILES_NAMES lowerCAmelCase_ : int = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ : Optional[Any] = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase_ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ : str = HerbertTokenizer def __init__( self , a__=None , a__=None , a__=None , a__="<s>" , a__="<unk>" , a__="<pad>" , a__="<mask>" , a__="</s>" , **a__ , ) -> List[str]: '''simple docstring''' super().__init__( a__ , a__ , tokenizer_file=a__ , cls_token=a__ , unk_token=a__ , pad_token=a__ , mask_token=a__ , sep_token=a__ , **a__ , ) def lowerCAmelCase__ ( self , a__ , a__ = None ) -> List[int]: '''simple docstring''' snake_case_ = [self.cls_token_id] snake_case_ = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase__ ( self , a__ , a__ = None , a__ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a__ , token_ids_a=a__ , already_has_special_tokens=a__ ) if token_ids_a is None: return [1] + ([0] * len(a__ )) + [1] return [1] + ([0] * len(a__ )) + [1] + ([0] * len(a__ )) + [1] def lowerCAmelCase__ ( self , a__ , a__ = None ) -> List[int]: '''simple docstring''' snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase__ ( self , a__ , a__ = None ) -> Tuple[str]: '''simple docstring''' snake_case_ = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
85
'''simple docstring''' from statistics import mean, stdev def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = min(snake_case ) snake_case_ = max(snake_case ) # normalize data return [round((x - x_min) / (x_max - x_min) , snake_case ) for x in data] def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = mean(snake_case ) snake_case_ = stdev(snake_case ) # standardize data return [round((x - mu) / (sigma) , snake_case ) for x in data]
85
1
'''simple docstring''' import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Dict = CLIPConfig lowerCAmelCase_ : Dict = ["CLIPEncoderLayer"] def __init__( self , a__ ) -> Dict: '''simple docstring''' super().__init__(a__ ) snake_case_ = CLIPVisionModelWithProjection(config.vision_config ) snake_case_ = nn.Linear(config.vision_config.projection_dim , 1 ) snake_case_ = nn.Linear(config.vision_config.projection_dim , 1 ) @torch.no_grad() def lowerCAmelCase__ ( self , a__ , a__ , a__=0.5 , a__=0.5 ) -> Any: '''simple docstring''' snake_case_ = self.vision_model(a__ )[0] snake_case_ = self.p_head(a__ ) snake_case_ = nsfw_detected.flatten() snake_case_ = nsfw_detected > p_threshold snake_case_ = nsfw_detected.tolist() if any(a__ ): logger.warning( "Potential NSFW content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, nsfw_detected_ in enumerate(a__ ): if nsfw_detected_: snake_case_ = np.zeros(images[idx].shape ) snake_case_ = self.w_head(a__ ) snake_case_ = watermark_detected.flatten() snake_case_ = watermark_detected > w_threshold snake_case_ = watermark_detected.tolist() if any(a__ ): logger.warning( "Potential watermarked content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, watermark_detected_ in enumerate(a__ ): if watermark_detected_: snake_case_ = np.zeros(images[idx].shape ) return images, nsfw_detected, watermark_detected
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : str = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
85
1
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("Googling.....") _SCREAMING_SNAKE_CASE : Tuple = "https://www.google.com/search?q=" + " ".join(sys.argv[1:]) _SCREAMING_SNAKE_CASE : str = requests.get(url, headers={"UserAgent": UserAgent().random}) # res.raise_for_status() with open("project1a.html", "wb") as out_file: # only for knowing the class for data in res.iter_content(1_0000): out_file.write(data) _SCREAMING_SNAKE_CASE : Any = BeautifulSoup(res.text, "html.parser") _SCREAMING_SNAKE_CASE : List[Any] = list(soup.select(".eZt8xd"))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("href")) else: webbrowser.open(F"https://google.com{link.get('href')}")
85
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. snake_case_ = min(snake_case , snake_case ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
85
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _SCREAMING_SNAKE_CASE : Optional[int] = { "configuration_xlm": ["XLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMConfig", "XLMOnnxConfig"], "tokenization_xlm": ["XLMTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Tuple = [ "XLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMForMultipleChoice", "XLMForQuestionAnswering", "XLMForQuestionAnsweringSimple", "XLMForSequenceClassification", "XLMForTokenClassification", "XLMModel", "XLMPreTrainedModel", "XLMWithLMHeadModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Dict = [ "TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLMForMultipleChoice", "TFXLMForQuestionAnsweringSimple", "TFXLMForSequenceClassification", "TFXLMForTokenClassification", "TFXLMMainLayer", "TFXLMModel", "TFXLMPreTrainedModel", "TFXLMWithLMHeadModel", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE : Tuple = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConditionalDetrConfig", "ConditionalDetrOnnxConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = ["ConditionalDetrFeatureExtractor"] _SCREAMING_SNAKE_CASE : List[Any] = ["ConditionalDetrImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Dict = [ "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "ConditionalDetrForObjectDetection", "ConditionalDetrForSegmentation", "ConditionalDetrModel", "ConditionalDetrPreTrainedModel", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' import random from .binary_exp_mod import bin_exp_mod def UpperCamelCase_( snake_case : Union[str, Any] , snake_case : str=1_0_0_0 ): '''simple docstring''' if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd snake_case_ = n - 1 snake_case_ = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) snake_case_ = 0 while count < prec: snake_case_ = random.randint(2 , n - 1 ) snake_case_ = bin_exp_mod(snake_case , snake_case , snake_case ) if b != 1: snake_case_ = True for _ in range(snake_case ): if b == n - 1: snake_case_ = False break snake_case_ = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Dict = abs(int(input("Enter bound : ").strip())) print("Here's the list of primes:") print(", ".join(str(i) for i in range(n + 1) if is_prime_big(i)))
85
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--txt2img_unclip", default="kakaobrain/karlo-v1-alpha", type=str, required=False, help="The pretrained txt2img unclip.", ) _SCREAMING_SNAKE_CASE : int = parser.parse_args() _SCREAMING_SNAKE_CASE : List[Any] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor() _SCREAMING_SNAKE_CASE : str = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") _SCREAMING_SNAKE_CASE : int = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
85
1
'''simple docstring''' import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' debug_launcher(test_script.main ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' debug_launcher(test_ops.main )
85
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "upernet" def __init__( self , a__=None , a__=512 , a__=0.0_2 , a__=[1, 2, 3, 6] , a__=True , a__=0.4 , a__=384 , a__=256 , a__=1 , a__=False , a__=255 , **a__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**a__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) snake_case_ = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a__ , a__ ): snake_case_ = backbone_config.get("model_type" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(a__ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1
'''simple docstring''' import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class _snake_case ( lowercase_ ): def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' with self.assertRaises(a__ ): snake_case_ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' with self.assertRaises(a__ ): snake_case_ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("bool" ) , type=Value("int64" ) ) ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = pa.array(TypedSequence([1, 2, 3] , type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): snake_case_ = pa.array(TypedSequence(["foo", "bar"] , type=Value("int64" ) ) ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = pa.array(TypedSequence(["foo", "bar"] , try_type=Value("int64" ) ) ) self.assertEqual(arr.type , pa.string() ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): snake_case_ = pa.array(TypedSequence(["foo", "bar"] , type=ArrayaD((1, 3) , "int64" ) ) ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = pa.array(TypedSequence(["foo", "bar"] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' import PIL.Image snake_case_ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( "datasets.arrow_writer.cast_to_python_objects" , side_effect=a__ ) as mock_cast_to_python_objects: snake_case_ = pa.array(TypedSequence([{"path": None, "bytes": b"image_bytes"}, pil_image] , type=Image() ) ) snake_case_ , snake_case_ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("optimize_list_casting" , a__ ) self.assertFalse(kwargs["optimize_list_casting"] ) def UpperCamelCase_( snake_case : Any , snake_case : int ): '''simple docstring''' snake_case_ = pa.BufferReader(snake_case ) if isinstance(snake_case , pa.Buffer ) else pa.memory_map(snake_case ) snake_case_ = pa.ipc.open_stream(snake_case ) snake_case_ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("writer_batch_size" , [None, 1, 1_0] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def UpperCamelCase_( snake_case : Dict , snake_case : Dict ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() snake_case_ = pa.schema(snake_case ) if fields else None with ArrowWriter(stream=snake_case , schema=snake_case , writer_batch_size=snake_case ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case_ = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(snake_case , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() snake_case_ = Features({"labels": ClassLabel(names=["neg", "pos"] )} ) with ArrowWriter(stream=snake_case , features=snake_case ) as writer: writer.write({"labels": 0} ) writer.write({"labels": 1} ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata snake_case_ = pa.BufferReader(output.getvalue() ) snake_case_ = pa.ipc.open_stream(snake_case ) snake_case_ = f.read_all() snake_case_ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(snake_case ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 1_0] ) def UpperCamelCase_( snake_case : Optional[Any] ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() with ArrowWriter( stream=snake_case , writer_batch_size=snake_case , hash_salt="split_name" , check_duplicates=snake_case , ) as writer: with pytest.raises(snake_case ): writer.write({"col_1": "foo", "col_2": 1} , key=[1, 2] ) snake_case_ , snake_case_ = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 1_0] ) def UpperCamelCase_( snake_case : Dict ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() with ArrowWriter( stream=snake_case , writer_batch_size=snake_case , hash_salt="split_name" , check_duplicates=snake_case , ) as writer: with pytest.raises(snake_case ): writer.write({"col_1": "foo", "col_2": 1} , key=1_0 ) writer.write({"col_1": "bar", "col_2": 2} , key=1_0 ) snake_case_ , snake_case_ = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 1_0] ) def UpperCamelCase_( snake_case : Any ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() with ArrowWriter( stream=snake_case , writer_batch_size=snake_case , hash_salt="split_name" , check_duplicates=snake_case , ) as writer: writer.write({"col_1": "foo", "col_2": 1} , key=1 ) writer.write({"col_1": "bar", "col_2": 2} , key=2 ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 1_0] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def UpperCamelCase_( snake_case : Union[str, Any] , snake_case : List[str] ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() snake_case_ = pa.schema(snake_case ) if fields else None with ArrowWriter(stream=snake_case , schema=snake_case , writer_batch_size=snake_case ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) writer.write_batch({"col_1": [], "col_2": []} ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case_ = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(snake_case , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 1_0] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def UpperCamelCase_( snake_case : str , snake_case : Dict ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() snake_case_ = pa.schema(snake_case ) if fields else None with ArrowWriter(stream=snake_case , schema=snake_case , writer_batch_size=snake_case ) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case_ = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(snake_case , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 1_0] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def UpperCamelCase_( snake_case : Optional[Any] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() snake_case_ = pa.schema(snake_case ) if fields else None with ArrowWriter(stream=snake_case , schema=snake_case , writer_batch_size=snake_case ) as writer: writer.write_row(pa.Table.from_pydict({"col_1": ["foo"], "col_2": [1]} ) ) writer.write_row(pa.Table.from_pydict({"col_1": ["bar"], "col_2": [2]} ) ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case_ = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(snake_case , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def UpperCamelCase_( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = {"col_1": pa.string(), "col_2": pa.intaa()} snake_case_ = os.path.join(snake_case , "test.arrow" ) with ArrowWriter(path=snake_case , schema=pa.schema(snake_case ) ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(snake_case , metadata=writer._schema.metadata ) _check_output(snake_case , 1 ) def UpperCamelCase_( snake_case : Tuple ): '''simple docstring''' if pa.types.is_list(snake_case ): return get_base_dtype(arr_type.value_type ) else: return arr_type def UpperCamelCase_( snake_case : Tuple , snake_case : Dict ): '''simple docstring''' if isinstance(lst[0] , snake_case ): change_first_primitive_element_in_list(lst[0] , snake_case ) else: snake_case_ = value @pytest.mark.parametrize("optimized_int_type, expected_dtype" , [(None, pa.intaa()), (Value("int32" ), pa.intaa())] ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def UpperCamelCase_( snake_case : List[Any] , snake_case : Dict , snake_case : int ): '''simple docstring''' snake_case_ = pa.array(TypedSequence(snake_case , optimized_int_type=snake_case ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( "col, expected_dtype" , [ ("attention_mask", pa.inta()), ("special_tokens_mask", pa.inta()), ("token_type_ids", pa.inta()), ("input_ids", pa.intaa()), ("other", pa.intaa()), ] , ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def UpperCamelCase_( snake_case : Optional[int] , snake_case : Any , snake_case : Dict ): '''simple docstring''' snake_case_ = pa.array(OptimizedTypedSequence(snake_case , col=snake_case ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications snake_case_ = copy.deepcopy(snake_case ) snake_case_ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(snake_case , snake_case ) snake_case_ = pa.array(OptimizedTypedSequence(snake_case , col=snake_case ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("raise_exception" , [False, True] ) def UpperCamelCase_( snake_case : List[str] , snake_case : Union[str, Any] ): '''simple docstring''' snake_case_ = str(tmp_path / "dataset-train.arrow" ) try: with ArrowWriter(path=snake_case ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def UpperCamelCase_( snake_case : Union[str, Any] ): '''simple docstring''' snake_case_ = "mock://dataset-train.arrow" with ArrowWriter(path=snake_case , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(snake_case ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(snake_case ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = pa.BufferOutputStream() with ParquetWriter(stream=snake_case ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) snake_case_ , snake_case_ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 snake_case_ = pa.BufferReader(output.getvalue() ) snake_case_ = pq.read_table(snake_case ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("embed_local_files" , [False, True] ) def UpperCamelCase_( snake_case : Optional[int] , snake_case : List[str] ): '''simple docstring''' import PIL.Image snake_case_ = str(tmp_path / "test_image_rgb.jpg" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(snake_case , format="png" ) snake_case_ = pa.BufferOutputStream() with ParquetWriter( stream=snake_case , features=Features({"image": Image()} ) , embed_local_files=snake_case ) as writer: writer.write({"image": image_path} ) writer.finalize() snake_case_ = pa.BufferReader(output.getvalue() ) snake_case_ = pq.read_table(snake_case ) snake_case_ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["image"][0]["path"] , snake_case ) with open(snake_case , "rb" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def UpperCamelCase_( ): '''simple docstring''' snake_case_ = pa.schema([pa.field("col_1" , pa.string() , nullable=snake_case )] ) snake_case_ = pa.BufferOutputStream() with ArrowWriter(stream=snake_case ) as writer: writer._build_writer(inferred_schema=snake_case ) assert writer._schema == pa.schema([pa.field("col_1" , pa.string() )] )
85
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def UpperCamelCase_( snake_case : Any ): '''simple docstring''' if ( (cp >= 0X4E00 and cp <= 0X9FFF) or (cp >= 0X3400 and cp <= 0X4DBF) # or (cp >= 0X2_0000 and cp <= 0X2_A6DF) # or (cp >= 0X2_A700 and cp <= 0X2_B73F) # or (cp >= 0X2_B740 and cp <= 0X2_B81F) # or (cp >= 0X2_B820 and cp <= 0X2_CEAF) # or (cp >= 0XF900 and cp <= 0XFAFF) or (cp >= 0X2_F800 and cp <= 0X2_FA1F) # ): # return True return False def UpperCamelCase_( snake_case : str ): '''simple docstring''' for char in word: snake_case_ = ord(snake_case ) if not _is_chinese_char(snake_case ): return 0 return 1 def UpperCamelCase_( snake_case : List[str] ): '''simple docstring''' snake_case_ = set() for token in tokens: snake_case_ = len(snake_case ) > 1 and is_chinese(snake_case ) if chinese_word: word_set.add(snake_case ) snake_case_ = list(snake_case ) return word_list def UpperCamelCase_( snake_case : List[str] , snake_case : set() ): '''simple docstring''' if not chinese_word_set: return bert_tokens snake_case_ = max([len(snake_case ) for w in chinese_word_set] ) snake_case_ = bert_tokens snake_case_ , snake_case_ = 0, len(snake_case ) while start < end: snake_case_ = True if is_chinese(bert_word[start] ): snake_case_ = min(end - start , snake_case ) for i in range(snake_case , 1 , -1 ): snake_case_ = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): snake_case_ = "##" + bert_word[j] snake_case_ = start + i snake_case_ = False break if single_word: start += 1 return bert_word def UpperCamelCase_( snake_case : List[str] , snake_case : LTP , snake_case : BertTokenizer ): '''simple docstring''' snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = ltp_tokenizer.pipeline(lines[i : i + 1_0_0] , tasks=["cws"] ).cws snake_case_ = [get_chinese_word(snake_case ) for r in res] ltp_res.extend(snake_case ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for i in range(0 , len(snake_case ) , 1_0_0 ): snake_case_ = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=snake_case , truncation=snake_case , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(snake_case ) == len(snake_case ) snake_case_ = [] for input_ids, chinese_word in zip(snake_case , snake_case ): snake_case_ = [] for id in input_ids: snake_case_ = bert_tokenizer._convert_id_to_token(snake_case ) input_tokens.append(snake_case ) snake_case_ = add_sub_symbol(snake_case , snake_case ) snake_case_ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(snake_case ): if token[:2] == "##": snake_case_ = token[2:] # save chinese tokens' pos if len(snake_case ) == 1 and _is_chinese_char(ord(snake_case ) ): ref_id.append(snake_case ) ref_ids.append(snake_case ) assert len(snake_case ) == len(snake_case ) return ref_ids def UpperCamelCase_( snake_case : Any ): '''simple docstring''' with open(args.file_name , "r" , encoding="utf-8" ) as f: snake_case_ = f.readlines() snake_case_ = [line.strip() for line in data if len(snake_case ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' snake_case_ = LTP(args.ltp ) # faster in GPU device snake_case_ = BertTokenizer.from_pretrained(args.bert ) snake_case_ = prepare_ref(snake_case , snake_case , snake_case ) with open(args.save_path , "w" , encoding="utf-8" ) as f: snake_case_ = [json.dumps(snake_case ) + "\n" for ref in ref_ids] f.writelines(snake_case ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", required=False, type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", required=False, type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path", ) parser.add_argument( "--bert", required=False, type=str, default="./resources/robert", help="resources for Bert tokenizer", ) parser.add_argument( "--save_path", required=False, type=str, default="./resources/ref.txt", help="path to save res", ) _SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() main(args)
85
1
'''simple docstring''' import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version _SCREAMING_SNAKE_CASE : Union[str, Any] = logging.getLogger(__name__) require_version("pytorch_lightning>=1.0.4") _SCREAMING_SNAKE_CASE : List[str] = { "base": AutoModel, "sequence-classification": AutoModelForSequenceClassification, "question-answering": AutoModelForQuestionAnswering, "pretraining": AutoModelForPreTraining, "token-classification": AutoModelForTokenClassification, "language-modeling": AutoModelWithLMHead, "summarization": AutoModelForSeqaSeqLM, "translation": AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization _SCREAMING_SNAKE_CASE : Union[str, Any] = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } _SCREAMING_SNAKE_CASE : Any = sorted(arg_to_scheduler.keys()) _SCREAMING_SNAKE_CASE : List[str] = "{" + ", ".join(arg_to_scheduler_choices) + "}" class _snake_case ( pl.LightningModule ): def __init__( self , a__ , a__=None , a__="base" , a__=None , a__=None , a__=None , **a__ , ) -> Optional[Any]: '''simple docstring''' super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(a__ ) snake_case_ = 0 snake_case_ = Path(self.hparams.output_dir ) snake_case_ = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: snake_case_ = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({"num_labels": num_labels} if num_labels is not None else {}) , cache_dir=a__ , **a__ , ) else: snake_case_ = config snake_case_ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(self.hparams , a__ , a__ ): assert hasattr(self.config , a__ ), F'model config doesn\'t have a `{p}` attribute' setattr(self.config , a__ , getattr(self.hparams , a__ ) ) if tokenizer is None: snake_case_ = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=a__ , ) else: snake_case_ = tokenizer snake_case_ = MODEL_MODES[mode] if model is None: snake_case_ = self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool(".ckpt" in self.hparams.model_name_or_path ) , config=self.config , cache_dir=a__ , ) else: snake_case_ = model def lowerCAmelCase__ ( self , *a__ , **a__ ) -> Any: '''simple docstring''' snake_case_ = self.model_type.from_pretrained(*a__ , **a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = arg_to_scheduler[self.hparams.lr_scheduler] snake_case_ = get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) snake_case_ = {"scheduler": scheduler, "interval": "step", "frequency": 1} return scheduler def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.model snake_case_ = ["bias", "LayerNorm.weight"] snake_case_ = [ { "params": [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters "weight_decay": self.hparams.weight_decay, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], "weight_decay": 0.0, }, ] if self.hparams.adafactor: snake_case_ = Adafactor( a__ , lr=self.hparams.learning_rate , scale_parameter=a__ , relative_step=a__ ) else: snake_case_ = AdamW( a__ , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) snake_case_ = optimizer snake_case_ = self.get_lr_scheduler() return [optimizer], [scheduler] def lowerCAmelCase__ ( self , a__ , a__ ) -> Dict: '''simple docstring''' return self.validation_step(a__ , a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' return self.validation_end(a__ ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores snake_case_ = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' if stage == "test": snake_case_ = len(self.test_dataloader().dataset ) else: snake_case_ = self.get_dataloader("train" , self.hparams.train_batch_size , shuffle=a__ ) snake_case_ = len(self.train_dataloader().dataset ) def lowerCAmelCase__ ( self , a__ , a__ , a__ = False ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError("You must implement this for your task" ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' return self.train_loader def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return self.get_dataloader("dev" , self.hparams.eval_batch_size , shuffle=a__ ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' return self.get_dataloader("test" , self.hparams.eval_batch_size , shuffle=a__ ) def lowerCAmelCase__ ( self , a__ ) -> List[Any]: '''simple docstring''' return os.path.join( self.hparams.data_dir , "cached_{}_{}_{}".format( a__ , list(filter(a__ , self.hparams.model_name_or_path.split("/" ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def lowerCAmelCase__ ( self , a__ ) -> None: '''simple docstring''' snake_case_ = self.output_dir.joinpath("best_tfmr" ) snake_case_ = self.step_count self.model.save_pretrained(a__ ) self.tokenizer.save_pretrained(a__ ) @staticmethod def lowerCAmelCase__ ( a__ , a__ ) -> List[Any]: '''simple docstring''' parser.add_argument( "--model_name_or_path" , default=a__ , type=a__ , required=a__ , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--config_name" , default="" , type=a__ , help="Pretrained config name or path if not the same as model_name" ) parser.add_argument( "--tokenizer_name" , default=a__ , type=a__ , help="Pretrained tokenizer name or path if not the same as model_name" , ) parser.add_argument( "--cache_dir" , default=str(Path(a__ ).parent / "test_run" / "cache" ) , type=a__ , help="Where do you want to store the pre-trained models downloaded from huggingface.co" , ) parser.add_argument( "--encoder_layerdrop" , type=a__ , help="Encoder layer dropout probability (Optional). Goes into model.config" , ) parser.add_argument( "--decoder_layerdrop" , type=a__ , help="Decoder layer dropout probability (Optional). Goes into model.config" , ) parser.add_argument( "--dropout" , type=a__ , help="Dropout probability (Optional). Goes into model.config" , ) parser.add_argument( "--attention_dropout" , type=a__ , help="Attention dropout probability (Optional). Goes into model.config" , ) parser.add_argument("--learning_rate" , default=5e-5 , type=a__ , help="The initial learning rate for Adam." ) parser.add_argument( "--lr_scheduler" , default="linear" , choices=a__ , metavar=a__ , type=a__ , help="Learning rate scheduler" , ) parser.add_argument("--weight_decay" , default=0.0 , type=a__ , help="Weight decay if we apply some." ) parser.add_argument("--adam_epsilon" , default=1e-8 , type=a__ , help="Epsilon for Adam optimizer." ) parser.add_argument("--warmup_steps" , default=0 , type=a__ , help="Linear warmup over warmup_steps." ) parser.add_argument("--num_workers" , default=4 , type=a__ , help="kwarg passed to DataLoader" ) parser.add_argument("--num_train_epochs" , dest="max_epochs" , default=3 , type=a__ ) parser.add_argument("--train_batch_size" , default=32 , type=a__ ) parser.add_argument("--eval_batch_size" , default=32 , type=a__ ) parser.add_argument("--adafactor" , action="store_true" ) class _snake_case ( pl.Callback ): def lowerCAmelCase__ ( self , a__ , a__ ) -> str: '''simple docstring''' if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class _snake_case ( pl.Callback ): def lowerCAmelCase__ ( self , a__ , a__ ) -> Any: '''simple docstring''' for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(a__ ) class _snake_case ( pl.Callback ): def lowerCAmelCase__ ( self , a__ , a__ ) -> List[str]: '''simple docstring''' snake_case_ = trainer.lr_schedulers[0]["scheduler"] snake_case_ = {F'lr_group_{i}': lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> List[str]: '''simple docstring''' rank_zero_info("***** Validation results *****" ) snake_case_ = trainer.callback_metrics # Log results for key in sorted(a__ ): if key not in ["log", "progress_bar"]: rank_zero_info("{} = {}\n".format(a__ , str(metrics[key] ) ) ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[int]: '''simple docstring''' rank_zero_info("***** Test results *****" ) snake_case_ = trainer.callback_metrics # Log and save results to file snake_case_ = os.path.join(pl_module.hparams.output_dir , "test_results.txt" ) with open(a__ , "w" ) as writer: for key in sorted(a__ ): if key not in ["log", "progress_bar"]: rank_zero_info("{} = {}\n".format(a__ , str(metrics[key] ) ) ) writer.write("{} = {}\n".format(a__ , str(metrics[key] ) ) ) def UpperCamelCase_( snake_case : List[Any] , snake_case : Optional[Any] ): '''simple docstring''' parser.add_argument( "--output_dir" , default=str(Path(snake_case ).parent / "test_run" / "model_checkpoints" ) , type=snake_case , help="The output directory where the model predictions and checkpoints will be written." , ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=snake_case , default="O2" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_tpu_cores" , dest="tpu_cores" , type=snake_case ) parser.add_argument("--max_grad_norm" , dest="gradient_clip_val" , default=1.0 , type=snake_case , help="Max gradient norm" ) parser.add_argument("--do_train" , action="store_true" , help="Whether to run training." ) parser.add_argument("--do_predict" , action="store_true" , help="Whether to run predictions on the test set." ) parser.add_argument( "--gradient_accumulation_steps" , dest="accumulate_grad_batches" , type=snake_case , default=1 , help="Number of updates steps to accumulate before performing a backward/update pass." , ) parser.add_argument("--seed" , type=snake_case , default=4_2 , help="random seed for initialization" ) parser.add_argument( "--data_dir" , default=str(Path(snake_case ).parent / "test_run" / "dummy-train-data" ) , type=snake_case , help="The input data dir. Should contain the training files for the CoNLL-2003 NER task." , ) def UpperCamelCase_( snake_case : BaseTransformer , snake_case : argparse.Namespace , snake_case : Optional[int]=None , snake_case : int=True , snake_case : List[str]=[] , snake_case : int=None , snake_case : Any=None , **snake_case : Dict , ): '''simple docstring''' pl.seed_everything(args.seed ) # init model snake_case_ = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=snake_case ) # add custom checkpoints if checkpoint_callback is None: snake_case_ = pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix="checkpoint" , monitor="val_loss" , mode="min" , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(snake_case ) if logging_callback is None: snake_case_ = LoggingCallback() snake_case_ = {} if args.fpaa: snake_case_ = 1_6 if args.gpus > 1: snake_case_ = "auto" snake_case_ = "ddp" snake_case_ = args.accumulate_grad_batches snake_case_ = None snake_case_ = "auto" snake_case_ = pl.Trainer.from_argparse_args( snake_case , weights_summary=snake_case , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=snake_case , val_check_interval=1 , num_sanity_val_steps=2 , **snake_case , ) if args.do_train: trainer.fit(snake_case ) else: print("RAG modeling tests with new set functions successfuly executed!" ) return trainer
85
'''simple docstring''' import warnings from functools import wraps from typing import Callable def UpperCamelCase_( snake_case : Callable ): '''simple docstring''' @wraps(snake_case ) def _inner_fn(*snake_case : Optional[int] , **snake_case : List[Any] ): warnings.warn( (f'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , snake_case , ) return fn(*snake_case , **snake_case ) return _inner_fn
85
1
'''simple docstring''' import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _snake_case ( lowercase_ , unittest.TestCase ): lowerCAmelCase_ : List[str] = LongformerTokenizer lowerCAmelCase_ : Optional[Any] = True lowerCAmelCase_ : List[str] = LongformerTokenizerFast lowerCAmelCase_ : Any = True def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case_ = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] snake_case_ = dict(zip(a__ , range(len(a__ ) ) ) ) snake_case_ = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] snake_case_ = {"unk_token": "<unk>"} snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) snake_case_ = 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 lowerCAmelCase__ ( self , **a__ ) -> List[Any]: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **a__ ) def lowerCAmelCase__ ( self , **a__ ) -> Union[str, Any]: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **a__ ) def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ = "lower newer" snake_case_ = "lower newer" return input_text, output_text def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case_ = "lower newer" snake_case_ = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"] snake_case_ = tokenizer.tokenize(a__ ) # , add_prefix_space=True) self.assertListEqual(a__ , a__ ) snake_case_ = tokens + [tokenizer.unk_token] snake_case_ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("Hello world!" , add_special_tokens=a__ ) , [0, 31_414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode("Hello world! cécé herlolip 418" , add_special_tokens=a__ ) , [0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2] , ) @slow def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.tokenizer_class.from_pretrained("allenai/longformer-base-4096" ) snake_case_ = tokenizer.encode("sequence builders" , add_special_tokens=a__ ) snake_case_ = tokenizer.encode("multi-sequence build" , add_special_tokens=a__ ) snake_case_ = tokenizer.encode( "sequence builders" , add_special_tokens=a__ , add_prefix_space=a__ ) snake_case_ = tokenizer.encode( "sequence builders" , "multi-sequence build" , add_special_tokens=a__ , add_prefix_space=a__ ) snake_case_ = tokenizer.build_inputs_with_special_tokens(a__ ) snake_case_ = tokenizer.build_inputs_with_special_tokens(a__ , a__ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.get_tokenizer() snake_case_ = "Encode this sequence." snake_case_ = tokenizer.byte_encoder[" ".encode("utf-8" )[0]] # Testing encoder arguments snake_case_ = tokenizer.encode(a__ , add_special_tokens=a__ , add_prefix_space=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(a__ , a__ ) snake_case_ = tokenizer.encode(a__ , add_special_tokens=a__ , add_prefix_space=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(a__ , a__ ) tokenizer.add_special_tokens({"bos_token": "<s>"} ) snake_case_ = tokenizer.encode(a__ , add_special_tokens=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(a__ , a__ ) # Testing spaces after special tokens snake_case_ = "<mask>" tokenizer.add_special_tokens( {"mask_token": AddedToken(a__ , lstrip=a__ , rstrip=a__ )} ) # mask token has a left space snake_case_ = tokenizer.convert_tokens_to_ids(a__ ) snake_case_ = "Encode <mask> sequence" snake_case_ = "Encode <mask>sequence" snake_case_ = tokenizer.encode(a__ ) snake_case_ = encoded.index(a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(a__ , a__ ) snake_case_ = tokenizer.encode(a__ ) snake_case_ = encoded.index(a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): snake_case_ = self.rust_tokenizer_class.from_pretrained(a__ , **a__ ) snake_case_ = self.tokenizer_class.from_pretrained(a__ , **a__ ) snake_case_ = "A, <mask> AllenNLP sentence." snake_case_ = tokenizer_r.encode_plus(a__ , add_special_tokens=a__ , return_token_type_ids=a__ ) snake_case_ = tokenizer_p.encode_plus(a__ , add_special_tokens=a__ , return_token_type_ids=a__ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["token_type_ids"] ) , sum(tokens_p["token_type_ids"] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) , sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) , ) snake_case_ = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] ) snake_case_ = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["input_ids"] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual(tokens_r["input_ids"] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual( a__ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) self.assertSequenceEqual( a__ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): snake_case_ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=a__ , add_prefix_space=a__ , trim_offsets=a__ ) snake_case_ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) snake_case_ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["add_prefix_space"] , a__ ) self.assertEqual(post_processor_state["add_prefix_space"] , a__ ) self.assertEqual(post_processor_state["trim_offsets"] , a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): snake_case_ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` snake_case_ = F'{text_of_1_token} {text_of_1_token}' snake_case_ = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , add_prefix_space=a__ , trim_offsets=a__ ) snake_case_ = 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__ )) , ) snake_case_ = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , add_prefix_space=a__ , trim_offsets=a__ ) snake_case_ = 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__ )) , ) snake_case_ = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , add_prefix_space=a__ , trim_offsets=a__ ) snake_case_ = 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__ ), len(a__ ) + 1 + len(a__ )) , ) snake_case_ = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , add_prefix_space=a__ , trim_offsets=a__ ) snake_case_ = 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__ ), len(a__ ) + 1 + len(a__ )) , ) snake_case_ = F' {text}' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) snake_case_ = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , add_prefix_space=a__ , trim_offsets=a__ ) snake_case_ = 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__ )) , ) snake_case_ = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , add_prefix_space=a__ , trim_offsets=a__ ) snake_case_ = tokenizer_r(a__ , return_offsets_mapping=a__ , add_special_tokens=a__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(a__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a__ ), 1 + len(a__ ) + 1 + len(a__ )) , ) snake_case_ = self.rust_tokenizer_class.from_pretrained( a__ , use_fast=a__ , add_prefix_space=a__ , trim_offsets=a__ ) snake_case_ = tokenizer_r(a__ , return_offsets_mapping=a__ , add_special_tokens=a__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(a__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a__ ), 1 + len(a__ ) + 1 + len(a__ )) , )
85
'''simple docstring''' from __future__ import annotations import requests def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty' return requests.get(snake_case ).json() def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' snake_case_ = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" snake_case_ = requests.get(snake_case ).json()[:max_stories] return [get_hackernews_story(snake_case ) for story_id in story_ids] def UpperCamelCase_( snake_case : int = 1_0 ): '''simple docstring''' snake_case_ = hackernews_top_stories(snake_case ) return "\n".join("* [{title}]({url})".format(**snake_case ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : list[list[int | float]] ): '''simple docstring''' snake_case_ = len(snake_case ) snake_case_ = len(matrix[0] ) snake_case_ = min(snake_case , snake_case ) for row in range(snake_case ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , snake_case ): snake_case_ = matrix[col][row] / matrix[row][row] for i in range(snake_case , snake_case ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows snake_case_ = True for i in range(row + 1 , snake_case ): if matrix[i][row] != 0: snake_case_ , snake_case_ = matrix[i], matrix[row] snake_case_ = False break if reduce: rank -= 1 for i in range(snake_case ): snake_case_ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : Optional[Any] = MODEL_FOR_CAUSAL_LM_MAPPING lowerCAmelCase_ : Optional[Any] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="pt" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ], [ { "generated_text": ( "This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy" " oscope. oscope. FiliFili@@" ) } ], ] , ) snake_case_ = text_generator("This is a test" , do_sample=a__ , num_return_sequences=2 , return_tensors=a__ ) self.assertEqual( a__ , [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ] , ) snake_case_ = text_generator.model.config.eos_token_id snake_case_ = "<pad>" snake_case_ = text_generator( ["This is a test", "This is a second test"] , do_sample=a__ , num_return_sequences=2 , batch_size=2 , return_tensors=a__ , ) self.assertEqual( a__ , [ [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], ] , ) @require_tf def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="tf" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] , do_sample=a__ ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ], [ { "generated_text": ( "This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes" " Cannes 閲閲Cannes Cannes Cannes 攵 please," ) } ], ] , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> str: '''simple docstring''' snake_case_ = TextGenerationPipeline(model=a__ , tokenizer=a__ ) return text_generator, ["This is a test", "Another test"] def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "Hello I believe in" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) snake_case_ = text_generator(a__ ) self.assertEqual( a__ , [{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}] , ) snake_case_ = text_generator(a__ , stop_sequence=" fe" ) self.assertEqual(a__ , [{"generated_text": "Hello I believe in fe"}] ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Tuple: '''simple docstring''' snake_case_ = text_generator.model snake_case_ = text_generator.tokenizer snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = pipeline(task="text-generation" , model=a__ , tokenizer=a__ , return_full_text=a__ ) snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) if text_generator.tokenizer.pad_token is not None: snake_case_ = text_generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_text=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_tensors=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_text=a__ , return_tensors=a__ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): snake_case_ = text_generator("" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): snake_case_ = text_generator("" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. snake_case_ = ["RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM"] if ( tokenizer.model_max_length < 10_000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("This is a test" * 500 , max_new_tokens=20 ) snake_case_ = text_generator("This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(a__ ): text_generator( "This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' import torch # Classic `model_kwargs` snake_case_ = pipeline( model="hf-internal-testing/tiny-random-bloom" , model_kwargs={"device_map": "auto", "torch_dtype": torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) @require_torch @require_torch_gpu def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device=0 , torch_dtype=torch.floataa ) pipe("This is a test" ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.floataa ) pipe("This is a test" , do_sample=a__ , top_p=0.5 ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "Hello world" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) if text_generator.model.framework == "tf": snake_case_ = logging.get_logger("transformers.generation.tf_utils" ) else: snake_case_ = logging.get_logger("transformers.generation.utils" ) snake_case_ = "Both `max_new_tokens`" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 , max_new_tokens=1 ) self.assertIn(a__ , cl.out ) # The user only sets one -> no warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_new_tokens=1 ) self.assertNotIn(a__ , cl.out ) with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 ) self.assertNotIn(a__ , cl.out )
85
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : str = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
85
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , lowercase_ ): def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = load_tool("text-classification" ) self.tool.setup() snake_case_ = load_tool("text-classification" , remote=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a__ , "positive" )
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : int = 5_0 ): '''simple docstring''' snake_case_ = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(F"{solution() = }")
85
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Dict = { "BridgeTower/bridgetower-base": "https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json", "BridgeTower/bridgetower-base-itm-mlm": ( "https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json" ), } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Dict = "bridgetower_vision_model" def __init__( self , a__=768 , a__=12 , a__=3 , a__=16 , a__=288 , a__=1 , a__=1e-05 , a__=False , a__=True , a__=False , **a__ , ) -> int: '''simple docstring''' super().__init__(**a__ ) snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_channels snake_case_ = patch_size snake_case_ = image_size snake_case_ = initializer_factor snake_case_ = layer_norm_eps snake_case_ = stop_gradient snake_case_ = share_layernorm snake_case_ = remove_last_layer @classmethod def lowerCAmelCase__ ( cls , a__ , **a__ ) -> "PretrainedConfig": '''simple docstring''' snake_case_ , snake_case_ = cls.get_config_dict(a__ , **a__ ) if config_dict.get("model_type" ) == "bridgetower": snake_case_ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a__ , **a__ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "bridgetower_text_model" def __init__( self , a__=50_265 , a__=768 , a__=12 , a__=12 , a__=1 , a__=3_072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=514 , a__=1 , a__=1e-05 , a__=1 , a__=0 , a__=2 , a__="absolute" , a__=True , **a__ , ) -> Optional[int]: '''simple docstring''' super().__init__(**a__ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = initializer_factor snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = layer_norm_eps snake_case_ = position_embedding_type snake_case_ = use_cache snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id @classmethod def lowerCAmelCase__ ( cls , a__ , **a__ ) -> "PretrainedConfig": '''simple docstring''' snake_case_ , snake_case_ = cls.get_config_dict(a__ , **a__ ) if config_dict.get("model_type" ) == "bridgetower": snake_case_ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(a__ , **a__ ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Union[str, Any] = "bridgetower" def __init__( self , a__=True , a__="gelu" , a__=768 , a__=1 , a__=1e-05 , a__=False , a__="add" , a__=12 , a__=6 , a__=False , a__=False , a__=None , a__=None , **a__ , ) -> int: '''simple docstring''' snake_case_ = kwargs.pop("text_config_dict" , a__ ) snake_case_ = kwargs.pop("vision_config_dict" , a__ ) super().__init__(**a__ ) snake_case_ = share_cross_modal_transformer_layers snake_case_ = hidden_act snake_case_ = hidden_size snake_case_ = initializer_factor snake_case_ = layer_norm_eps snake_case_ = share_link_tower_layers snake_case_ = link_tower_type snake_case_ = num_attention_heads snake_case_ = num_hidden_layers snake_case_ = tie_word_embeddings snake_case_ = init_layernorm_from_vision_encoder if text_config is None: snake_case_ = {} logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values." ) if vision_config is None: snake_case_ = {} logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values." ) snake_case_ = BridgeTowerTextConfig(**a__ ) snake_case_ = BridgeTowerVisionConfig(**a__ ) @classmethod def lowerCAmelCase__ ( cls , a__ , a__ , **a__ ) -> List[Any]: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.text_config.to_dict() snake_case_ = self.vision_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1
'''simple docstring''' def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = len(snake_case ) while cur > 1: # Find the maximum number in arr snake_case_ = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi snake_case_ = arr[mi::-1] + arr[mi + 1 : len(snake_case )] # Reverse whole list snake_case_ = arr[cur - 1 :: -1] + arr[cur : len(snake_case )] cur -= 1 return arr if __name__ == "__main__": _SCREAMING_SNAKE_CASE : str = input("Enter numbers separated by a comma:\n").strip() _SCREAMING_SNAKE_CASE : int = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
85
'''simple docstring''' from __future__ import annotations def UpperCamelCase_( snake_case : list[int] ): '''simple docstring''' return len(set(snake_case ) ) == len(snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
85
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class _snake_case ( unittest.TestCase ): lowerCAmelCase_ : Optional[Any] = MODEL_FOR_CAUSAL_LM_MAPPING lowerCAmelCase_ : Optional[Any] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="pt" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ], [ { "generated_text": ( "This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy" " oscope. oscope. FiliFili@@" ) } ], ] , ) snake_case_ = text_generator("This is a test" , do_sample=a__ , num_return_sequences=2 , return_tensors=a__ ) self.assertEqual( a__ , [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ] , ) snake_case_ = text_generator.model.config.eos_token_id snake_case_ = "<pad>" snake_case_ = text_generator( ["This is a test", "This is a second test"] , do_sample=a__ , num_return_sequences=2 , batch_size=2 , return_tensors=a__ , ) self.assertEqual( a__ , [ [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], [ {"generated_token_ids": ANY(a__ )}, {"generated_token_ids": ANY(a__ )}, ], ] , ) @require_tf def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="tf" ) # Using `do_sample=False` to force deterministic output snake_case_ = text_generator("This is a test" , do_sample=a__ ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ] , ) snake_case_ = text_generator(["This is a test", "This is a second test"] , do_sample=a__ ) self.assertEqual( a__ , [ [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ], [ { "generated_text": ( "This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes" " Cannes 閲閲Cannes Cannes Cannes 攵 please," ) } ], ] , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> str: '''simple docstring''' snake_case_ = TextGenerationPipeline(model=a__ , tokenizer=a__ ) return text_generator, ["This is a test", "Another test"] def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "Hello I believe in" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) snake_case_ = text_generator(a__ ) self.assertEqual( a__ , [{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}] , ) snake_case_ = text_generator(a__ , stop_sequence=" fe" ) self.assertEqual(a__ , [{"generated_text": "Hello I believe in fe"}] ) def lowerCAmelCase__ ( self , a__ , a__ ) -> Tuple: '''simple docstring''' snake_case_ = text_generator.model snake_case_ = text_generator.tokenizer snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = pipeline(task="text-generation" , model=a__ , tokenizer=a__ , return_full_text=a__ ) snake_case_ = text_generator("This is a test" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) snake_case_ = text_generator("This is a test" , return_full_text=a__ ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) snake_case_ = text_generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) if text_generator.tokenizer.pad_token is not None: snake_case_ = text_generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=a__ ) self.assertEqual( a__ , [ [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], [{"generated_text": ANY(a__ )}, {"generated_text": ANY(a__ )}], ] , ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_text=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_full_text=a__ , return_tensors=a__ ) with self.assertRaises(a__ ): snake_case_ = text_generator("test" , return_text=a__ , return_tensors=a__ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): snake_case_ = text_generator("" ) self.assertEqual(a__ , [{"generated_text": ANY(a__ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): snake_case_ = text_generator("" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. snake_case_ = ["RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM"] if ( tokenizer.model_max_length < 10_000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("This is a test" * 500 , max_new_tokens=20 ) snake_case_ = text_generator("This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(a__ ): text_generator( "This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' import torch # Classic `model_kwargs` snake_case_ = pipeline( model="hf-internal-testing/tiny-random-bloom" , model_kwargs={"device_map": "auto", "torch_dtype": torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) snake_case_ = pipe("This is a test" ) self.assertEqual( a__ , [ { "generated_text": ( "This is a test test test test test test test test test test test test test test test test" " test" ) } ] , ) @require_torch @require_torch_gpu def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device=0 , torch_dtype=torch.floataa ) pipe("This is a test" ) @require_torch @require_accelerate @require_torch_gpu def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' import torch snake_case_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.floataa ) pipe("This is a test" , do_sample=a__ , top_p=0.5 ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = "Hello world" snake_case_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) if text_generator.model.framework == "tf": snake_case_ = logging.get_logger("transformers.generation.tf_utils" ) else: snake_case_ = logging.get_logger("transformers.generation.utils" ) snake_case_ = "Both `max_new_tokens`" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 , max_new_tokens=1 ) self.assertIn(a__ , cl.out ) # The user only sets one -> no warning with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_new_tokens=1 ) self.assertNotIn(a__ , cl.out ) with CaptureLogger(a__ ) as cl: snake_case_ = text_generator(a__ , max_length=10 ) self.assertNotIn(a__ , cl.out )
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = False try: _SCREAMING_SNAKE_CASE : Optional[Any] = _is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class _snake_case : def __init__( self , a__ = None , a__ = [] ) -> List[str]: '''simple docstring''' snake_case_ = 0 snake_case_ = choices snake_case_ = prompt if sys.platform == "win32": snake_case_ = "*" else: snake_case_ = "➔ " def lowerCAmelCase__ ( self , a__ , a__ = "" ) -> int: '''simple docstring''' if sys.platform != "win32": writeColor(self.choices[index] , 32 , a__ ) else: forceWrite(self.choices[index] , a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a__ ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def lowerCAmelCase__ ( self , a__ , a__ = 1 ) -> List[str]: '''simple docstring''' snake_case_ = 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 lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a__ )] for number in range(10 )] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = int(chr(self.current_selection ) ) snake_case_ = 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 lowerCAmelCase__ ( self , a__ = 0 ) -> List[str]: '''simple docstring''' 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" ) snake_case_ = 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: snake_case_ = int(builtins.input() ) except ValueError: snake_case_ = default_choice else: snake_case_ = 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
85
1
'''simple docstring''' import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class _snake_case : def __init__( self , a__ , a__=13 , a__=2 , a__=24 , a__=16 , a__=True , a__=True , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.0_2 , a__=None , a__=2 , a__=2 , ) -> str: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = patch_size snake_case_ = max_length snake_case_ = num_mel_bins snake_case_ = is_training snake_case_ = use_labels snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = scope snake_case_ = frequency_stride snake_case_ = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) snake_case_ = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 snake_case_ = (self.max_length - self.patch_size) // self.time_stride + 1 snake_case_ = frequency_out_dimension * time_out_dimension snake_case_ = num_patches + 2 def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = self.get_config() return config, input_values, labels def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = ASTModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = {"input_values": input_values} return config, inputs_dict @require_torch class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : List[str] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) lowerCAmelCase_ : Any = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Tuple = False lowerCAmelCase_ : Optional[Any] = False lowerCAmelCase_ : Any = False def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ ) -> Dict: '''simple docstring''' if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = ASTModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="AST does not use inputs_embeds" ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , nn.Linear ) ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["input_values"] self.assertListEqual(arg_names[:1] , a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) @slow def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ASTModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" ) snake_case_ , snake_case_ = torchaudio.load(snake_case ) return audio, sampling_rate @require_torch @require_torchaudio class _snake_case ( unittest.TestCase ): @cached_property def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' return ( ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ) if is_torchaudio_available() else None ) @slow def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = self.default_feature_extractor snake_case_ = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(a__ ) snake_case_ = self.default_feature_extractor snake_case_ , snake_case_ = prepare_audio() snake_case_ = audio.squeeze().numpy() snake_case_ = feature_extractor(a__ , sampling_rate=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) # verify the logits snake_case_ = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , a__ ) snake_case_ = torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) )
85
'''simple docstring''' import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def UpperCamelCase_( snake_case : Optional[int] ): '''simple docstring''' return EnvironmentCommand() class _snake_case ( lowercase_ ): @staticmethod def lowerCAmelCase__ ( a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = parser.add_parser("env" ) download_parser.set_defaults(func=a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = huggingface_hub.__version__ snake_case_ = "not installed" snake_case_ = "NA" if is_torch_available(): import torch snake_case_ = torch.__version__ snake_case_ = torch.cuda.is_available() snake_case_ = "not installed" if is_transformers_available(): import transformers snake_case_ = transformers.__version__ snake_case_ = "not installed" if is_accelerate_available(): import accelerate snake_case_ = accelerate.__version__ snake_case_ = "not installed" if is_xformers_available(): import xformers snake_case_ = xformers.__version__ snake_case_ = { "`diffusers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "PyTorch version (GPU?)": F'{pt_version} ({pt_cuda_available})', "Huggingface_hub version": hub_version, "Transformers version": transformers_version, "Accelerate version": accelerate_version, "xFormers version": xformers_version, "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(a__ ) ) return info @staticmethod def lowerCAmelCase__ ( a__ ) -> str: '''simple docstring''' return "\n".join([F'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
85
1
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class _snake_case : def __init__( self , a__ , a__=2 , a__=True , a__=False , a__=10 , a__=3 , a__=32 * 4 , a__=32 * 6 , a__=4 , a__=32 , ) -> List[Any]: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = is_training snake_case_ = use_auxiliary_loss snake_case_ = num_queries snake_case_ = num_channels snake_case_ = min_size snake_case_ = max_size snake_case_ = num_labels snake_case_ = mask_feature_size def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( a__ ) snake_case_ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=a__ ) snake_case_ = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=a__ ) > 0.5 ).float() snake_case_ = (torch.rand((self.batch_size, self.num_labels) , device=a__ ) > 0.5).long() snake_case_ = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.prepare_config_and_inputs() snake_case_ = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def lowerCAmelCase__ ( self , a__ , a__ ) -> Optional[Any]: '''simple docstring''' snake_case_ = output.encoder_hidden_states snake_case_ = output.pixel_decoder_hidden_states snake_case_ = output.transformer_decoder_hidden_states self.parent.assertTrue(len(a__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(a__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(a__ ) , config.decoder_config.decoder_layers ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__=False ) -> int: '''simple docstring''' with torch.no_grad(): snake_case_ = MaskFormerModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(pixel_values=a__ , pixel_mask=a__ ) snake_case_ = model(a__ , output_hidden_states=a__ ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(a__ , a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ = MaskFormerForInstanceSegmentation(config=a__ ) model.to(a__ ) model.eval() def comm_check_on_output(a__ ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): snake_case_ = model(pixel_values=a__ , pixel_mask=a__ ) snake_case_ = model(a__ ) comm_check_on_output(a__ ) snake_case_ = model( pixel_values=a__ , pixel_mask=a__ , mask_labels=a__ , class_labels=a__ ) comm_check_on_output(a__ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : str = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCAmelCase_ : Dict = ( {"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCAmelCase_ : Dict = False lowerCAmelCase_ : List[Any] = False lowerCAmelCase_ : Optional[Any] = False lowerCAmelCase_ : List[str] = False def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = MaskFormerModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , has_text_modality=a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(a__ , **a__ , output_hidden_states=a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*a__ ) @unittest.skip(reason="MaskFormer does not use inputs_embeds" ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' pass @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' pass @unittest.skip(reason="MaskFormer is not a generative model" ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' pass @unittest.skip(reason="MaskFormer does not use token embeddings" ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , a__ ) @slow def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' for model_name in ["facebook/maskformer-swin-small-coco"]: snake_case_ = MaskFormerModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = (self.model_tester.min_size,) * 2 snake_case_ = { "pixel_values": torch.randn((2, 3, *size) , device=a__ ), "mask_labels": torch.randn((2, 10, *size) , device=a__ ), "class_labels": torch.zeros(2 , 10 , device=a__ ).long(), } snake_case_ = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(a__ ) snake_case_ = model(**a__ ) self.assertTrue(outputs.loss is not None ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(a__ , **a__ , output_hidden_states=a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ).to(a__ ) snake_case_ = model(**a__ , output_attentions=a__ ) self.assertTrue(outputs.attentions is not None ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss snake_case_ = self.all_model_classes[1] snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() snake_case_ = model_class(a__ ) model.to(a__ ) model.train() snake_case_ = model(a__ , mask_labels=a__ , class_labels=a__ ).loss loss.backward() def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.all_model_classes[1] snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() snake_case_ = True snake_case_ = True snake_case_ = model_class(a__ ) model.to(a__ ) model.train() snake_case_ = model(a__ , mask_labels=a__ , class_labels=a__ ) snake_case_ = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() snake_case_ = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't snake_case_ = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() snake_case_ = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=a__ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _SCREAMING_SNAKE_CASE : int = 1e-4 def UpperCamelCase_( ): '''simple docstring''' snake_case_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class _snake_case ( unittest.TestCase ): @cached_property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" ) if is_vision_available() else None ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(a__ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(a__ , return_tensors="pt" ).to(a__ ) snake_case_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(a__ , (1, 3, 800, 1_088) ) with torch.no_grad(): snake_case_ = model(**a__ ) snake_case_ = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(a__ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , a__ , atol=a__ ) ) snake_case_ = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(a__ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , a__ , atol=a__ ) ) snake_case_ = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(a__ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , a__ , atol=a__ ) ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(a__ ) .eval() ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(a__ , return_tensors="pt" ).to(a__ ) snake_case_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(a__ , (1, 3, 800, 1_088) ) with torch.no_grad(): snake_case_ = model(**a__ ) # masks_queries_logits snake_case_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) snake_case_ = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] snake_case_ = torch.tensor(a__ ).to(a__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , a__ , atol=a__ ) ) # class_queries_logits snake_case_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) snake_case_ = torch.tensor( [ [1.6512e00, -5.2572e00, -3.3519e00], [3.6169e-02, -5.9025e00, -2.9313e00], [1.0766e-04, -7.7630e00, -5.1263e00], ] ).to(a__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , a__ , atol=a__ ) ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" ) .to(a__ ) .eval() ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(a__ , return_tensors="pt" ).to(a__ ) snake_case_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(a__ , (1, 3, 800, 1_088) ) with torch.no_grad(): snake_case_ = model(**a__ ) # masks_queries_logits snake_case_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) snake_case_ = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] snake_case_ = torch.tensor(a__ ).to(a__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , a__ , atol=a__ ) ) # class_queries_logits snake_case_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) snake_case_ = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(a__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , a__ , atol=a__ ) ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(a__ ) .eval() ) snake_case_ = self.default_image_processor snake_case_ = image_processor( [np.zeros((3, 800, 1_333) ), np.zeros((3, 800, 1_333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) snake_case_ = inputs["pixel_values"].to(a__ ) snake_case_ = [el.to(a__ ) for el in inputs["mask_labels"]] snake_case_ = [el.to(a__ ) for el in inputs["class_labels"]] with torch.no_grad(): snake_case_ = model(**a__ ) self.assertTrue(outputs.loss is not None )
85
'''simple docstring''' import os _SCREAMING_SNAKE_CASE : int = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = 0 snake_case_ = 0 while index < len(snake_case ) - 1: snake_case_ = SYMBOLS[numerals[index]] snake_case_ = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = "" snake_case_ = num // 1_0_0_0 numerals += m_count * "M" num %= 1_0_0_0 snake_case_ = num // 1_0_0 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_0_0 snake_case_ = num // 1_0 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 1_0 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def UpperCamelCase_( snake_case : str = "/p089_roman.txt" ): '''simple docstring''' snake_case_ = 0 with open(os.path.dirname(snake_case ) + roman_numerals_filename ) as filea: snake_case_ = filea.readlines() for line in lines: snake_case_ = line.strip() snake_case_ = parse_roman_numerals(snake_case ) snake_case_ = generate_roman_numerals(snake_case ) savings += len(snake_case ) - len(snake_case ) return savings if __name__ == "__main__": print(F"{solution() = }")
85
1
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( "stable diffusion controlnet", "0.22.0", "Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.", standard_warn=False, stacklevel=3, )
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _SCREAMING_SNAKE_CASE : int = { "configuration_clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig", ], "processing_clip": ["CLIPProcessor"], "tokenization_clip": ["CLIPTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = ["CLIPTokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = ["CLIPFeatureExtractor"] _SCREAMING_SNAKE_CASE : Dict = ["CLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _SCREAMING_SNAKE_CASE : List[str] = 2_9979_2458 # Symbols _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = symbols("ct x y z") def UpperCamelCase_( snake_case : float ): '''simple docstring''' if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!" ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("Speed must be greater than or equal to 1!" ) return velocity / c def UpperCamelCase_( snake_case : float ): '''simple docstring''' return 1 / sqrt(1 - beta(snake_case ) ** 2 ) def UpperCamelCase_( snake_case : float ): '''simple docstring''' return np.array( [ [gamma(snake_case ), -gamma(snake_case ) * beta(snake_case ), 0, 0], [-gamma(snake_case ) * beta(snake_case ), gamma(snake_case ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def UpperCamelCase_( snake_case : float , snake_case : np.ndarray | None = None ): '''simple docstring''' if event is None: snake_case_ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(snake_case ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: _SCREAMING_SNAKE_CASE : List[str] = transform(2997_9245) print("Example of four vector: ") print(F"ct' = {four_vector[0]}") print(F"x' = {four_vector[1]}") print(F"y' = {four_vector[2]}") print(F"z' = {four_vector[3]}") # Substitute symbols with numerical values _SCREAMING_SNAKE_CASE : List[Any] = {ct: c, x: 1, y: 1, z: 1} _SCREAMING_SNAKE_CASE : List[Any] = [four_vector[i].subs(sub_dict) for i in range(4)] print(F"\n{numerical_vector}")
85
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE : Union[str, Any] = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } _SCREAMING_SNAKE_CASE : int = { "gpt-neox-20b": 2048, } class _snake_case ( lowercase_ ): lowerCAmelCase_ : str = VOCAB_FILES_NAMES lowerCAmelCase_ : Tuple = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ : str = ["input_ids", "attention_mask"] def __init__( self , a__=None , a__=None , a__=None , a__="<|endoftext|>" , a__="<|endoftext|>" , a__="<|endoftext|>" , a__=False , **a__ , ) -> Tuple: '''simple docstring''' super().__init__( a__ , a__ , tokenizer_file=a__ , unk_token=a__ , bos_token=a__ , eos_token=a__ , add_prefix_space=a__ , **a__ , ) snake_case_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , a__ ) != add_prefix_space: snake_case_ = getattr(a__ , pre_tok_state.pop("type" ) ) snake_case_ = add_prefix_space snake_case_ = pre_tok_class(**a__ ) snake_case_ = add_prefix_space def lowerCAmelCase__ ( self , a__ , a__ = None ) -> Tuple[str]: '''simple docstring''' snake_case_ = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ ) def lowerCAmelCase__ ( self , a__ ) -> List[int]: '''simple docstring''' snake_case_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(a__ , add_special_tokens=a__ ) + [self.eos_token_id] ) if len(a__ ) > self.model_max_length: snake_case_ = input_ids[-self.model_max_length :] return input_ids
85
1
'''simple docstring''' from maths.prime_factors import prime_factors def UpperCamelCase_( snake_case : int ): '''simple docstring''' if not isinstance(snake_case , snake_case ): snake_case_ = f'Input value of [number={number}] must be an integer' raise TypeError(snake_case ) if number < 1: raise ValueError("Input must be a positive integer" ) return -1 if len(prime_factors(snake_case ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def UpperCamelCase_( snake_case : Tuple ): '''simple docstring''' snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = 0.01 with locka.acquire(): with pytest.raises(snake_case ): snake_case_ = time.time() locka.acquire(snake_case ) assert time.time() - _start > timeout def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = "a" * 1_0_0_0 + ".lock" snake_case_ = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(snake_case ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 snake_case_ = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case ): locka.acquire(0 )
85
1
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class _snake_case : lowerCAmelCase_ : int lowerCAmelCase_ : TreeNode | None = None lowerCAmelCase_ : TreeNode | None = None _SCREAMING_SNAKE_CASE : List[str] = namedtuple("CoinsDistribResult", "moves excess") def UpperCamelCase_( snake_case : TreeNode | None ): '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case ) != count_coins(snake_case ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(snake_case : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) snake_case_ , snake_case_ = get_distrib(node.left ) snake_case_ , snake_case_ = get_distrib(node.right ) snake_case_ = 1 - left_distrib_excess snake_case_ = 1 - right_distrib_excess snake_case_ = ( left_distrib_moves + right_distrib_moves + abs(snake_case ) + abs(snake_case ) ) snake_case_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case , snake_case ) return get_distrib(snake_case )[0] if __name__ == "__main__": import doctest doctest.testmod()
85
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE : Any = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _snake_case ( datasets.BuilderConfig ): lowerCAmelCase_ : Optional[datasets.Features] = None def UpperCamelCase_( snake_case : "pyspark.sql.DataFrame" , snake_case : List[int] , ): '''simple docstring''' import pyspark def generate_fn(): snake_case_ = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: snake_case_ = df_with_partition_id.select("*" ).where(f'part_id = {partition_id}' ).drop("part_id" ) snake_case_ = partition_df.collect() snake_case_ = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class _snake_case ( _BaseExamplesIterable ): def __init__( self , a__ , a__=None , ) -> Any: '''simple docstring''' snake_case_ = df snake_case_ = partition_order or range(self.df.rdd.getNumPartitions() ) snake_case_ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Union[str, Any]: '''simple docstring''' yield from self.generate_examples_fn() def lowerCAmelCase__ ( self , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> "SparkExamplesIterable": '''simple docstring''' snake_case_ = self.split_shard_indices_by_worker(a__ , a__ ) return SparkExamplesIterable(self.df , partition_order=a__ ) @property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return len(self.partition_order ) class _snake_case ( datasets.DatasetBuilder ): lowerCAmelCase_ : Dict = SparkConfig def __init__( self , a__ , a__ = None , a__ = None , **a__ , ) -> str: '''simple docstring''' import pyspark snake_case_ = pyspark.sql.SparkSession.builder.getOrCreate() snake_case_ = df snake_case_ = working_dir super().__init__( cache_dir=a__ , config_name=str(self.df.semanticHash() ) , **a__ , ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' def create_cache_and_write_probe(a__ ): # 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__ ) snake_case_ = 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: snake_case_ = ( 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 lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCAmelCase__ ( self , a__ ) -> Union[str, Any]: '''simple docstring''' import pyspark def get_arrow_batch_size(a__ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) snake_case_ = self.df.count() snake_case_ = 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. snake_case_ = ( 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 ) snake_case_ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. snake_case_ = min(a__ , int(approx_total_size / max_shard_size ) ) snake_case_ = self.df.repartition(a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: '''simple docstring''' import pyspark snake_case_ = ParquetWriter if file_format == "parquet" else ArrowWriter snake_case_ = os.path.join(self._working_dir , os.path.basename(a__ ) ) if self._working_dir else fpath snake_case_ = 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. snake_case_ = self.config.features snake_case_ = self._writer_batch_size snake_case_ = self._fs.storage_options def write_arrow(a__ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. snake_case_ = pyspark.TaskContext().taskAttemptId() snake_case_ = 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"] , ) snake_case_ = 0 snake_case_ = 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__ , ) snake_case_ = 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: snake_case_ , snake_case_ = 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 snake_case_ = 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__ , ) snake_case_ = pa.Table.from_batches([batch] ) writer.write_table(a__ ) if writer._num_bytes > 0: snake_case_ , snake_case_ = 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__ ) ): snake_case_ = os.path.join(os.path.dirname(a__ ) , os.path.basename(a__ ) ) shutil.move(a__ , a__ ) snake_case_ = ( 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 lowerCAmelCase__ ( self , a__ , a__ = "arrow" , a__ = None , a__ = None , **a__ , ) -> int: '''simple docstring''' self._validate_cache_dir() snake_case_ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a__ ) snake_case_ = not is_remote_filesystem(self._fs ) snake_case_ = os.path.join if is_local else posixpath.join snake_case_ = "-TTTTT-SSSSS-of-NNNNN" snake_case_ = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' snake_case_ = path_join(self._output_dir , a__ ) snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = [] snake_case_ = [] for task_id, content in self._prepare_split_single(a__ , a__ , a__ ): ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = 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__ ) snake_case_ = total_num_examples snake_case_ = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: snake_case_ = 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. snake_case_ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a__ , a__ , a__ , ): 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}' ) , ) snake_case_ = [] snake_case_ = 0 for i in range(len(a__ ) ): snake_case_ , snake_case_ = 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 snake_case_ = 0 snake_case_ = 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 lowerCAmelCase__ ( self , a__ , ) -> SparkExamplesIterable: '''simple docstring''' return SparkExamplesIterable(self.df )
85
1
'''simple docstring''' from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _snake_case ( lowercase_ ): lowerCAmelCase_ : int = ["image_processor", "tokenizer"] lowerCAmelCase_ : Union[str, Any] = "BridgeTowerImageProcessor" lowerCAmelCase_ : Union[str, Any] = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self , a__ , a__ ) -> Optional[int]: '''simple docstring''' super().__init__(a__ , a__ ) def __call__( self , a__ , a__ = None , a__ = True , a__ = False , a__ = None , a__ = None , a__ = 0 , a__ = None , a__ = None , a__ = None , a__ = False , a__ = False , a__ = False , a__ = False , a__ = True , a__ = None , **a__ , ) -> BatchEncoding: '''simple docstring''' snake_case_ = self.tokenizer( text=a__ , add_special_tokens=a__ , padding=a__ , truncation=a__ , max_length=a__ , stride=a__ , pad_to_multiple_of=a__ , return_token_type_ids=a__ , return_attention_mask=a__ , return_overflowing_tokens=a__ , return_special_tokens_mask=a__ , return_offsets_mapping=a__ , return_length=a__ , verbose=a__ , return_tensors=a__ , **a__ , ) # add pixel_values + pixel_mask snake_case_ = self.image_processor( a__ , return_tensors=a__ , do_normalize=a__ , do_center_crop=a__ , **a__ ) encoding.update(a__ ) return encoding def lowerCAmelCase__ ( self , *a__ , **a__ ) -> Optional[int]: '''simple docstring''' return self.tokenizer.batch_decode(*a__ , **a__ ) def lowerCAmelCase__ ( self , *a__ , **a__ ) -> int: '''simple docstring''' return self.tokenizer.decode(*a__ , **a__ ) @property def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.tokenizer.model_input_names snake_case_ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
85
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB 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 typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : List[str] = { "configuration_cpmant": ["CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CpmAntConfig"], "tokenization_cpmant": ["CpmAntTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST", "CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Any = { "microsoft/swin-tiny-patch4-window7-224": ( "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json" ), # See all Swin models at https://huggingface.co/models?filter=swin } class _snake_case ( lowercase_ , lowercase_ ): lowerCAmelCase_ : Tuple = "swin" lowerCAmelCase_ : Dict = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a__=224 , a__=4 , a__=3 , a__=96 , a__=[2, 2, 6, 2] , a__=[3, 6, 12, 24] , a__=7 , a__=4.0 , a__=True , a__=0.0 , a__=0.0 , a__=0.1 , a__="gelu" , a__=False , a__=0.0_2 , a__=1e-5 , a__=32 , a__=None , a__=None , **a__ , ) -> Optional[int]: '''simple docstring''' super().__init__(**a__ ) snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = embed_dim snake_case_ = depths snake_case_ = len(a__ ) snake_case_ = num_heads snake_case_ = window_size snake_case_ = mlp_ratio snake_case_ = qkv_bias snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = drop_path_rate snake_case_ = hidden_act snake_case_ = use_absolute_embeddings snake_case_ = layer_norm_eps snake_case_ = initializer_range snake_case_ = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case_ = int(embed_dim * 2 ** (len(a__ ) - 1) ) snake_case_ = ["stem"] + [F'stage{idx}' for idx in range(1 , len(a__ ) + 1 )] snake_case_ , snake_case_ = get_aligned_output_features_output_indices( out_features=a__ , out_indices=a__ , stage_names=self.stage_names ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : str = version.parse("1.11" ) @property def lowerCAmelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def lowerCAmelCase__ ( self ) -> float: '''simple docstring''' return 1e-4
85
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu _SCREAMING_SNAKE_CASE : Union[str, Any] = False class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' return 12 @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' return 32 @property def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 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 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(a__ ) @property def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = 12 snake_case_ = 12 snake_case_ = { "attention_bias": True, "cross_attention_dim": 32, "attention_head_dim": height * width, "num_attention_heads": 1, "num_vector_embeds": self.num_embed, "num_embeds_ada_norm": self.num_embeds_ada_norm, "norm_num_groups": 32, "sample_size": width, "activation_fn": "geglu-approximate", } snake_case_ = TransformeraDModel(**a__ ) return model def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings(learnable=a__ ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_5_5_1, 0.6_1_6_8, 0.5_0_0_8, 0.5_6_7_6, 0.5_6_5_9, 0.4_2_9_5, 0.6_0_7_3, 0.5_5_9_9, 0.4_9_9_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.dummy_vqvae snake_case_ = self.dummy_text_encoder snake_case_ = self.dummy_tokenizer snake_case_ = self.dummy_transformer snake_case_ = VQDiffusionScheduler(self.num_embed ) snake_case_ = LearnedClassifierFreeSamplingEmbeddings( learnable=a__ , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) snake_case_ = VQDiffusionPipeline( vqvae=a__ , text_encoder=a__ , tokenizer=a__ , transformer=a__ , scheduler=a__ , learned_classifier_free_sampling_embeddings=a__ , ) snake_case_ = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) snake_case_ = "teddy bear playing in the pool" snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe([prompt] , generator=a__ , num_inference_steps=2 , output_type="np" ) snake_case_ = output.images snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipe( [prompt] , generator=a__ , output_type="np" , return_dict=a__ , num_inference_steps=2 )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) snake_case_ = np.array([0.6_6_9_3, 0.6_0_7_5, 0.4_9_5_9, 0.5_7_0_1, 0.5_5_8_3, 0.4_3_3_3, 0.6_1_7_1, 0.5_6_8_4, 0.4_9_8_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy" ) snake_case_ = VQDiffusionPipeline.from_pretrained("microsoft/vq-diffusion-ithq" ) snake_case_ = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though snake_case_ = torch.Generator(device=a__ ).manual_seed(0 ) snake_case_ = pipeline( "teddy bear playing in the pool" , num_images_per_prompt=1 , generator=a__ , output_type="np" , ) snake_case_ = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
85
1
'''simple docstring''' import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class _snake_case : def __init__( self , a__ , a__=100 , a__=13 , a__=30 , a__=2 , a__=3 , a__=True , a__=True , a__=32 , a__=4 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.0_2 , a__=3 , a__=None , a__=[0, 1, 2, 3] , ) -> Tuple: '''simple docstring''' snake_case_ = parent snake_case_ = 100 snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = is_training snake_case_ = use_labels snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = scope snake_case_ = out_indices snake_case_ = num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case_ = (image_size // patch_size) ** 2 snake_case_ = num_patches + 1 def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels, pixel_labels def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a__ , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> Any: '''simple docstring''' snake_case_ = BeitModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> Any: '''simple docstring''' snake_case_ = BeitForMaskedImageModeling(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> str: '''simple docstring''' snake_case_ = self.type_sequence_label_size snake_case_ = BeitForImageClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case_ = 1 snake_case_ = BeitForImageClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> List[str]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = BeitForSemanticSegmentation(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) snake_case_ = model(a__ , labels=a__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _snake_case ( lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : int = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) lowerCAmelCase_ : Optional[Any] = ( { "feature-extraction": BeitModel, "image-classification": BeitForImageClassification, "image-segmentation": BeitForSemanticSegmentation, } if is_torch_available() else {} ) lowerCAmelCase_ : List[str] = False lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Tuple = False def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = BeitModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="BEiT does not use inputs_embeds" ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , nn.Linear ) ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(a__ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , a__ ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' if not self.model_tester.is_training: return snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(a__ ), BeitForMaskedImageModeling]: continue snake_case_ = model_class(a__ ) model.to(a__ ) model.train() snake_case_ = self._prepare_for_class(a__ , a__ , return_labels=a__ ) snake_case_ = model(**a__ ).loss loss.backward() def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return snake_case_ = False snake_case_ = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(a__ ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(a__ ) model.gradient_checkpointing_enable() model.to(a__ ) model.train() snake_case_ = self._prepare_for_class(a__ , a__ , return_labels=a__ ) snake_case_ = model(**a__ ).loss loss.backward() def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = _config_zero_init(a__ ) for model_class in self.all_model_classes: snake_case_ = model_class(config=a__ ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue 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' , ) @slow def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = BeitModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def UpperCamelCase_( ): '''simple docstring''' snake_case_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _snake_case ( unittest.TestCase ): @cached_property def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224" ) if is_vision_available() else None @slow def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k" ).to(a__ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(images=a__ , return_tensors="pt" ).pixel_values.to(a__ ) # prepare bool_masked_pos snake_case_ = torch.ones((1, 196) , dtype=torch.bool ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(pixel_values=a__ , bool_masked_pos=a__ ) snake_case_ = outputs.logits # verify the logits snake_case_ = torch.Size((1, 196, 8_192) ) self.assertEqual(logits.shape , a__ ) snake_case_ = torch.tensor( [[-3.2_4_3_7, 0.5_0_7_2, -1_3.9_1_7_4], [-3.2_4_5_6, 0.4_9_4_8, -1_3.9_4_0_1], [-3.2_0_3_3, 0.5_1_2_1, -1_3.8_5_5_0]] ).to(a__ ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , a__ , atol=1e-2 ) ) @slow def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224" ).to(a__ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(images=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) snake_case_ = outputs.logits # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(logits.shape , a__ ) snake_case_ = torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8] ).to(a__ ) self.assertTrue(torch.allclose(logits[0, :3] , a__ , atol=1e-4 ) ) snake_case_ = 281 self.assertEqual(logits.argmax(-1 ).item() , a__ ) @slow def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k" ).to( a__ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(images=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) snake_case_ = outputs.logits # verify the logits snake_case_ = torch.Size((1, 21_841) ) self.assertEqual(logits.shape , a__ ) snake_case_ = torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1] ).to(a__ ) self.assertTrue(torch.allclose(logits[0, :3] , a__ , atol=1e-4 ) ) snake_case_ = 2_396 self.assertEqual(logits.argmax(-1 ).item() , a__ ) @slow def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) snake_case_ = model.to(a__ ) snake_case_ = BeitImageProcessor(do_resize=a__ , size=640 , do_center_crop=a__ ) snake_case_ = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) snake_case_ = Image.open(ds[0]["file"] ) snake_case_ = image_processor(images=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) snake_case_ = outputs.logits # verify the logits snake_case_ = torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape , a__ ) snake_case_ = version.parse(PIL.__version__ ) < version.parse("9.0.0" ) if is_pillow_less_than_a: snake_case_ = torch.tensor( [ [[-4.9_2_2_5, -2.3_9_5_4, -3.0_5_2_2], [-2.8_8_2_2, -1.0_0_4_6, -1.7_5_6_1], [-2.9_5_4_9, -1.3_2_2_8, -2.1_3_4_7]], [[-5.8_1_6_8, -3.4_1_2_9, -4.0_7_7_8], [-3.8_6_5_1, -2.2_2_1_4, -3.0_2_7_7], [-3.8_3_5_6, -2.4_6_4_3, -3.3_5_3_5]], [[-0.0_0_7_8, 3.9_9_5_2, 4.0_7_5_4], [2.9_8_5_6, 4.6_9_4_4, 5.0_0_3_5], [3.2_4_1_3, 4.7_8_1_3, 4.9_9_6_9]], ] , device=a__ , ) else: snake_case_ = torch.tensor( [ [[-4.8_9_6_0, -2.3_6_8_8, -3.0_3_5_5], [-2.8_4_7_8, -0.9_8_3_6, -1.7_4_1_8], [-2.9_4_4_9, -1.3_3_3_2, -2.1_4_5_6]], [[-5.8_0_8_1, -3.4_1_2_4, -4.1_0_0_6], [-3.8_5_6_1, -2.2_0_8_1, -3.0_3_2_3], [-3.8_3_6_5, -2.4_6_0_1, -3.3_6_6_9]], [[-0.0_3_0_9, 3.9_8_6_8, 4.0_5_4_0], [2.9_6_4_0, 4.6_8_7_7, 4.9_9_7_6], [3.2_0_8_1, 4.7_6_9_0, 4.9_9_4_2]], ] , device=a__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , a__ , atol=1e-4 ) ) @slow def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) snake_case_ = model.to(a__ ) snake_case_ = BeitImageProcessor(do_resize=a__ , size=640 , do_center_crop=a__ ) snake_case_ = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) snake_case_ = Image.open(ds[0]["file"] ) snake_case_ = image_processor(images=a__ , return_tensors="pt" ).to(a__ ) # forward pass with torch.no_grad(): snake_case_ = model(**a__ ) snake_case_ = outputs.logits.detach().cpu() snake_case_ = image_processor.post_process_semantic_segmentation(outputs=a__ , target_sizes=[(500, 300)] ) snake_case_ = torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , a__ ) snake_case_ = image_processor.post_process_semantic_segmentation(outputs=a__ ) snake_case_ = torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape , a__ )
85
'''simple docstring''' from statistics import mean, stdev def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = min(snake_case ) snake_case_ = max(snake_case ) # normalize data return [round((x - x_min) / (x_max - x_min) , snake_case ) for x in data] def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = mean(snake_case ) snake_case_ = stdev(snake_case ) # standardize data return [round((x - mu) / (sigma) , snake_case ) for x in data]
85
1
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class _snake_case ( lowercase_ ): lowerCAmelCase_ : int = (DPMSolverSinglestepScheduler,) lowerCAmelCase_ : Optional[int] = (("num_inference_steps", 25),) def lowerCAmelCase__ ( self , **a__ ) -> int: '''simple docstring''' snake_case_ = { "num_train_timesteps": 1_000, "beta_start": 0.0_0_0_1, "beta_end": 0.0_2, "beta_schedule": "linear", "solver_order": 2, "prediction_type": "epsilon", "thresholding": False, "sample_max_value": 1.0, "algorithm_type": "dpmsolver++", "solver_type": "midpoint", "lambda_min_clipped": -float("inf" ), "variance_type": None, } config.update(**a__ ) return config def lowerCAmelCase__ ( self , a__=0 , **a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = dict(self.forward_default_kwargs ) snake_case_ = kwargs.pop("num_inference_steps" , a__ ) snake_case_ = self.dummy_sample snake_case_ = 0.1 * sample snake_case_ = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: snake_case_ = self.get_scheduler_config(**a__ ) snake_case_ = scheduler_class(**a__ ) scheduler.set_timesteps(a__ ) # copy over dummy past residuals snake_case_ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a__ ) snake_case_ = scheduler_class.from_pretrained(a__ ) new_scheduler.set_timesteps(a__ ) # copy over dummy past residuals snake_case_ = dummy_past_residuals[: new_scheduler.config.solver_order] snake_case_ , snake_case_ = sample, sample for t in range(a__ , time_step + scheduler.config.solver_order + 1 ): snake_case_ = scheduler.step(a__ , a__ , a__ , **a__ ).prev_sample snake_case_ = 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 lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' pass def lowerCAmelCase__ ( self , a__=0 , **a__ ) -> Any: '''simple docstring''' snake_case_ = dict(self.forward_default_kwargs ) snake_case_ = kwargs.pop("num_inference_steps" , a__ ) snake_case_ = self.dummy_sample snake_case_ = 0.1 * sample snake_case_ = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: snake_case_ = self.get_scheduler_config() snake_case_ = scheduler_class(**a__ ) scheduler.set_timesteps(a__ ) # copy over dummy past residuals (must be after setting timesteps) snake_case_ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(a__ ) snake_case_ = 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) snake_case_ = dummy_past_residuals[: new_scheduler.config.solver_order] snake_case_ = scheduler.step(a__ , a__ , a__ , **a__ ).prev_sample snake_case_ = 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 lowerCAmelCase__ ( self , a__=None , **a__ ) -> List[str]: '''simple docstring''' if scheduler is None: snake_case_ = self.scheduler_classes[0] snake_case_ = self.get_scheduler_config(**a__ ) snake_case_ = scheduler_class(**a__ ) snake_case_ = self.scheduler_classes[0] snake_case_ = self.get_scheduler_config(**a__ ) snake_case_ = scheduler_class(**a__ ) snake_case_ = 10 snake_case_ = self.dummy_model() snake_case_ = self.dummy_sample_deter scheduler.set_timesteps(a__ ) for i, t in enumerate(scheduler.timesteps ): snake_case_ = model(a__ , a__ ) snake_case_ = scheduler.step(a__ , a__ , a__ ).prev_sample return sample def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) snake_case_ = 50 snake_case_ = self.dummy_model() snake_case_ = self.dummy_sample_deter scheduler.set_timesteps(a__ ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): snake_case_ = model(a__ , a__ ) snake_case_ = scheduler.step(a__ , a__ , a__ ).prev_sample snake_case_ = torch.mean(torch.abs(a__ ) ) assert abs(result_mean.item() - 0.2_5_7_4 ) < 1e-3 def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' for timesteps in [25, 50, 100, 999, 1_000]: self.check_over_configs(num_train_timesteps=a__ ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) snake_case_ = self.full_loop(scheduler=a__ ) snake_case_ = torch.mean(torch.abs(a__ ) ) assert abs(result_mean.item() - 0.2_7_9_1 ) < 1e-3 snake_case_ = DEISMultistepScheduler.from_config(scheduler.config ) snake_case_ = DPMSolverMultistepScheduler.from_config(scheduler.config ) snake_case_ = UniPCMultistepScheduler.from_config(scheduler.config ) snake_case_ = DPMSolverSinglestepScheduler.from_config(scheduler.config ) snake_case_ = self.full_loop(scheduler=a__ ) snake_case_ = torch.mean(torch.abs(a__ ) ) assert abs(result_mean.item() - 0.2_7_9_1 ) < 1e-3 def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self.check_over_configs(thresholding=a__ ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: 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__ , algorithm_type="dpmsolver++" , solver_order=a__ , solver_type=a__ , ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: 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__ , algorithm_type=a__ , ) snake_case_ = self.full_loop( solver_order=a__ , solver_type=a__ , prediction_type=a__ , algorithm_type=a__ , ) assert not torch.isnan(a__ ).any(), "Samples have nan numbers" def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.check_over_configs(lower_order_final=a__ ) self.check_over_configs(lower_order_final=a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' self.check_over_configs(lambda_min_clipped=-float("inf" ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' self.check_over_configs(variance_type=a__ ) self.check_over_configs(variance_type="learned_range" ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1_000]: self.check_over_forward(num_inference_steps=a__ , time_step=0 ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.full_loop() snake_case_ = torch.mean(torch.abs(a__ ) ) assert abs(result_mean.item() - 0.2_7_9_1 ) < 1e-3 def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.full_loop(use_karras_sigmas=a__ ) snake_case_ = torch.mean(torch.abs(a__ ) ) assert abs(result_mean.item() - 0.2_2_4_8 ) < 1e-3 def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.full_loop(prediction_type="v_prediction" ) snake_case_ = torch.mean(torch.abs(a__ ) ) assert abs(result_mean.item() - 0.1_4_5_3 ) < 1e-3 def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = self.full_loop(prediction_type="v_prediction" , use_karras_sigmas=a__ ) snake_case_ = torch.mean(torch.abs(a__ ) ) assert abs(result_mean.item() - 0.0_6_4_9 ) < 1e-3 def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.scheduler_classes[0] snake_case_ = self.get_scheduler_config(thresholding=a__ , dynamic_thresholding_ratio=0 ) snake_case_ = scheduler_class(**a__ ) snake_case_ = 10 snake_case_ = self.dummy_model() snake_case_ = self.dummy_sample_deter.half() scheduler.set_timesteps(a__ ) for i, t in enumerate(scheduler.timesteps ): snake_case_ = model(a__ , a__ ) snake_case_ = scheduler.step(a__ , a__ , a__ ).prev_sample assert sample.dtype == torch.floataa
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE : Optional[Any] = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : str = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[str] = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[Any] = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
85
1
'''simple docstring''' from collections import deque from .hash_table import HashTable class _snake_case ( lowercase_ ): def __init__( self , *a__ , **a__ ) -> Tuple: '''simple docstring''' super().__init__(*a__ , **a__ ) def lowerCAmelCase__ ( self , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(a__ ) snake_case_ = self.values[key] def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return ( sum(self.charge_factor - len(a__ ) for slot in self.values ) / self.size_table * self.charge_factor ) def lowerCAmelCase__ ( self , a__ , a__=None ) -> str: '''simple docstring''' if not ( len(self.values[key] ) == self.charge_factor and self.values.count(a__ ) == 0 ): return key return super()._collision_resolution(a__ , a__ )
85
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. snake_case_ = min(snake_case , snake_case ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
85
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "upernet" def __init__( self , a__=None , a__=512 , a__=0.0_2 , a__=[1, 2, 3, 6] , a__=True , a__=0.4 , a__=384 , a__=256 , a__=1 , a__=False , a__=255 , **a__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**a__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) snake_case_ = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a__ , a__ ): snake_case_ = backbone_config.get("model_type" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(a__ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE : Tuple = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConditionalDetrConfig", "ConditionalDetrOnnxConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Union[str, Any] = ["ConditionalDetrFeatureExtractor"] _SCREAMING_SNAKE_CASE : List[Any] = ["ConditionalDetrImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Dict = [ "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "ConditionalDetrForObjectDetection", "ConditionalDetrForSegmentation", "ConditionalDetrModel", "ConditionalDetrPreTrainedModel", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = "ZinengTang/tvlt-base" snake_case_ = tempfile.mkdtemp() def lowerCAmelCase__ ( self , **a__ ) -> Any: '''simple docstring''' return TvltImageProcessor.from_pretrained(self.checkpoint , **a__ ) def lowerCAmelCase__ ( self , **a__ ) -> Union[str, Any]: '''simple docstring''' return TvltFeatureExtractor.from_pretrained(self.checkpoint , **a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) processor.save_pretrained(self.tmpdirname ) snake_case_ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , a__ ) self.assertIsInstance(processor.image_processor , a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) snake_case_ = np.ones([12_000] ) snake_case_ = feature_extractor(a__ , return_tensors="np" ) snake_case_ = processor(audio=a__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) snake_case_ = np.ones([3, 224, 224] ) snake_case_ = image_processor(a__ , return_tensors="np" ) snake_case_ = processor(images=a__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) snake_case_ = np.ones([12_000] ) snake_case_ = np.ones([3, 224, 224] ) snake_case_ = processor(audio=a__ , images=a__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(a__ ): processor() def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
85
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--txt2img_unclip", default="kakaobrain/karlo-v1-alpha", type=str, required=False, help="The pretrained txt2img unclip.", ) _SCREAMING_SNAKE_CASE : int = parser.parse_args() _SCREAMING_SNAKE_CASE : List[Any] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor() _SCREAMING_SNAKE_CASE : str = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") _SCREAMING_SNAKE_CASE : int = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
85
1
'''simple docstring''' import warnings from functools import wraps from typing import Callable def UpperCamelCase_( snake_case : Callable ): '''simple docstring''' @wraps(snake_case ) def _inner_fn(*snake_case : Optional[int] , **snake_case : List[Any] ): warnings.warn( (f'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , snake_case , ) return fn(*snake_case , **snake_case ) return _inner_fn
85
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lowerCAmelCase_ : Any = "upernet" def __init__( self , a__=None , a__=512 , a__=0.0_2 , a__=[1, 2, 3, 6] , a__=True , a__=0.4 , a__=384 , a__=256 , a__=1 , a__=False , a__=255 , **a__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**a__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) snake_case_ = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a__ , a__ ): snake_case_ = backbone_config.get("model_type" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(a__ ) snake_case_ = backbone_config snake_case_ = hidden_size snake_case_ = initializer_range snake_case_ = pool_scales snake_case_ = use_auxiliary_head snake_case_ = auxiliary_loss_weight snake_case_ = auxiliary_in_channels snake_case_ = auxiliary_channels snake_case_ = auxiliary_num_convs snake_case_ = auxiliary_concat_input snake_case_ = loss_ignore_index def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
85
1