code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import re import string import numpy as np import datasets _UpperCamelCase : List[str] = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" _UpperCamelCase : Optional[Any] = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" _UpperCamelCase : Optional[Any] = "\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCAmelCase_ ( datasets.Metric): def _UpperCAmelCase ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , reference_urls=[] , ) def _UpperCAmelCase ( self , a , a , a=None , a=False , a=False , a=False , ) -> Union[str, Any]: if regexes_to_ignore is not None: for s in regexes_to_ignore: lowercase__ : List[Any] = np.array([re.sub(a , '' , a ) for x in predictions] ) lowercase__ : Tuple = np.array([re.sub(a , '' , a ) for x in references] ) else: lowercase__ : Optional[int] = np.asarray(a ) lowercase__ : Union[str, Any] = np.asarray(a ) if ignore_case: lowercase__ : Tuple = np.char.lower(a ) lowercase__ : List[Any] = np.char.lower(a ) if ignore_punctuation: lowercase__ : Any = string.punctuation.maketrans('' , '' , string.punctuation ) lowercase__ : Union[str, Any] = np.char.translate(a , table=a ) lowercase__ : Optional[int] = np.char.translate(a , table=a ) if ignore_numbers: lowercase__ : Any = string.digits.maketrans('' , '' , string.digits ) lowercase__ : Union[str, Any] = np.char.translate(a , table=a ) lowercase__ : List[Any] = np.char.translate(a , table=a ) lowercase__ : Any = predictions == references return {"exact_match": np.mean(a ) * 1_0_0}
77
"""simple docstring""" import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def a_ ( _lowerCAmelCase : Tuple , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : List[str] , _lowerCAmelCase : Union[str, Any] ): '''simple docstring''' lowercase__ : int = FunnelConfig.from_json_file(_lowerCAmelCase ) print(f"""Building PyTorch model from configuration: {config}""" ) lowercase__ : List[Any] = FunnelBaseModel(_lowerCAmelCase ) if base_model else FunnelModel(_lowerCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_funnel(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , _lowerCAmelCase ) if __name__ == "__main__": _UpperCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not." ) _UpperCamelCase : List[str] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
77
1
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json SCREAMING_SNAKE_CASE_:Optional[int] = """sshleifer/mar_enro_6_3_student""" class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def _lowerCAmelCase ( self ): super().setUp() A : Union[str, Any] = cached_path( """https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz""", extract_compressed_file=lowerCamelCase__, ) A : str = f'''{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k''' @slow @require_torch_gpu def _lowerCAmelCase ( self ): MarianMTModel.from_pretrained(lowerCamelCase__ ) @slow @require_torch_gpu def _lowerCAmelCase ( self ): A : List[str] = { """$MAX_LEN""": 64, """$BS""": 64, """$GAS""": 1, """$ENRO_DIR""": self.data_dir, """facebook/mbart-large-cc25""": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", """--learning_rate=3e-5""": """--learning_rate 3e-4""", """--num_train_epochs 6""": """--num_train_epochs 1""", } # Clean up bash script A : List[str] = (self.test_file_dir / """train_mbart_cc25_enro.sh""").open().read().split("""finetune.py""" )[1].strip() A : Any = bash_script.replace("""\\\n""", """""" ).strip().replace("""\"$@\"""", """""" ) for k, v in env_vars_to_replace.items(): A : int = bash_script.replace(lowerCamelCase__, str(lowerCamelCase__ ) ) A : Optional[int] = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") A : str = f''' --output_dir {output_dir} --tokenizer_name Helsinki-NLP/opus-mt-en-ro --sortish_sampler --do_predict --gpus 1 --freeze_encoder --n_train 40000 --n_val 500 --n_test 500 --fp16_opt_level O1 --num_sanity_val_steps 0 --eval_beams 2 '''.split() # XXX: args.gpus > 1 : handle multi_gpu in the future A : Optional[Any] = ["""finetune.py"""] + bash_script.split() + args with patch.object(lowerCamelCase__, """argv""", lowerCamelCase__ ): A : Any = argparse.ArgumentParser() A : Union[str, Any] = pl.Trainer.add_argparse_args(lowerCamelCase__ ) A : Union[str, Any] = SummarizationModule.add_model_specific_args(lowerCamelCase__, os.getcwd() ) A : List[Any] = parser.parse_args() A : List[str] = main(lowerCamelCase__ ) # Check metrics A : str = load_json(model.metrics_save_path ) A : Tuple = metrics["""val"""][0] A : int = metrics["""val"""][-1] self.assertEqual(len(metrics["""val"""] ), (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'''val_avg_{model.val_metric}'''], lowerCamelCase__ ) self.assertGreater(last_step_stats["""val_avg_gen_time"""], 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["""val_avg_gen_time"""], 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["""val_avg_bleu"""] - first_step_stats["""val_avg_bleu"""], 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["""val_avg_bleu"""], 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["""val"""][-1]["""val_avg_bleu"""] - metrics["""test"""][-1]["""test_avg_bleu"""] ), 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict A : Dict = os.listdir(lowerCamelCase__ ) A : List[str] = [x for x in contents if x.endswith(""".ckpt""" )][0] A : List[str] = os.path.join(args.output_dir, lowerCamelCase__ ) A : Tuple = torch.load(lowerCamelCase__, map_location="""cpu""" ) A : Any = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: A : Tuple = {os.path.basename(lowerCamelCase__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1 class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self ): A : Tuple = f'''{self.test_file_dir_str}/test_data/wmt_en_ro''' A : str = { """--fp16_opt_level=O1""": """""", """$MAX_LEN""": 128, """$BS""": 16, """$GAS""": 1, """$ENRO_DIR""": data_dir, """$m""": """sshleifer/student_marian_en_ro_6_1""", """val_check_interval=0.25""": """val_check_interval=1.0""", } # Clean up bash script A : int = ( (self.test_file_dir / """distil_marian_no_teacher.sh""").open().read().split("""distillation.py""" )[1].strip() ) A : Tuple = bash_script.replace("""\\\n""", """""" ).strip().replace("""\"$@\"""", """""" ) A : Optional[Any] = bash_script.replace("""--fp16 """, """ """ ) for k, v in env_vars_to_replace.items(): A : int = bash_script.replace(lowerCamelCase__, str(lowerCamelCase__ ) ) A : Union[str, Any] = self.get_auto_remove_tmp_dir() A : Optional[int] = bash_script.replace("""--fp16""", """""" ) A : Any = 6 A : int = ( ["""distillation.py"""] + bash_script.split() + [ f'''--output_dir={output_dir}''', """--gpus=1""", """--learning_rate=1e-3""", f'''--num_train_epochs={epochs}''', """--warmup_steps=10""", """--val_check_interval=1.0""", """--do_predict""", ] ) with patch.object(lowerCamelCase__, """argv""", lowerCamelCase__ ): A : Union[str, Any] = argparse.ArgumentParser() A : List[str] = pl.Trainer.add_argparse_args(lowerCamelCase__ ) A : Any = SummarizationDistiller.add_model_specific_args(lowerCamelCase__, os.getcwd() ) A : Union[str, Any] = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu A : List[str] = distill_main(lowerCamelCase__ ) # Check metrics A : Optional[int] = load_json(model.metrics_save_path ) A : str = metrics["""val"""][0] A : Any = metrics["""val"""][-1] assert len(metrics["""val"""] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'''val_avg_{model.val_metric}'''], lowerCamelCase__ ) # check lightning ckpt can be loaded and has a reasonable statedict A : Tuple = os.listdir(lowerCamelCase__ ) A : Any = [x for x in contents if x.endswith(""".ckpt""" )][0] A : List[str] = os.path.join(args.output_dir, lowerCamelCase__ ) A : List[Any] = torch.load(lowerCamelCase__, map_location="""cpu""" ) A : Optional[Any] = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: A : Dict = {os.path.basename(lowerCamelCase__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1
115
from __future__ import annotations def __UpperCamelCase ( _lowerCAmelCase ) -> list[int]: """simple docstring""" A : Tuple = 2 A : List[Any] = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_lowerCAmelCase ) if n > 1: factors.append(_lowerCAmelCase ) return factors if __name__ == "__main__": import doctest doctest.testmod()
115
1
_A : Any = frozenset( [ 'prompt', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) _A : List[Any] = frozenset(['prompt', 'negative_prompt']) _A : List[Any] = frozenset([]) _A : Optional[int] = frozenset(['image']) _A : int = frozenset( [ 'image', 'height', 'width', 'guidance_scale', ] ) _A : str = frozenset(['image']) _A : Tuple = frozenset( [ 'prompt', 'image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) _A : Optional[Any] = frozenset(['prompt', 'image', 'negative_prompt']) _A : Dict = frozenset( [ # Text guided image variation with an image mask 'prompt', 'image', 'mask_image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) _A : int = frozenset(['prompt', 'image', 'mask_image', 'negative_prompt']) _A : str = frozenset( [ # image variation with an image mask 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) _A : Optional[int] = frozenset(['image', 'mask_image']) _A : Optional[Any] = frozenset( [ 'example_image', 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) _A : int = frozenset(['example_image', 'image', 'mask_image']) _A : Dict = frozenset(['class_labels']) _A : List[Any] = frozenset(['class_labels']) _A : List[str] = frozenset(['batch_size']) _A : int = frozenset([]) _A : Any = frozenset(['batch_size']) _A : Any = frozenset([]) _A : Dict = frozenset( [ 'prompt', 'audio_length_in_s', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) _A : int = frozenset(['prompt', 'negative_prompt']) _A : List[Any] = frozenset(['input_tokens']) _A : Tuple = frozenset(['input_tokens'])
142
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor _A : str = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): def __init__( self : Dict , *A : Any , **A : List[Any] ) ->None: warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , A , ) super().__init__(*A , **A )
142
1
'''simple docstring''' from math import ceil def UpperCAmelCase__ ( UpperCAmelCase__ = 10_01 ) -> List[str]: A_ = 1 for i in range(1, int(ceil(n / 2.0 ) ) ): A_ = 2 * i + 1 A_ = 2 * i A_ = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: __lowerCamelCase = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
359
'''simple docstring''' import requests __lowerCamelCase = '''''' # <-- Put your OpenWeatherMap appid here! __lowerCamelCase = '''https://api.openweathermap.org/data/2.5/''' def UpperCAmelCase__ ( UpperCAmelCase__ = "Chicago", UpperCAmelCase__ = APPID ) -> dict: return requests.get(URL_BASE + """weather""", params=locals() ).json() def UpperCAmelCase__ ( UpperCAmelCase__ = "Kolkata, India", UpperCAmelCase__ = APPID ) -> dict: return requests.get(URL_BASE + """forecast""", params=locals() ).json() def UpperCAmelCase__ ( UpperCAmelCase__ = 55.68, UpperCAmelCase__ = 12.57, UpperCAmelCase__ = APPID ) -> dict: return requests.get(URL_BASE + """onecall""", params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowerCamelCase = input('''Enter a location:''').strip() if location: pprint(current_weather(location)) else: break
101
0
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( '''kwargs, expected''' , [ ({'''num_shards''': 0, '''max_num_jobs''': 1}, []), ({'''num_shards''': 10, '''max_num_jobs''': 1}, [range(10 )]), ({'''num_shards''': 10, '''max_num_jobs''': 10}, [range(_UpperCAmelCase , i + 1 ) for i in range(10 )]), ({'''num_shards''': 1, '''max_num_jobs''': 10}, [range(1 )]), ({'''num_shards''': 10, '''max_num_jobs''': 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({'''num_shards''': 3, '''max_num_jobs''': 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : List[Any] = _distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( '''gen_kwargs, max_num_jobs, expected''' , [ ({'''foo''': 0}, 10, [{'''foo''': 0}]), ({'''shards''': [0, 1, 2, 3]}, 1, [{'''shards''': [0, 1, 2, 3]}]), ({'''shards''': [0, 1, 2, 3]}, 4, [{'''shards''': [0]}, {'''shards''': [1]}, {'''shards''': [2]}, {'''shards''': [3]}]), ({'''shards''': [0, 1]}, 4, [{'''shards''': [0]}, {'''shards''': [1]}]), ({'''shards''': [0, 1, 2, 3]}, 2, [{'''shards''': [0, 1]}, {'''shards''': [2, 3]}]), ] , ) def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : str = _split_gen_kwargs(_UpperCAmelCase , _UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( '''gen_kwargs, expected''' , [ ({'''foo''': 0}, 1), ({'''shards''': [0]}, 1), ({'''shards''': [0, 1, 2, 3]}, 4), ({'''shards''': [0, 1, 2, 3], '''foo''': 0}, 4), ({'''shards''': [0, 1, 2, 3], '''other''': (0, 1)}, 4), ({'''shards''': [0, 1, 2, 3], '''shards2''': [0, 1]}, RuntimeError), ] , ) def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: A_ : Tuple = _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
167
"""simple docstring""" from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase ( __UpperCAmelCase): def a_ ( self : List[str] ): """simple docstring""" A_ : Optional[int] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_lowerCamelCase , '''embed_dim''' ) ) self.parent.assertTrue(hasattr(_lowerCamelCase , '''num_heads''' ) ) class lowercase : def __init__( self : Tuple , _lowerCamelCase : List[Any] , _lowerCamelCase : Union[str, Any]=13 , _lowerCamelCase : List[str]=64 , _lowerCamelCase : int=3 , _lowerCamelCase : int=[16, 48, 96] , _lowerCamelCase : Dict=[1, 3, 6] , _lowerCamelCase : List[Any]=[1, 2, 10] , _lowerCamelCase : Optional[int]=[7, 3, 3] , _lowerCamelCase : Optional[int]=[4, 2, 2] , _lowerCamelCase : Union[str, Any]=[2, 1, 1] , _lowerCamelCase : str=[2, 2, 2] , _lowerCamelCase : Tuple=[False, False, True] , _lowerCamelCase : Union[str, Any]=[0.0, 0.0, 0.0] , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Dict=1E-12 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : List[Any]=2 , ): """simple docstring""" A_ : Tuple = parent A_ : Dict = batch_size A_ : str = image_size A_ : Dict = patch_sizes A_ : Optional[int] = patch_stride A_ : Optional[int] = patch_padding A_ : Optional[Any] = is_training A_ : Union[str, Any] = use_labels A_ : str = num_labels A_ : Optional[int] = num_channels A_ : str = embed_dim A_ : Tuple = num_heads A_ : List[Any] = stride_kv A_ : str = depth A_ : Dict = cls_token A_ : Optional[Any] = attention_drop_rate A_ : str = initializer_range A_ : Tuple = layer_norm_eps def a_ ( self : Tuple ): """simple docstring""" A_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A_ : List[Any] = None if self.use_labels: # create a random int32 tensor of given shape A_ : Tuple = ids_tensor([self.batch_size] , self.num_labels ) A_ : Tuple = self.get_config() return config, pixel_values, labels def a_ ( self : Any ): """simple docstring""" return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def a_ ( self : List[str] , _lowerCamelCase : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[str, Any] ): """simple docstring""" A_ : str = TFCvtModel(config=_lowerCamelCase ) A_ : Any = model(_lowerCamelCase , training=_lowerCamelCase ) A_ : int = (self.image_size, self.image_size) A_ , A_ : Optional[int] = image_size[0], image_size[1] for i in range(len(self.depth ) ): A_ : List[str] = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) A_ : int = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def a_ ( self : Tuple , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Tuple ): """simple docstring""" A_ : Any = self.num_labels A_ : str = TFCvtForImageClassification(_lowerCamelCase ) A_ : List[Any] = model(_lowerCamelCase , labels=_lowerCamelCase , training=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self : Tuple ): """simple docstring""" A_ : Union[str, Any] = self.prepare_config_and_inputs() A_ , A_ , A_ : Tuple = config_and_inputs A_ : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class lowercase ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase): __lowerCAmelCase : str = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () __lowerCAmelCase : Tuple = ( {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification} if is_tf_available() else {} ) __lowerCAmelCase : int = False __lowerCAmelCase : List[Any] = False __lowerCAmelCase : List[Any] = False __lowerCAmelCase : List[str] = False __lowerCAmelCase : List[str] = False def a_ ( self : int ): """simple docstring""" A_ : Dict = TFCvtModelTester(self ) A_ : int = TFCvtConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def a_ ( self : Any ): """simple docstring""" self.config_tester.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() @unittest.skip(reason='''Cvt does not output attentions''' ) def a_ ( self : str ): """simple docstring""" pass @unittest.skip(reason='''Cvt does not use inputs_embeds''' ) def a_ ( self : Tuple ): """simple docstring""" pass @unittest.skip(reason='''Cvt does not support input and output embeddings''' ) def a_ ( self : Tuple ): """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) def a_ ( self : Tuple ): """simple docstring""" super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) @slow def a_ ( self : Dict ): """simple docstring""" super().test_keras_fit() @unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8''' ) def a_ ( self : int ): """simple docstring""" A_ : List[Any] = tf.keras.mixed_precision.Policy('''mixed_float16''' ) tf.keras.mixed_precision.set_global_policy(_lowerCamelCase ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('''float32''' ) def a_ ( self : str ): """simple docstring""" A_ , A_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : Optional[Any] = model_class(_lowerCamelCase ) A_ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A_ : Dict = [*signature.parameters.keys()] A_ : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def a_ ( self : int ): """simple docstring""" def check_hidden_states_output(_lowerCamelCase : int , _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] ): A_ : Union[str, Any] = model_class(_lowerCamelCase ) A_ : Tuple = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) A_ : Optional[int] = outputs.hidden_states A_ : Union[str, Any] = len(self.model_tester.depth ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) A_ , A_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : str = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A_ : Dict = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def a_ ( self : Tuple ): """simple docstring""" A_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def a_ ( self : int ): """simple docstring""" A_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @slow def a_ ( self : List[Any] ): """simple docstring""" for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ : List[Any] = TFCvtModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def lowercase_ ( ): """simple docstring""" A_ : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class lowercase ( unittest.TestCase): @cached_property def a_ ( self : List[Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def a_ ( self : Any ): """simple docstring""" A_ : Optional[int] = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) A_ : int = self.default_image_processor A_ : str = prepare_img() A_ : Optional[int] = image_processor(images=_lowerCamelCase , return_tensors='''tf''' ) # forward pass A_ : Dict = model(**_lowerCamelCase ) # verify the logits A_ : Union[str, Any] = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) A_ : Tuple = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _lowerCamelCase , atol=1E-4 ) )
167
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class a ( metaclass=_lowerCamelCase ): snake_case_ = ["torch", "scipy"] def __init__( self : Dict , *lowercase_ : Any , **lowercase_ : int ): requires_backends(self , ['''torch''', '''scipy'''] ) @classmethod def A_ ( cls : Any , *lowercase_ : str , **lowercase_ : Dict ): requires_backends(cls , ['''torch''', '''scipy'''] ) @classmethod def A_ ( cls : Optional[int] , *lowercase_ : int , **lowercase_ : Optional[Any] ): requires_backends(cls , ['''torch''', '''scipy'''] )
72
'''simple docstring''' import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset a : int = 'bert-base-cased' a : Optional[int] = 'google/pegasus-xsum' a : Optional[int] = [' Sam ate lunch today.', 'Sams lunch ingredients.'] a : int = ['A very interesting story about what I ate for lunch.', 'Avocado, celery, turkey, coffee'] a : Dict = 'patrickvonplaten/t5-tiny-random' a : Any = 'sshleifer/bart-tiny-random' a : Union[str, Any] = 'sshleifer/tiny-mbart' a : Optional[int] = 'sshleifer/tiny-marian-en-de' def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' snake_case_ = '''\n'''.join(__UpperCAmelCase ) Path(__UpperCAmelCase ).open('''w''' ).writelines(__UpperCAmelCase ) def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' for split in ["train", "val", "test"]: _dump_articles(os.path.join(__UpperCAmelCase, F"{split}.source" ), __UpperCAmelCase ) _dump_articles(os.path.join(__UpperCAmelCase, F"{split}.target" ), __UpperCAmelCase ) return tmp_dir class a ( _lowerCamelCase ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def A_ ( self : int , lowercase_ : Optional[Any] ): snake_case_ = AutoTokenizer.from_pretrained(lowercase_ ) snake_case_ = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) snake_case_ = max(len(tokenizer.encode(lowercase_ ) ) for a in ARTICLES ) snake_case_ = max(len(tokenizer.encode(lowercase_ ) ) for a in SUMMARIES ) snake_case_ = 4 snake_case_ = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated snake_case_ ,snake_case_ = '''ro_RO''', '''de_DE''' # ignored for all but mbart, but never causes error. snake_case_ = SeqaSeqDataset( lowercase_ , data_dir=lowercase_ , type_path='''train''' , max_source_length=lowercase_ , max_target_length=lowercase_ , src_lang=lowercase_ , tgt_lang=lowercase_ , ) snake_case_ = DataLoader(lowercase_ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(lowercase_ , lowercase_ ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place snake_case_ = shift_tokens_right(batch['''labels'''] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def A_ ( self : Union[str, Any] , lowercase_ : Dict ): snake_case_ = AutoTokenizer.from_pretrained(lowercase_ ) snake_case_ = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) snake_case_ = max(len(tokenizer.encode(lowercase_ ) ) for a in ARTICLES ) snake_case_ = max(len(tokenizer.encode(lowercase_ ) ) for a in SUMMARIES ) snake_case_ = 4 snake_case_ = LegacySeqaSeqDataset( lowercase_ , data_dir=lowercase_ , type_path='''train''' , max_source_length=20 , max_target_length=lowercase_ , ) snake_case_ = DataLoader(lowercase_ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 20 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def A_ ( self : Any ): snake_case_ = AutoTokenizer.from_pretrained('''facebook/mbart-large-cc25''' ) snake_case_ = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) snake_case_ = tmp_dir.joinpath('''train.source''' ).open().readlines() snake_case_ = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(lowercase_ , lowercase_ , 128 , lowercase_ ) snake_case_ = {x.name for x in tmp_dir.iterdir()} snake_case_ = {x.name for x in save_dir.iterdir()} snake_case_ = save_dir.joinpath('''train.source''' ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(lowercase_ ) < len(lowercase_ ) assert len(lowercase_ ) == 1 assert len(packed_examples[0] ) == sum(len(lowercase_ ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason='''This test requires fairseq''' ) def A_ ( self : Any ): if not FAIRSEQ_AVAILABLE: return snake_case_ ,snake_case_ ,snake_case_ = self._get_dataset(max_len=64 ) snake_case_ = 64 snake_case_ = ds.make_dynamic_sampler(lowercase_ , required_batch_size_multiple=lowercase_ ) snake_case_ = [len(lowercase_ ) for x in batch_sampler] assert len(set(lowercase_ ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(lowercase_ ) == len(lowercase_ ) # no dropped or added examples snake_case_ = DataLoader(lowercase_ , batch_sampler=lowercase_ , collate_fn=ds.collate_fn , num_workers=2 ) snake_case_ = [] snake_case_ = [] for batch in data_loader: snake_case_ = batch['''input_ids'''].shape snake_case_ = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple snake_case_ = np.product(batch['''input_ids'''].shape ) num_src_per_batch.append(lowercase_ ) if num_src_tokens > (max_tokens * 1.1): failures.append(lowercase_ ) assert num_src_per_batch[0] == max(lowercase_ ) if failures: raise AssertionError(F"too many tokens in {len(lowercase_ )} batches" ) def A_ ( self : List[str] ): snake_case_ ,snake_case_ ,snake_case_ = self._get_dataset(max_len=512 ) snake_case_ = 2 snake_case_ = ds.make_sortish_sampler(lowercase_ , shuffle=lowercase_ ) snake_case_ = DataLoader(lowercase_ , batch_size=lowercase_ , collate_fn=ds.collate_fn , num_workers=2 ) snake_case_ = DataLoader(lowercase_ , batch_size=lowercase_ , collate_fn=ds.collate_fn , num_workers=2 , sampler=lowercase_ ) snake_case_ = tokenizer.pad_token_id def count_pad_tokens(lowercase_ : Any , lowercase_ : int="input_ids" ): return [batch[k].eq(lowercase_ ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(lowercase_ , k='''labels''' ) ) < sum(count_pad_tokens(lowercase_ , k='''labels''' ) ) assert sum(count_pad_tokens(lowercase_ ) ) < sum(count_pad_tokens(lowercase_ ) ) assert len(lowercase_ ) == len(lowercase_ ) def A_ ( self : List[str] , lowercase_ : Tuple=1000 , lowercase_ : Optional[Any]=128 ): if os.getenv('''USE_REAL_DATA''' , lowercase_ ): snake_case_ = '''examples/seq2seq/wmt_en_ro''' snake_case_ = max_len * 2 * 64 if not Path(lowercase_ ).joinpath('''train.len''' ).exists(): save_len_file(lowercase_ , lowercase_ ) else: snake_case_ = '''examples/seq2seq/test_data/wmt_en_ro''' snake_case_ = max_len * 4 save_len_file(lowercase_ , lowercase_ ) snake_case_ = AutoTokenizer.from_pretrained(lowercase_ ) snake_case_ = SeqaSeqDataset( lowercase_ , data_dir=lowercase_ , type_path='''train''' , max_source_length=lowercase_ , max_target_length=lowercase_ , n_obs=lowercase_ , ) return ds, max_tokens, tokenizer def A_ ( self : Any ): snake_case_ ,snake_case_ ,snake_case_ = self._get_dataset() snake_case_ = set(DistributedSortishSampler(lowercase_ , 256 , num_replicas=2 , rank=0 , add_extra_examples=lowercase_ ) ) snake_case_ = set(DistributedSortishSampler(lowercase_ , 256 , num_replicas=2 , rank=1 , add_extra_examples=lowercase_ ) ) assert idsa.intersection(lowercase_ ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def A_ ( self : List[str] , lowercase_ : Optional[Any] ): snake_case_ = AutoTokenizer.from_pretrained(lowercase_ , use_fast=lowercase_ ) if tok_name == MBART_TINY: snake_case_ = SeqaSeqDataset( lowercase_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='''train''' , max_source_length=4 , max_target_length=8 , src_lang='''EN''' , tgt_lang='''FR''' , ) snake_case_ = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: snake_case_ = SeqaSeqDataset( lowercase_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='''train''' , max_source_length=4 , max_target_length=8 , ) snake_case_ = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(lowercase_ ) == 1 if tok_name == BART_TINY else len(lowercase_ ) == 0
72
1
import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class _lowercase ( snake_case_ , unittest.TestCase ): lowercase = BlenderbotSmallTokenizer lowercase = False def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: """simple docstring""" super().setUp() UpperCamelCase_ : Dict = ['__start__', 'adapt', 'act', 'ap@@', 'te', '__end__', '__unk__'] UpperCamelCase_ : Union[str, Any] = dict(zip(snake_case , range(len(snake_case ) ) ) ) UpperCamelCase_ : Any = ['#version: 0.2', 'a p', 't e</w>', 'ap t</w>', 'a d', 'ad apt</w>', 'a c', 'ac t</w>', ''] UpperCamelCase_ : List[Any] = {'unk_token': '__unk__', 'bos_token': '__start__', 'eos_token': '__end__'} UpperCamelCase_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(snake_case ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(snake_case ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **snake_case : Tuple ) -> Optional[int]: """simple docstring""" kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **snake_case ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case : Optional[Any] ) -> int: """simple docstring""" UpperCamelCase_ : Any = 'adapt act apte' UpperCamelCase_ : Dict = 'adapt act apte' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self : int ) -> int: """simple docstring""" UpperCamelCase_ : Any = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase_ : Union[str, Any] = 'adapt act apte' UpperCamelCase_ : Tuple = ['adapt', 'act', 'ap@@', 'te'] UpperCamelCase_ : int = tokenizer.tokenize(snake_case ) self.assertListEqual(snake_case , snake_case ) UpperCamelCase_ : int = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] UpperCamelCase_ : Any = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case ) , snake_case ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCamelCase_ : int = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) assert tok('sam' ).input_ids == [1_3_8_4] UpperCamelCase_ : Optional[int] = 'I am a small frog.' UpperCamelCase_ : Optional[int] = tok([src_text] , padding=snake_case , truncation=snake_case )['input_ids'] UpperCamelCase_ : Optional[Any] = tok.batch_decode(snake_case , skip_special_tokens=snake_case , clean_up_tokenization_spaces=snake_case )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ : List[str] = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) UpperCamelCase_ : Optional[int] = 'I am a small frog .' UpperCamelCase_ : int = '.' UpperCamelCase_ : Dict = tok(snake_case )['input_ids'] UpperCamelCase_ : Union[str, Any] = tok(snake_case )['input_ids'] assert encoded[-1] == encoded_dot[0]
175
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip a_ = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def __lowercase ( lowerCamelCase : Optional[Any] ): if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : str ): return max(metric_fn(lowerCamelCase , lowerCamelCase ) for gt in ground_truths ) def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : Dict ): UpperCamelCase_ : Tuple = [line.strip() for line in open(lowerCamelCase , 'r' ).readlines()] UpperCamelCase_ : List[Any] = [] if args.gold_data_mode == "qa": UpperCamelCase_ : Union[str, Any] = pd.read_csv(lowerCamelCase , sep='\t' , header=lowerCamelCase ) for answer_list in data[1]: UpperCamelCase_ : Optional[int] = ast.literal_eval(lowerCamelCase ) answers.append(lowerCamelCase ) else: UpperCamelCase_ : int = [line.strip() for line in open(lowerCamelCase , 'r' ).readlines()] UpperCamelCase_ : Optional[int] = [[reference] for reference in references] UpperCamelCase_ : Optional[int] = 0 for prediction, ground_truths in zip(lowerCamelCase , lowerCamelCase ): total += 1 em += metric_max_over_ground_truths(lowerCamelCase , lowerCamelCase , lowerCamelCase ) fa += metric_max_over_ground_truths(lowerCamelCase , lowerCamelCase , lowerCamelCase ) UpperCamelCase_ : Union[str, Any] = 1_0_0.0 * em / total UpperCamelCase_ : List[Any] = 1_0_0.0 * fa / total logger.info(F"F1: {fa:.2f}" ) logger.info(F"EM: {em:.2f}" ) def __lowercase ( lowerCamelCase : Any , lowerCamelCase : int , lowerCamelCase : List[str] ): UpperCamelCase_ : Optional[int] = args.k UpperCamelCase_ : List[Any] = [line.strip() for line in open(lowerCamelCase , 'r' ).readlines()] UpperCamelCase_ : List[str] = [line.strip() for line in open(lowerCamelCase , 'r' ).readlines()] UpperCamelCase_ : List[str] = 0 for hypo, reference in zip(lowerCamelCase , lowerCamelCase ): UpperCamelCase_ : List[str] = set(hypo.split('\t' )[:k] ) UpperCamelCase_ : int = set(reference.split('\t' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k UpperCamelCase_ : Union[str, Any] = 1_0_0.0 * em / total logger.info(F"Precision@{k}: {em: .2f}" ) def __lowercase ( lowerCamelCase : Tuple , lowerCamelCase : Any , lowerCamelCase : Any ): def strip_title(lowerCamelCase : List[str] ): if title.startswith('"' ): UpperCamelCase_ : List[str] = title[1:] if title.endswith('"' ): UpperCamelCase_ : int = title[:-1] return title UpperCamelCase_ : Optional[int] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCamelCase , return_tensors='pt' , padding=lowerCamelCase , truncation=lowerCamelCase , )['input_ids'].to(args.device ) UpperCamelCase_ : int = rag_model.rag.question_encoder(lowerCamelCase ) UpperCamelCase_ : List[str] = question_enc_outputs[0] UpperCamelCase_ : Tuple = rag_model.retriever( lowerCamelCase , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='pt' , ) UpperCamelCase_ : str = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) UpperCamelCase_ : int = [] for docs in all_docs: UpperCamelCase_ : Union[str, Any] = [strip_title(lowerCamelCase ) for title in docs['title']] provenance_strings.append('\t'.join(lowerCamelCase ) ) return provenance_strings def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : List[Any] , lowerCamelCase : List[Any] ): with torch.no_grad(): UpperCamelCase_ : List[Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCamelCase , return_tensors='pt' , padding=lowerCamelCase , truncation=lowerCamelCase ) UpperCamelCase_ : Union[str, Any] = inputs_dict.input_ids.to(args.device ) UpperCamelCase_ : str = inputs_dict.attention_mask.to(args.device ) UpperCamelCase_ : List[Any] = rag_model.generate( # rag_model overwrites generate lowerCamelCase , attention_mask=lowerCamelCase , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCamelCase , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) UpperCamelCase_ : str = rag_model.retriever.generator_tokenizer.batch_decode(lowerCamelCase , skip_special_tokens=lowerCamelCase ) if args.print_predictions: for q, a in zip(lowerCamelCase , lowerCamelCase ): logger.info('Q: {} - A: {}'.format(lowerCamelCase , lowerCamelCase ) ) return answers def __lowercase ( ): UpperCamelCase_ : Optional[int] = argparse.ArgumentParser() parser.add_argument( '--model_type' , choices=['rag_sequence', 'rag_token', 'bart'] , type=lowerCamelCase , help=( 'RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the' ' model_name_or_path' ) , ) parser.add_argument( '--index_name' , default=lowerCamelCase , choices=['exact', 'compressed', 'legacy'] , type=lowerCamelCase , help='RAG model retriever type' , ) parser.add_argument( '--index_path' , default=lowerCamelCase , type=lowerCamelCase , help='Path to the retrieval index' , ) parser.add_argument('--n_docs' , default=5 , type=lowerCamelCase , help='Number of retrieved docs' ) parser.add_argument( '--model_name_or_path' , default=lowerCamelCase , type=lowerCamelCase , required=lowerCamelCase , help='Path to pretrained checkpoints or model identifier from huggingface.co/models' , ) parser.add_argument( '--eval_mode' , choices=['e2e', 'retrieval'] , default='e2e' , type=lowerCamelCase , help=( 'Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates' ' precision@k.' ) , ) parser.add_argument('--k' , default=1 , type=lowerCamelCase , help='k for the precision@k calculation' ) parser.add_argument( '--evaluation_set' , default=lowerCamelCase , type=lowerCamelCase , required=lowerCamelCase , help='Path to a file containing evaluation samples' , ) parser.add_argument( '--gold_data_path' , default=lowerCamelCase , type=lowerCamelCase , required=lowerCamelCase , help='Path to a tab-separated file with gold samples' , ) parser.add_argument( '--gold_data_mode' , default='qa' , type=lowerCamelCase , choices=['qa', 'ans'] , help=( 'Format of the gold data file' 'qa - a single line in the following format: question [tab] answer_list' 'ans - a single line of the gold file contains the expected answer string' ) , ) parser.add_argument( '--predictions_path' , type=lowerCamelCase , default='predictions.txt' , help='Name of the predictions file, to be stored in the checkpoints directory' , ) parser.add_argument( '--eval_all_checkpoints' , action='store_true' , help='Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number' , ) parser.add_argument( '--eval_batch_size' , default=8 , type=lowerCamelCase , help='Batch size per GPU/CPU for evaluation.' , ) parser.add_argument( '--recalculate' , help='Recalculate predictions even if the prediction file exists' , action='store_true' , ) parser.add_argument( '--num_beams' , default=4 , type=lowerCamelCase , help='Number of beams to be used when generating answers' , ) parser.add_argument('--min_length' , default=1 , type=lowerCamelCase , help='Min length of the generated answers' ) parser.add_argument('--max_length' , default=50 , type=lowerCamelCase , help='Max length of the generated answers' ) parser.add_argument( '--print_predictions' , action='store_true' , help='If True, prints predictions while evaluating.' , ) parser.add_argument( '--print_docs' , action='store_true' , help='If True, prints docs retried while generating.' , ) UpperCamelCase_ : Union[str, Any] = parser.parse_args() UpperCamelCase_ : Union[str, Any] = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) return args def __lowercase ( lowerCamelCase : int ): UpperCamelCase_ : Any = {} if args.model_type is None: UpperCamelCase_ : List[Any] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('rag' ): UpperCamelCase_ : Optional[int] = RagTokenForGeneration if args.model_type == 'rag_token' else RagSequenceForGeneration UpperCamelCase_ : Dict = args.n_docs if args.index_name is not None: UpperCamelCase_ : Union[str, Any] = args.index_name if args.index_path is not None: UpperCamelCase_ : str = args.index_path else: UpperCamelCase_ : Tuple = BartForConditionalGeneration UpperCamelCase_ : Optional[int] = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('Evaluate the following checkpoints: %s' , lowerCamelCase ) UpperCamelCase_ : Optional[int] = get_scores if args.eval_mode == 'e2e' else get_precision_at_k UpperCamelCase_ : Optional[int] = evaluate_batch_eae if args.eval_mode == 'e2e' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('Calculating metrics based on an existing predictions file: {}'.format(args.predictions_path ) ) score_fn(lowerCamelCase , args.predictions_path , args.gold_data_path ) continue logger.info('***** Running evaluation for {} *****'.format(lowerCamelCase ) ) logger.info(' Batch size = %d' , args.eval_batch_size ) logger.info(' Predictions will be stored under {}'.format(args.predictions_path ) ) if args.model_type.startswith('rag' ): UpperCamelCase_ : List[str] = RagRetriever.from_pretrained(lowerCamelCase , **lowerCamelCase ) UpperCamelCase_ : List[Any] = model_class.from_pretrained(lowerCamelCase , retriever=lowerCamelCase , **lowerCamelCase ) model.retriever.init_retrieval() else: UpperCamelCase_ : Optional[Any] = model_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) model.to(args.device ) with open(args.evaluation_set , 'r' ) as eval_file, open(args.predictions_path , 'w' ) as preds_file: UpperCamelCase_ : Optional[Any] = [] for line in tqdm(lowerCamelCase ): questions.append(line.strip() ) if len(lowerCamelCase ) == args.eval_batch_size: UpperCamelCase_ : Dict = evaluate_batch_fn(lowerCamelCase , lowerCamelCase , lowerCamelCase ) preds_file.write('\n'.join(lowerCamelCase ) + '\n' ) preds_file.flush() UpperCamelCase_ : Tuple = [] if len(lowerCamelCase ) > 0: UpperCamelCase_ : Optional[int] = evaluate_batch_fn(lowerCamelCase , lowerCamelCase , lowerCamelCase ) preds_file.write('\n'.join(lowerCamelCase ) ) preds_file.flush() score_fn(lowerCamelCase , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": a_ = get_args() main(args)
175
1
'''simple docstring''' from __future__ import annotations class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A, A : List[Any] = text, pattern A, A : Optional[Any] = len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Tuple = [] for i in range(self.textLen - self.patLen + 1 ): A : Optional[int] = self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: A : List[str] = self.match_in_pattern(self.text[mismatch_index] ) A : Optional[int] = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions lowercase : Optional[int] = 'ABAABA' lowercase : Tuple = 'AB' lowercase : Tuple = BoyerMooreSearch(text, pattern) lowercase : Tuple = bms.bad_character_heuristic() if len(positions) == 0: print('No match found') else: print('Pattern found in following positions: ') print(positions)
353
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[int] = logging.get_logger(__name__) lowercase : Tuple = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class A ( __snake_case ): __magic_name__ = '''pix2struct_text_model''' __magic_name__ = ['''past_key_values'''] __magic_name__ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , SCREAMING_SNAKE_CASE=50244 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = vocab_size A : List[str] = hidden_size A : List[Any] = d_kv A : Optional[Any] = d_ff A : Dict = num_layers A : Dict = num_heads A : Optional[int] = relative_attention_num_buckets A : Optional[Any] = relative_attention_max_distance A : Dict = dropout_rate A : Dict = layer_norm_epsilon A : Tuple = initializer_factor A : Union[str, Any] = use_cache A : int = eos_token_id A : List[str] = decoder_start_token_id # for backwards compatibility A : int = dense_act_fn super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , tie_word_embeddings=SCREAMING_SNAKE_CASE , is_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : Optional[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Union[str, Any] = 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(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct_vision_model''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=1e-10 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : List[str] = hidden_size A : Optional[Any] = patch_embed_hidden_size A : Union[str, Any] = d_ff A : Dict = dropout_rate A : str = num_hidden_layers A : Dict = num_attention_heads A : Tuple = initializer_range A : List[str] = initializer_factor A : Union[str, Any] = attention_dropout A : Tuple = layer_norm_eps A : int = dense_act_fn A : Optional[int] = seq_len A : Tuple = relative_attention_num_buckets A : str = relative_attention_max_distance A : Optional[Any] = d_kv @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE ) A, A : int = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": A : Optional[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = '''pix2struct''' __magic_name__ = True def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(tie_word_embeddings=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if text_config is None: A : Dict = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: A : str = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) A : Dict = PixaStructTextConfig(**SCREAMING_SNAKE_CASE ) A : Any = PixaStructVisionConfig(**SCREAMING_SNAKE_CASE ) A : Any = self.text_config.decoder_start_token_id A : Any = self.text_config.pad_token_id A : Dict = self.text_config.eos_token_id A : Union[str, Any] = initializer_factor A : Tuple = initializer_range A : Optional[Any] = self.initializer_range A : int = self.initializer_range A : Tuple = is_vqa @classmethod def __lowerCAmelCase ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Tuple = copy.deepcopy(self.__dict__ ) A : Dict = self.text_config.to_dict() A : int = self.vision_config.to_dict() A : Any = self.__class__.model_type return output
311
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = {'''vocab_file''': '''sentencepiece.bpe.model'''} __snake_case = { '''vocab_file''': { '''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''', '''moussaKam/barthez-orangesum-title''': ( '''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model''' ), }, } __snake_case = { '''moussaKam/mbarthez''': 1024, '''moussaKam/barthez''': 1024, '''moussaKam/barthez-orangesum-title''': 1024, } __snake_case = '''▁''' class lowercase ( A__ ): """simple docstring""" _a = VOCAB_FILES_NAMES _a = PRETRAINED_VOCAB_FILES_MAP _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = ['input_ids', 'attention_mask'] def __init__( self , UpperCamelCase_ , UpperCamelCase_="<s>" , UpperCamelCase_="</s>" , UpperCamelCase_="</s>" , UpperCamelCase_="<s>" , UpperCamelCase_="<unk>" , UpperCamelCase_="<pad>" , UpperCamelCase_="<mask>" , UpperCamelCase_ = None , **UpperCamelCase_ , ): '''simple docstring''' UpperCamelCase__ :Tuple = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token UpperCamelCase__ :Tuple = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase_ , ) UpperCamelCase__ :List[str] = vocab_file UpperCamelCase__ :List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCamelCase_ ) ) UpperCamelCase__ :Optional[int] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} UpperCamelCase__ :Optional[int] = len(self.sp_model ) - 1 UpperCamelCase__ :Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCamelCase__ :Optional[int] = [self.cls_token_id] UpperCamelCase__ :List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] return [1] + ([0] * len(UpperCamelCase_ )) + [1, 1] + ([0] * len(UpperCamelCase_ )) + [1] def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' UpperCamelCase__ :Optional[Any] = [self.sep_token_id] UpperCamelCase__ :int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCAmelCase__ ( self ): '''simple docstring''' return len(self.sp_model ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Dict = {self.convert_ids_to_tokens(UpperCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' return self.sp_model.encode(UpperCamelCase_ , out_type=UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCamelCase__ :List[Any] = self.sp_model.PieceToId(UpperCamelCase_ ) return spm_id if spm_id else self.unk_token_id def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = [] UpperCamelCase__ :Optional[int] = '''''' UpperCamelCase__ :str = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCamelCase_ ) + token UpperCamelCase__ :List[str] = True UpperCamelCase__ :Any = [] else: current_sub_tokens.append(UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = False out_string += self.sp_model.decode(UpperCamelCase_ ) return out_string.strip() def __getstate__( self ): '''simple docstring''' UpperCamelCase__ :Dict = self.__dict__.copy() UpperCamelCase__ :str = None return state def __setstate__( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[str] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCamelCase__ :List[str] = {} UpperCamelCase__ :Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' if not os.path.isdir(UpperCamelCase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCamelCase__ :Optional[int] = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase_ , '''wb''' ) as fi: UpperCamelCase__ :Optional[Any] = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase_ ) return (out_vocab_file,)
97
'''simple docstring''' from pathlib import Path import fire from tqdm import tqdm def a ( __a="ro" , __a="en" , __a="wmt16" , __a=None ) -> None: '''simple docstring''' try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError('''run pip install datasets''' ) UpperCamelCase__ :int = f'''{src_lang}-{tgt_lang}''' print(f'''Converting {dataset}-{pair}''' ) UpperCamelCase__ :Tuple = datasets.load_dataset(__a , __a ) if save_dir is None: UpperCamelCase__ :Any = f'''{dataset}-{pair}''' UpperCamelCase__ :Dict = Path(__a ) save_dir.mkdir(exist_ok=__a ) for split in ds.keys(): print(f'''Splitting {split} with {ds[split].num_rows} records''' ) # to save to val.source, val.target like summary datasets UpperCamelCase__ :Dict = '''val''' if split == '''validation''' else split UpperCamelCase__ :List[Any] = save_dir.joinpath(f'''{fn}.source''' ) UpperCamelCase__ :int = save_dir.joinpath(f'''{fn}.target''' ) UpperCamelCase__ :Union[str, Any] = src_path.open('''w+''' ) UpperCamelCase__ :Tuple = tgt_path.open('''w+''' ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): UpperCamelCase__ :Union[str, Any] = x['''translation'''] src_fp.write(ex[src_lang] + '''\n''' ) tgt_fp.write(ex[tgt_lang] + '''\n''' ) print(f'''Saved {dataset} dataset to {save_dir}''' ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
97
1
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging lowerCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( _lowerCamelCase): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): super().__init__() if hasattr(scheduler.config , 'steps_offset' ) and scheduler.config.steps_offset != 1: __lowerCAmelCase : Optional[Any] = ( f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " 'to update the config accordingly as leaving `steps_offset` might led to incorrect results' ' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,' ' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`' ' file' ) deprecate('steps_offset!=1' , '1.0.0' , _SCREAMING_SNAKE_CASE , standard_warn=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = dict(scheduler.config ) __lowerCAmelCase : str = 1 __lowerCAmelCase : Tuple = FrozenDict(_SCREAMING_SNAKE_CASE ) if hasattr(scheduler.config , 'skip_prk_steps' ) and scheduler.config.skip_prk_steps is False: __lowerCAmelCase : List[Any] = ( f"The configuration file of this scheduler: {scheduler} has not set the configuration" ' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make' ' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to' ' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face' ' Hub, it would be very nice if you could open a Pull request for the' ' `scheduler/scheduler_config.json` file' ) deprecate('skip_prk_steps not set' , '1.0.0' , _SCREAMING_SNAKE_CASE , standard_warn=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = dict(scheduler.config ) __lowerCAmelCase : List[str] = True __lowerCAmelCase : Union[str, Any] = FrozenDict(_SCREAMING_SNAKE_CASE ) if safety_checker is None: logger.warning( f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" ' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered' ' results in services or applications open to the public. Both the diffusers team and Hugging Face' ' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling' ' it only for use-cases that involve analyzing network behavior or auditing its results. For more' ' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .' ) self.register_modules( segmentation_model=_SCREAMING_SNAKE_CASE , segmentation_processor=_SCREAMING_SNAKE_CASE , vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __lowerCAmelCase : Any = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): self.enable_attention_slicing(_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __lowerCAmelCase : Any = torch.device('cuda' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCamelCase ( self ): if self.device != torch.device('meta' ) or not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_SCREAMING_SNAKE_CASE , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 5_12 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : List[str] = self.segmentation_processor( text=[text] , images=[image] , padding='max_length' , return_tensors='pt' ).to(self.device ) __lowerCAmelCase : int = self.segmentation_model(**_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : str = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __lowerCAmelCase : Tuple = self.numpy_to_pil(_SCREAMING_SNAKE_CASE )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __lowerCAmelCase : Optional[int] = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , )
182
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """facebook/nllb-moe-54B""": """https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json""", } class A__ ( _lowerCamelCase): A_ : str = 'nllb-moe' A_ : Optional[Any] = ['past_key_values'] A_ : List[str] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , _SCREAMING_SNAKE_CASE=12_81_12 , _SCREAMING_SNAKE_CASE=10_24 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=40_96 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=40_96 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.05 , _SCREAMING_SNAKE_CASE=0.05 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=10_24 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="float32" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1_28 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=0.001 , _SCREAMING_SNAKE_CASE=0.001 , _SCREAMING_SNAKE_CASE="all" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=0.2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : int = vocab_size __lowerCAmelCase : str = max_position_embeddings __lowerCAmelCase : Dict = d_model __lowerCAmelCase : Tuple = encoder_ffn_dim __lowerCAmelCase : Optional[Any] = encoder_layers __lowerCAmelCase : Any = encoder_attention_heads __lowerCAmelCase : Tuple = decoder_ffn_dim __lowerCAmelCase : Dict = decoder_layers __lowerCAmelCase : str = decoder_attention_heads __lowerCAmelCase : str = dropout __lowerCAmelCase : List[str] = attention_dropout __lowerCAmelCase : Optional[int] = activation_dropout __lowerCAmelCase : List[Any] = activation_function __lowerCAmelCase : List[str] = init_std __lowerCAmelCase : Union[str, Any] = encoder_layerdrop __lowerCAmelCase : List[Any] = decoder_layerdrop __lowerCAmelCase : Optional[int] = use_cache __lowerCAmelCase : Optional[Any] = encoder_layers __lowerCAmelCase : Optional[int] = scale_embedding # scale factor will be sqrt(d_model) if True __lowerCAmelCase : Union[str, Any] = router_z_loss_coef __lowerCAmelCase : Optional[Any] = router_aux_loss_coef __lowerCAmelCase : int = decoder_sparse_step __lowerCAmelCase : str = encoder_sparse_step __lowerCAmelCase : Tuple = num_experts __lowerCAmelCase : Dict = expert_capacity __lowerCAmelCase : Union[str, Any] = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}" ) __lowerCAmelCase : Union[str, Any] = router_dtype __lowerCAmelCase : Any = router_ignore_padding_tokens __lowerCAmelCase : str = batch_prioritized_routing __lowerCAmelCase : Tuple = second_expert_policy __lowerCAmelCase : List[str] = normalize_router_prob_before_dropping __lowerCAmelCase : Dict = moe_eval_capacity_token_fraction __lowerCAmelCase : Union[str, Any] = moe_token_dropout __lowerCAmelCase : List[Any] = output_router_logits super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , is_encoder_decoder=_SCREAMING_SNAKE_CASE , decoder_start_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
182
1
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowerCAmelCase_ = logging.get_logger(__name__) @add_end_docstrings(_lowerCamelCase ) class _A ( _lowerCamelCase ): def __init__( self : Optional[int] , **_A : Dict ) -> int: """simple docstring""" super().__init__(**_A ) if self.framework != "pt": raise ValueError(f"""The {self.__class__} is only available in PyTorch.""" ) # No specific FOR_XXX available yet def __call__( self : Dict , _A : Union[np.ndarray, bytes, str] , **_A : Optional[int] ) -> Optional[Any]: """simple docstring""" return super().__call__(_A , **_A ) def __a ( self : str , **_A : Dict ) -> Any: """simple docstring""" lowercase : str = {} if "candidate_labels" in kwargs: lowercase : Optional[Any] = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: lowercase : Union[str, Any] = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def __a ( self : Optional[int] , _A : str , _A : Union[str, Any]=None , _A : str="This is a sound of {}." ) -> Optional[Any]: """simple docstring""" if isinstance(_A , _A ): if audio.startswith('''http://''' ) or audio.startswith('''https://''' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png lowercase : int = requests.get(_A ).content else: with open(_A , '''rb''' ) as f: lowercase : List[Any] = f.read() if isinstance(_A , _A ): lowercase : List[str] = ffmpeg_read(_A , self.feature_extractor.sampling_rate ) if not isinstance(_A , np.ndarray ): raise ValueError('''We expect a numpy ndarray as input''' ) if len(audio.shape ) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''' ) lowercase : Optional[Any] = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''' ) lowercase : List[str] = candidate_labels lowercase : Union[str, Any] = [hypothesis_template.format(_A ) for x in candidate_labels] lowercase : Tuple = self.tokenizer(_A , return_tensors=self.framework , padding=_A ) lowercase : Tuple = [text_inputs] return inputs def __a ( self : Optional[int] , _A : Union[str, Any] ) -> Dict: """simple docstring""" lowercase : int = model_inputs.pop('''candidate_labels''' ) lowercase : Optional[Any] = model_inputs.pop('''text_inputs''' ) if isinstance(text_inputs[0] , _A ): lowercase : Any = text_inputs[0] else: # Batching case. lowercase : Tuple = text_inputs[0][0] lowercase : Dict = self.model(**_A , **_A ) lowercase : Any = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def __a ( self : str , _A : Tuple ) -> List[Any]: """simple docstring""" lowercase : Dict = model_outputs.pop('''candidate_labels''' ) lowercase : Any = model_outputs['''logits'''][0] if self.framework == "pt": lowercase : Optional[Any] = logits.softmax(dim=0 ) lowercase : Dict = probs.tolist() else: raise ValueError('''`tf` framework not supported.''' ) lowercase : Dict = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(_A , _A ) , key=lambda _A : -x[0] ) ] return result
308
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase_ = logging.get_logger(__name__) def snake_case( __magic_name__ ) -> List[List[ImageInput]]: '''simple docstring''' if isinstance(__magic_name__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__magic_name__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__magic_name__ ): return [[videos]] raise ValueError(F"""Could not make batched video from {videos}""" ) class _A ( _lowerCamelCase ): _UpperCamelCase : str = ['''pixel_values'''] def __init__( self : List[str] , _A : bool = True , _A : Dict[str, int] = None , _A : PILImageResampling = PILImageResampling.BILINEAR , _A : bool = True , _A : Dict[str, int] = None , _A : bool = True , _A : Union[int, float] = 1 / 255 , _A : bool = True , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[float, List[float]]] = None , **_A : Optional[int] , ) -> None: """simple docstring""" super().__init__(**_A ) lowercase : List[Any] = size if size is not None else {'''shortest_edge''': 224} lowercase : Tuple = get_size_dict(_A , default_to_square=_A ) lowercase : Dict = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} lowercase : Dict = get_size_dict(_A , param_name='''crop_size''' ) lowercase : List[str] = do_resize lowercase : Optional[Any] = size lowercase : List[str] = do_center_crop lowercase : List[Any] = crop_size lowercase : str = resample lowercase : Tuple = do_rescale lowercase : Any = rescale_factor lowercase : Tuple = do_normalize lowercase : List[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowercase : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def __a ( self : Union[str, Any] , _A : np.ndarray , _A : Dict[str, int] , _A : PILImageResampling = PILImageResampling.BILINEAR , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Any , ) -> np.ndarray: """simple docstring""" lowercase : Tuple = get_size_dict(_A , default_to_square=_A ) if "shortest_edge" in size: lowercase : Dict = get_resize_output_image_size(_A , size['''shortest_edge'''] , default_to_square=_A ) elif "height" in size and "width" in size: lowercase : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(f"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def __a ( self : Dict , _A : np.ndarray , _A : Dict[str, int] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Any , ) -> np.ndarray: """simple docstring""" lowercase : Optional[Any] = get_size_dict(_A ) if "height" not in size or "width" not in size: raise ValueError(f"""Size must have 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(_A , size=(size['''height'''], size['''width''']) , data_format=_A , **_A ) def __a ( self : Union[str, Any] , _A : np.ndarray , _A : Union[int, float] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Tuple , ) -> Union[str, Any]: """simple docstring""" return rescale(_A , scale=_A , data_format=_A , **_A ) def __a ( self : str , _A : np.ndarray , _A : Union[float, List[float]] , _A : Union[float, List[float]] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Union[str, Any] , ) -> np.ndarray: """simple docstring""" return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def __a ( self : int , _A : ImageInput , _A : bool = None , _A : Dict[str, int] = None , _A : PILImageResampling = None , _A : bool = None , _A : Dict[str, int] = None , _A : bool = None , _A : float = None , _A : bool = None , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[float, List[float]]] = None , _A : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: """simple docstring""" if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. lowercase : Union[str, Any] = to_numpy_array(_A ) if do_resize: lowercase : List[Any] = self.resize(image=_A , size=_A , resample=_A ) if do_center_crop: lowercase : Optional[int] = self.center_crop(_A , size=_A ) if do_rescale: lowercase : Tuple = self.rescale(image=_A , scale=_A ) if do_normalize: lowercase : Union[str, Any] = self.normalize(image=_A , mean=_A , std=_A ) lowercase : Any = to_channel_dimension_format(_A , _A ) return image def __a ( self : List[Any] , _A : ImageInput , _A : bool = None , _A : Dict[str, int] = None , _A : PILImageResampling = None , _A : bool = None , _A : Dict[str, int] = None , _A : bool = None , _A : float = None , _A : bool = None , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[str, TensorType]] = None , _A : ChannelDimension = ChannelDimension.FIRST , **_A : Union[str, Any] , ) -> PIL.Image.Image: """simple docstring""" lowercase : str = do_resize if do_resize is not None else self.do_resize lowercase : Optional[Any] = resample if resample is not None else self.resample lowercase : List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase : str = do_rescale if do_rescale is not None else self.do_rescale lowercase : int = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase : List[str] = do_normalize if do_normalize is not None else self.do_normalize lowercase : Optional[int] = image_mean if image_mean is not None else self.image_mean lowercase : Optional[Any] = image_std if image_std is not None else self.image_std lowercase : str = size if size is not None else self.size lowercase : Any = get_size_dict(_A , default_to_square=_A ) lowercase : Optional[int] = crop_size if crop_size is not None else self.crop_size lowercase : str = get_size_dict(_A , param_name='''crop_size''' ) if not valid_images(_A ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) lowercase : Union[str, Any] = make_batched(_A ) lowercase : Dict = [ [ self._preprocess_image( image=_A , do_resize=_A , size=_A , resample=_A , do_center_crop=_A , crop_size=_A , do_rescale=_A , rescale_factor=_A , do_normalize=_A , image_mean=_A , image_std=_A , data_format=_A , ) for img in video ] for video in videos ] lowercase : Tuple = {'''pixel_values''': videos} return BatchFeature(data=_A , tensor_type=_A )
308
1
"""simple docstring""" def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): if index == r: for j in range(UpperCamelCase_ ): print(data[j] , end=""" """ ) print(""" """ ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location __SCREAMING_SNAKE_CASE = arr[i] combination_util(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , index + 1 , UpperCamelCase_ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): # A temporary array to store all combination one by one __SCREAMING_SNAKE_CASE = [0] * r # Print all combination using temporary array 'data[]' combination_util(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , 0 , UpperCamelCase_ , 0 ) if __name__ == "__main__": # Driver code to check the function above __magic_name__ = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
359
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __magic_name__ = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( __a , unittest.TestCase ): """simple docstring""" __lowercase : Union[str, Any] = XGLMTokenizer __lowercase : int = XGLMTokenizerFast __lowercase : Optional[Any] = True __lowercase : str = True def snake_case_ ( self): super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = XGLMTokenizer(lowerCAmelCase__ , keep_accents=lowerCAmelCase__) tokenizer.save_pretrained(self.tmpdirname) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = """<pad>""" __SCREAMING_SNAKE_CASE = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__) , lowerCAmelCase__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__) , lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , """<s>""") self.assertEqual(vocab_keys[1] , """<pad>""") self.assertEqual(len(lowerCAmelCase__) , 1_0_0_8) def snake_case_ ( self): self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = XGLMTokenizer(lowerCAmelCase__ , keep_accents=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""") self.assertListEqual(lowerCAmelCase__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase__) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""") self.assertListEqual( lowerCAmelCase__ , [ 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""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(lowerCAmelCase__) self.assertListEqual( lowerCAmelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(lowerCAmelCase__) self.assertListEqual( lowerCAmelCase__ , [ 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>""", """.""", ] , ) @cached_property def snake_case_ ( self): return XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") def snake_case_ ( self): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCAmelCase__ , f.name) __SCREAMING_SNAKE_CASE = XGLMTokenizer(f.name , keep_accents=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = pickle.dumps(lowerCAmelCase__) pickle.loads(lowerCAmelCase__) def snake_case_ ( self): if not self.test_rust_tokenizer: return __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = """I was born in 92000, and this is falsé.""" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(lowerCAmelCase__) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = rust_tokenizer.encode(lowerCAmelCase__) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__) @slow def snake_case_ ( self): __SCREAMING_SNAKE_CASE = """Hello World!""" __SCREAMING_SNAKE_CASE = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(lowerCAmelCase__ , self.big_tokenizer.encode(lowerCAmelCase__)) @slow def snake_case_ ( self): __SCREAMING_SNAKE_CASE = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth""" ) # fmt: off __SCREAMING_SNAKE_CASE = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(lowerCAmelCase__ , self.big_tokenizer.encode(lowerCAmelCase__)) @slow def snake_case_ ( self): # fmt: off __SCREAMING_SNAKE_CASE = { """input_ids""": [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase__ , model_name="""facebook/xglm-564M""" , padding=lowerCAmelCase__ , )
255
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _A : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Optional[Any] = ["MLukeTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys _A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
142
'''simple docstring''' import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed _lowerCamelCase : Optional[int] = logging.getLogger(__name__) def __lowerCamelCase ( A__=2 , A__=3 , A__=16 , A__ = 10 , A__ = 2 ) -> int: """simple docstring""" def get_dataset(A__ ): UpperCamelCase = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(A__ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) UpperCamelCase = get_dataset(A__ ) UpperCamelCase = get_dataset(A__ ) UpperCamelCase = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 ) UpperCamelCase = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 ) return (train_dataloader, valid_dataloader) def __lowerCamelCase ( A__ , A__ , A__ , A__ , A__ , A__=None ) -> int: """simple docstring""" UpperCamelCase = [] for epoch in range(A__ ): # Train quickly model.train() for batch in dataloader: UpperCamelCase , UpperCamelCase = batch UpperCamelCase = model(A__ ) UpperCamelCase = torch.nn.functional.mse_loss(A__ , A__ ) accelerator.backward(A__ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class SCREAMING_SNAKE_CASE ( nn.Module ): """simple docstring""" def __init__( self : Tuple ): """simple docstring""" super().__init__() UpperCamelCase = nn.Parameter(torch.randn(1 ) ) UpperCamelCase = nn.Parameter(torch.randn(1 ) ) def A ( self : str , UpperCamelCase__ : Dict ): """simple docstring""" return x * self.a + self.b class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def A ( self : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) UpperCamelCase = DummyModel() UpperCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) UpperCamelCase , UpperCamelCase = dummy_dataloaders() UpperCamelCase = ProjectConfiguration(total_limit=1 , project_dir=UpperCamelCase__ , automatic_checkpoint_naming=UpperCamelCase__ ) # Train baseline UpperCamelCase = Accelerator(project_config=UpperCamelCase__ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def A ( self : Optional[int] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) UpperCamelCase = DummyModel() UpperCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) UpperCamelCase , UpperCamelCase = dummy_dataloaders() # Train baseline UpperCamelCase = Accelerator() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save initial UpperCamelCase = os.path.join(UpperCamelCase__ , 'initial' ) accelerator.save_state(UpperCamelCase__ ) ((UpperCamelCase) , (UpperCamelCase)) = model.a.item(), model.b.item() UpperCamelCase = optimizer.state_dict() UpperCamelCase = train(3 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCamelCase) , (UpperCamelCase)) = model.a.item(), model.b.item() UpperCamelCase = optimizer.state_dict() # Train partially set_seed(4_2 ) UpperCamelCase = DummyModel() UpperCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) UpperCamelCase , UpperCamelCase = dummy_dataloaders() UpperCamelCase = Accelerator() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) accelerator.load_state(UpperCamelCase__ ) ((UpperCamelCase) , (UpperCamelCase)) = model.a.item(), model.b.item() UpperCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = train(2 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save everything UpperCamelCase = os.path.join(UpperCamelCase__ , 'checkpoint' ) accelerator.save_state(UpperCamelCase__ ) # Load everything back in and make sure all states work accelerator.load_state(UpperCamelCase__ ) test_rands += train(1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCamelCase) , (UpperCamelCase)) = model.a.item(), model.b.item() UpperCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def A ( self : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) UpperCamelCase = DummyModel() UpperCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) UpperCamelCase , UpperCamelCase = dummy_dataloaders() UpperCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase__ ) # Train baseline UpperCamelCase = Accelerator(project_dir=UpperCamelCase__ , project_config=UpperCamelCase__ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save initial accelerator.save_state() ((UpperCamelCase) , (UpperCamelCase)) = model.a.item(), model.b.item() UpperCamelCase = optimizer.state_dict() UpperCamelCase = train(3 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCamelCase) , (UpperCamelCase)) = model.a.item(), model.b.item() UpperCamelCase = optimizer.state_dict() # Train partially set_seed(4_2 ) UpperCamelCase = DummyModel() UpperCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) UpperCamelCase , UpperCamelCase = dummy_dataloaders() UpperCamelCase = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=UpperCamelCase__ ) UpperCamelCase = Accelerator(project_dir=UpperCamelCase__ , project_config=UpperCamelCase__ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) accelerator.load_state(os.path.join(UpperCamelCase__ , 'checkpoints' , 'checkpoint_0' ) ) ((UpperCamelCase) , (UpperCamelCase)) = model.a.item(), model.b.item() UpperCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = train(2 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(UpperCamelCase__ , 'checkpoints' , 'checkpoint_1' ) ) test_rands += train(1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCamelCase) , (UpperCamelCase)) = model.a.item(), model.b.item() UpperCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def A ( self : Optional[int] ): """simple docstring""" UpperCamelCase = torch.tensor([1, 2, 3] ) UpperCamelCase = torch.tensor([2, 3, 4] ) UpperCamelCase = DummyModel() UpperCamelCase = torch.optim.Adam(net.parameters() ) UpperCamelCase = Accelerator() with self.assertRaises(UpperCamelCase__ ) as ve: accelerator.register_for_checkpointing(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = str(ve.exception ) self.assertTrue('Item at index 0' in message ) self.assertTrue('Item at index 1' in message ) self.assertFalse('Item at index 2' in message ) self.assertFalse('Item at index 3' in message ) def A ( self : Dict ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) UpperCamelCase = DummyModel() UpperCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) UpperCamelCase = torch.optim.lr_scheduler.StepLR(UpperCamelCase__ , step_size=1 , gamma=0.9_9 ) UpperCamelCase , UpperCamelCase = dummy_dataloaders() UpperCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase__ ) # Train baseline UpperCamelCase = Accelerator(project_dir=UpperCamelCase__ , project_config=UpperCamelCase__ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save initial accelerator.save_state() UpperCamelCase = scheduler.state_dict() train(3 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) self.assertNotEqual(UpperCamelCase__ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(UpperCamelCase__ , 'checkpoints' , 'checkpoint_0' ) ) self.assertEqual(UpperCamelCase__ , scheduler.state_dict() ) def A ( self : List[str] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(4_2 ) UpperCamelCase = DummyModel() UpperCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase__ , total_limit=2 ) # Train baseline UpperCamelCase = Accelerator(project_dir=UpperCamelCase__ , project_config=UpperCamelCase__ ) UpperCamelCase = accelerator.prepare(UpperCamelCase__ ) # Save 3 states: for _ in range(1_1 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(UpperCamelCase__ , 'checkpoints' , 'checkpoint_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , 'checkpoints' , 'checkpoint_9' ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , 'checkpoints' , 'checkpoint_10' ) ) ) @require_cuda def A ( self : Dict ): """simple docstring""" UpperCamelCase = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase : Optional[int] = "/tmp/accelerate/state_checkpointing" _lowerCamelCase : Union[str, Any] = DummyModel() _lowerCamelCase : Optional[Any] = torch.optim.Adam(params=model.parameters(), lr=1e-3) _lowerCamelCase : List[Any] = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) _lowerCamelCase ,_lowerCamelCase : Tuple = dummy_dataloaders() _lowerCamelCase : List[Any] = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline _lowerCamelCase : Any = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="no") if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase : Union[str, Any] = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) _lowerCamelCase ,_lowerCamelCase : Tuple = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: _lowerCamelCase : Any = group["params"][0].device break assert param_device.type == accelerator.device.type _lowerCamelCase : Tuple = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="cpu") for group in optimizer.param_groups: _lowerCamelCase : Optional[Any] = group["params"][0].device break assert ( param_device.type == torch.device("cpu").type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="on_device") for group in optimizer.param_groups: _lowerCamelCase : Dict = group["params"][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match="Unsupported optimizer map location passed"): accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="invalid") accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
28
0
'''simple docstring''' import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask lowerCamelCase : List[str] = logging.getLogger(__name__) class A__ ( A__ ): A__ = 'token-classification' def __init__( self : Optional[Any] , _a : Optional[Any] ) -> Tuple: '''simple docstring''' if type(_a ) == dict: _SCREAMING_SNAKE_CASE =Namespace(**_a ) _SCREAMING_SNAKE_CASE =import_module('tasks' ) try: _SCREAMING_SNAKE_CASE =getattr(_a , hparams.task_type ) _SCREAMING_SNAKE_CASE =token_classification_task_clazz() except AttributeError: raise ValueError( f"Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. " f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}" ) _SCREAMING_SNAKE_CASE =self.token_classification_task.get_labels(hparams.labels ) _SCREAMING_SNAKE_CASE =CrossEntropyLoss().ignore_index super().__init__(_a , len(self.labels ) , self.mode ) def A ( self : List[Any] , **_a : Optional[Any] ) -> int: '''simple docstring''' return self.model(**_a ) def A ( self : Any , _a : Union[str, Any] , _a : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE ={'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type != "distilbert": _SCREAMING_SNAKE_CASE =( batch[2] if self.config.model_type in ['bert', 'xlnet'] else None ) # XLM and RoBERTa don"t use token_type_ids _SCREAMING_SNAKE_CASE =self(**_a ) _SCREAMING_SNAKE_CASE =outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def A ( self : List[str] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.hparams for mode in ["train", "dev", "test"]: _SCREAMING_SNAKE_CASE =self._feature_file(_a ) if os.path.exists(_a ) and not args.overwrite_cache: logger.info('Loading features from cached file %s' , _a ) _SCREAMING_SNAKE_CASE =torch.load(_a ) else: logger.info('Creating features from dataset file at %s' , args.data_dir ) _SCREAMING_SNAKE_CASE =self.token_classification_task.read_examples_from_file(args.data_dir , _a ) _SCREAMING_SNAKE_CASE =self.token_classification_task.convert_examples_to_features( _a , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ['xlnet'] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ['xlnet'] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=_a , pad_on_left=bool(self.config.model_type in ['xlnet'] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info('Saving features into cached file %s' , _a ) torch.save(_a , _a ) def A ( self : Optional[int] , _a : int , _a : int , _a : bool = False ) -> DataLoader: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._feature_file(_a ) logger.info('Loading features from cached file %s' , _a ) _SCREAMING_SNAKE_CASE =torch.load(_a ) _SCREAMING_SNAKE_CASE =torch.tensor([f.input_ids for f in features] , dtype=torch.long ) _SCREAMING_SNAKE_CASE =torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: _SCREAMING_SNAKE_CASE =torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: _SCREAMING_SNAKE_CASE =torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) _SCREAMING_SNAKE_CASE =torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(_a , _a , _a , _a ) , batch_size=_a ) def A ( self : str , _a : List[Any] , _a : Dict ) -> Dict: '''simple docstring''' """Compute validation""" "" _SCREAMING_SNAKE_CASE ={'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type != "distilbert": _SCREAMING_SNAKE_CASE =( batch[2] if self.config.model_type in ['bert', 'xlnet'] else None ) # XLM and RoBERTa don"t use token_type_ids _SCREAMING_SNAKE_CASE =self(**_a ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =outputs[:2] _SCREAMING_SNAKE_CASE =logits.detach().cpu().numpy() _SCREAMING_SNAKE_CASE =inputs['labels'].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def A ( self : Optional[Any] , _a : Tuple ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =torch.stack([x['val_loss'] for x in outputs] ).mean() _SCREAMING_SNAKE_CASE =np.concatenate([x['pred'] for x in outputs] , axis=0 ) _SCREAMING_SNAKE_CASE =np.argmax(_a , axis=2 ) _SCREAMING_SNAKE_CASE =np.concatenate([x['target'] for x in outputs] , axis=0 ) _SCREAMING_SNAKE_CASE =dict(enumerate(self.labels ) ) _SCREAMING_SNAKE_CASE =[[] for _ in range(out_label_ids.shape[0] )] _SCREAMING_SNAKE_CASE =[[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) _SCREAMING_SNAKE_CASE ={ 'val_loss': val_loss_mean, 'accuracy_score': accuracy_score(_a , _a ), 'precision': precision_score(_a , _a ), 'recall': recall_score(_a , _a ), 'f1': fa_score(_a , _a ), } _SCREAMING_SNAKE_CASE =dict(results.items() ) _SCREAMING_SNAKE_CASE =results return ret, preds_list, out_label_list def A ( self : List[Any] , _a : Optional[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._eval_end(_a ) _SCREAMING_SNAKE_CASE =ret['log'] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def A ( self : List[str] , _a : List[str] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._eval_end(_a ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 _SCREAMING_SNAKE_CASE =ret['log'] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def A ( _a : Tuple , _a : Union[str, Any] ) -> Any: '''simple docstring''' BaseTransformer.add_model_specific_args(_a , _a ) parser.add_argument( '--task_type' , default='NER' , type=_a , help='Task type to fine tune in training (e.g. NER, POS, etc)' ) parser.add_argument( '--max_seq_length' , default=128 , type=_a , help=( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) , ) parser.add_argument( '--labels' , default='' , type=_a , help='Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.' , ) parser.add_argument( '--gpus' , default=0 , type=_a , help='The number of GPUs allocated for this, it is by default 0 meaning none' , ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) return parser if __name__ == "__main__": lowerCamelCase : Tuple = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) lowerCamelCase : Union[str, Any] = NERTransformer.add_model_specific_args(parser, os.getcwd()) lowerCamelCase : Union[str, Any] = parser.parse_args() lowerCamelCase : str = NERTransformer(args) lowerCamelCase : List[Any] = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 lowerCamelCase : Dict = sorted(glob.glob(os.path.join(args.output_dir, "checkpoint-epoch=*.ckpt"), recursive=True)) lowerCamelCase : List[Any] = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
114
'''simple docstring''' from ..utils import DummyObject, requires_backends class A__ ( metaclass=A__ ): A__ = ['note_seq'] def __init__( self : List[str] , *_a : Any , **_a : Dict ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['note_seq'] ) @classmethod def A ( cls : Any , *_a : str , **_a : List[Any] ) -> List[str]: '''simple docstring''' requires_backends(cls , ['note_seq'] ) @classmethod def A ( cls : int , *_a : Optional[Any] , **_a : Optional[int] ) -> Tuple: '''simple docstring''' requires_backends(cls , ['note_seq'] )
114
1
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a : Tuple = logging.get_logger(__name__) a : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } a : List[str] = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } a : str = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase_ (): """simple docstring""" UpperCAmelCase_: Dict = ( list(range(ord("""!""" ) , ord("""~""" ) + 1 ) ) + list(range(ord("""¡""" ) , ord("""¬""" ) + 1 ) ) + list(range(ord("""®""" ) , ord("""ÿ""" ) + 1 ) ) ) UpperCAmelCase_: List[Any] = bs[:] UpperCAmelCase_: Optional[int] = 0 for b in range(2**8 ): if b not in bs: bs.append(_snake_case ) cs.append(2**8 + n ) n += 1 UpperCAmelCase_: List[Any] = [chr(_snake_case ) for n in cs] return dict(zip(_snake_case , _snake_case ) ) def lowerCAmelCase_ (lowerCAmelCase__: Tuple ): """simple docstring""" UpperCAmelCase_: Union[str, Any] = set() UpperCAmelCase_: Optional[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCAmelCase_: Tuple = char return pairs class _a ( a__ ): A = VOCAB_FILES_NAMES A = PRETRAINED_VOCAB_FILES_MAP A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A = ['''input_ids''', '''attention_mask'''] def __init__(self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_="replace", SCREAMING_SNAKE_CASE_="<s>", SCREAMING_SNAKE_CASE_="</s>", SCREAMING_SNAKE_CASE_="</s>", SCREAMING_SNAKE_CASE_="<s>", SCREAMING_SNAKE_CASE_="<unk>", SCREAMING_SNAKE_CASE_="<pad>", SCREAMING_SNAKE_CASE_="<mask>", SCREAMING_SNAKE_CASE_=False, **SCREAMING_SNAKE_CASE_, ) -> Union[str, Any]: UpperCAmelCase_: List[str] = AddedToken(SCREAMING_SNAKE_CASE__, lstrip=SCREAMING_SNAKE_CASE__, rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else bos_token UpperCAmelCase_: Dict = AddedToken(SCREAMING_SNAKE_CASE__, lstrip=SCREAMING_SNAKE_CASE__, rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else eos_token UpperCAmelCase_: str = AddedToken(SCREAMING_SNAKE_CASE__, lstrip=SCREAMING_SNAKE_CASE__, rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else sep_token UpperCAmelCase_: Any = AddedToken(SCREAMING_SNAKE_CASE__, lstrip=SCREAMING_SNAKE_CASE__, rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else cls_token UpperCAmelCase_: Union[str, Any] = AddedToken(SCREAMING_SNAKE_CASE__, lstrip=SCREAMING_SNAKE_CASE__, rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else unk_token UpperCAmelCase_: Any = AddedToken(SCREAMING_SNAKE_CASE__, lstrip=SCREAMING_SNAKE_CASE__, rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase_: int = AddedToken(SCREAMING_SNAKE_CASE__, lstrip=SCREAMING_SNAKE_CASE__, rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE__, bos_token=SCREAMING_SNAKE_CASE__, eos_token=SCREAMING_SNAKE_CASE__, unk_token=SCREAMING_SNAKE_CASE__, sep_token=SCREAMING_SNAKE_CASE__, cls_token=SCREAMING_SNAKE_CASE__, pad_token=SCREAMING_SNAKE_CASE__, mask_token=SCREAMING_SNAKE_CASE__, add_prefix_space=SCREAMING_SNAKE_CASE__, **SCREAMING_SNAKE_CASE__, ) with open(SCREAMING_SNAKE_CASE__, encoding="""utf-8""" ) as vocab_handle: UpperCAmelCase_: int = json.load(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_: Dict = {v: k for k, v in self.encoder.items()} UpperCAmelCase_: List[Any] = errors # how to handle errors in decoding UpperCAmelCase_: List[str] = bytes_to_unicode() UpperCAmelCase_: List[str] = {v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE__, encoding="""utf-8""" ) as merges_handle: UpperCAmelCase_: Dict = merges_handle.read().split("""\n""" )[1:-1] UpperCAmelCase_: Union[str, Any] = [tuple(merge.split() ) for merge in bpe_merges] UpperCAmelCase_: Optional[Any] = dict(zip(SCREAMING_SNAKE_CASE__, range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) UpperCAmelCase_: Optional[int] = {} UpperCAmelCase_: List[str] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions UpperCAmelCase_: Tuple = re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def __snake_case (self ) -> int: return len(self.encoder ) def __snake_case (self ) -> int: return dict(self.encoder, **self.added_tokens_encoder ) def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Tuple: if token in self.cache: return self.cache[token] UpperCAmelCase_: int = tuple(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_: Union[str, Any] = get_pairs(SCREAMING_SNAKE_CASE__ ) if not pairs: return token while True: UpperCAmelCase_: Optional[int] = min(SCREAMING_SNAKE_CASE__, key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE__, float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break UpperCAmelCase_: List[Any] = bigram UpperCAmelCase_: Any = [] UpperCAmelCase_: Optional[Any] = 0 while i < len(SCREAMING_SNAKE_CASE__ ): try: UpperCAmelCase_: Tuple = word.index(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCAmelCase_: Dict = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCAmelCase_: str = tuple(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_: List[Any] = new_word if len(SCREAMING_SNAKE_CASE__ ) == 1: break else: UpperCAmelCase_: Tuple = get_pairs(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_: List[str] = """ """.join(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_: Union[str, Any] = word return word def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCAmelCase_: Dict = [] for token in re.findall(self.pat, SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_: List[Any] = """""".join( self.byte_encoder[b] for b in token.encode("""utf-8""" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE__ ).split(""" """ ) ) return bpe_tokens def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Optional[int]: return self.encoder.get(SCREAMING_SNAKE_CASE__, self.encoder.get(self.unk_token ) ) def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> str: return self.decoder.get(SCREAMING_SNAKE_CASE__ ) def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: UpperCAmelCase_: Optional[Any] = """""".join(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_: Union[str, Any] = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""", errors=self.errors ) return text def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return UpperCAmelCase_: List[Any] = os.path.join( SCREAMING_SNAKE_CASE__, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCAmelCase_: Optional[int] = os.path.join( SCREAMING_SNAKE_CASE__, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(SCREAMING_SNAKE_CASE__, """w""", encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder, indent=2, sort_keys=SCREAMING_SNAKE_CASE__, ensure_ascii=SCREAMING_SNAKE_CASE__ ) + """\n""" ) UpperCAmelCase_: Union[str, Any] = 0 with open(SCREAMING_SNAKE_CASE__, """w""", encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' """ Please check that the tokenizer is not corrupted!""" ) UpperCAmelCase_: str = token_index writer.write(""" """.join(SCREAMING_SNAKE_CASE__ ) + """\n""" ) index += 1 return vocab_file, merge_file def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__, token_ids_a=SCREAMING_SNAKE_CASE__, already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> List[int]: UpperCAmelCase_: Optional[int] = [self.sep_token_id] UpperCAmelCase_: List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=False, **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCAmelCase_: Union[str, Any] = kwargs.pop("""add_prefix_space""", self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE__ ) > 0 and not text[0].isspace()): UpperCAmelCase_: List[Any] = """ """ + text return (text, kwargs) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> int: return token_ids_a + [self.eos_token_id] def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> List[int]: UpperCAmelCase_: Tuple = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(""" """ + text ) else: # Generated responses should contain them already. inputs.append(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_: List[str] = """ """.join(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_: Dict = self.encode(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > self.model_max_length: UpperCAmelCase_: Any = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
147
"""simple docstring""" import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def lowercase_ ( _snake_case ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def lowercase_ ( _snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Any = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue SCREAMING_SNAKE_CASE__ : Optional[int] = key.replace("""heads.cmd.mim_head.cls.predictions""" ,"""mmm_image_head""" ) SCREAMING_SNAKE_CASE__ : Dict = key.replace("""heads.cmd.mlm_head.cls.predictions""" ,"""mmm_text_head""" ) SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""heads.cmd.itm_head.cls""" ,"""itm_head""" ) SCREAMING_SNAKE_CASE__ : Tuple = key.replace("""heads.cmd.itm_head.pooler""" ,"""itm_head.pooler""" ) SCREAMING_SNAKE_CASE__ : int = key.replace("""heads.cmd.clip_head.logit_scale""" ,"""flava.logit_scale""" ) SCREAMING_SNAKE_CASE__ : Tuple = key.replace("""heads.fairseq_mlm.cls.predictions""" ,"""mlm_head""" ) SCREAMING_SNAKE_CASE__ : str = key.replace("""heads.imagenet.mim_head.cls.predictions""" ,"""mim_head""" ) SCREAMING_SNAKE_CASE__ : List[str] = key.replace("""mm_text_projection""" ,"""flava.text_to_mm_projection""" ) SCREAMING_SNAKE_CASE__ : Dict = key.replace("""mm_image_projection""" ,"""flava.image_to_mm_projection""" ) SCREAMING_SNAKE_CASE__ : str = key.replace("""image_encoder.module""" ,"""flava.image_model""" ) SCREAMING_SNAKE_CASE__ : Tuple = key.replace("""text_encoder.module""" ,"""flava.text_model""" ) SCREAMING_SNAKE_CASE__ : int = key.replace("""mm_encoder.module.encoder.cls_token""" ,"""flava.multimodal_model.cls_token""" ) SCREAMING_SNAKE_CASE__ : Dict = key.replace("""mm_encoder.module""" ,"""flava.multimodal_model""" ) SCREAMING_SNAKE_CASE__ : Any = key.replace("""text_projection""" ,"""flava.text_projection""" ) SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""image_projection""" ,"""flava.image_projection""" ) SCREAMING_SNAKE_CASE__ : Tuple = value.float() for key, value in codebook_state_dict.items(): SCREAMING_SNAKE_CASE__ : Optional[Any] = value return upgrade @torch.no_grad() def lowercase_ ( _snake_case ,_snake_case ,_snake_case ,_snake_case=None ): if config_path is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = FlavaConfig.from_pretrained(_snake_case ) else: SCREAMING_SNAKE_CASE__ : List[str] = FlavaConfig() SCREAMING_SNAKE_CASE__ : Optional[int] = FlavaForPreTraining(_snake_case ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = convert_dalle_checkpoint(_snake_case ,_snake_case ,save_checkpoint=_snake_case ) if os.path.exists(_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = torch.load(_snake_case ,map_location="""cpu""" ) else: SCREAMING_SNAKE_CASE__ : Tuple = torch.hub.load_state_dict_from_url(_snake_case ,map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : Dict = upgrade_state_dict(_snake_case ,_snake_case ) hf_model.load_state_dict(_snake_case ) SCREAMING_SNAKE_CASE__ : Any = hf_model.state_dict() SCREAMING_SNAKE_CASE__ : Any = count_parameters(_snake_case ) SCREAMING_SNAKE_CASE__ : str = count_parameters(_snake_case ) + count_parameters(_snake_case ) assert torch.allclose(_snake_case ,_snake_case ,atol=1E-3 ) hf_model.save_pretrained(_snake_case ) if __name__ == "__main__": UpperCAmelCase__ : List[Any] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') UpperCAmelCase__ : Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
25
0
def A_ ( A__ ) -> Any: a__ : Union[str, Any] = [0] * len(__lowerCAmelCase ) for i in range(1 , len(__lowerCAmelCase ) ): # use last results for better performance - dynamic programming a__ : Optional[int] = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: a__ : Optional[Any] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 a__ : Tuple = j return prefix_result def A_ ( A__ ) -> Tuple: return max(prefix_function(__lowerCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod()
371
def A_ ( A__ ) -> List[str]: # noqa: E741 a__ : Dict = len(A__ ) a__ : str = 0 a__ : Any = [0] * n a__ : int = [False] * n a__ : Optional[Any] = [False] * n def dfs(A__ , A__ , A__ , A__ ): if parent == root: out_edge_count += 1 a__ : Union[str, Any] = True a__ : Optional[Any] = at for to in l[at]: if to == parent: pass elif not visited[to]: a__ : List[Any] = dfs(A__ , A__ , A__ , A__ ) a__ : Dict = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: a__ : Dict = True # AP found via cycle if at == low[to]: a__ : List[Any] = True else: a__ : Optional[int] = min(low[at] , A__ ) return out_edge_count for i in range(A__ ): if not visited[i]: a__ : Tuple = 0 a__ : Any = dfs(A__ , A__ , -1 , A__ ) a__ : List[Any] = out_edge_count > 1 for x in range(len(A__ ) ): if is_art[x] is True: print(A__ ) # Adjacency list of graph lowercase : List[Any] = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
225
0
'''simple docstring''' import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class _lowercase ( unittest.TestCase ): '''simple docstring''' def a ( self : List[Any] ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() def a ( self : Union[str, Any] ) -> Any: __lowerCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __lowerCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __lowerCAmelCase = """xvjiarui/stable-diffusion-2-inpainting""" __lowerCAmelCase , __lowerCAmelCase = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = """Face of a yellow cat, high resolution, sitting on a park bench""" __lowerCAmelCase = jax.random.PRNGKey(0 ) __lowerCAmelCase = 50 __lowerCAmelCase = jax.device_count() __lowerCAmelCase = num_samples * [prompt] __lowerCAmelCase = num_samples * [init_image] __lowerCAmelCase = num_samples * [mask_image] __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # shard inputs and rng __lowerCAmelCase = replicate(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = jax.random.split(SCREAMING_SNAKE_CASE__ , jax.device_count() ) __lowerCAmelCase = shard(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = shard(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = shard(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = pipeline( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , jit=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = output.images.reshape(SCREAMING_SNAKE_CASE__ , 5_12 , 5_12 , 3 ) __lowerCAmelCase = images[0, 2_53:2_56, 2_53:2_56, -1] __lowerCAmelCase = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __lowerCAmelCase = jnp.array( [0.3_6_1_1_3_0_7, 0.3_7_6_4_9_7_3_6, 0.3_7_5_7_4_0_8, 0.3_8_2_1_3_9_5_3, 0.3_9_2_9_5_1_6_7, 0.3_8_4_1_6_3_1, 0.4_1_5_5_4_9_7_8, 0.4_1_3_7_4_7_5, 0.4_2_1_7_0_8_4] ) print(f"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
229
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( """The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion""" ) __UpperCamelCase : Union[str, Any] = None __UpperCamelCase : Any = { """7B""": 11008, """13B""": 13824, """30B""": 17920, """65B""": 22016, """70B""": 28672, } __UpperCamelCase : Optional[Any] = { """7B""": 1, """7Bf""": 1, """13B""": 2, """13Bf""": 2, """30B""": 4, """65B""": 8, """70B""": 8, """70Bf""": 8, } def a_ ( _A , _A=1 , _A=256 ) -> str: """simple docstring""" return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def a_ ( _A ) -> int: """simple docstring""" with open(_A , 'r' ) as f: return json.load(_A ) def a_ ( _A , _A ) -> int: """simple docstring""" with open(_A , 'w' ) as f: json.dump(_A , _A ) def a_ ( _A , _A , _A , _A=True ) -> List[str]: """simple docstring""" os.makedirs(_A , exist_ok=_A ) snake_case__ = os.path.join(_A , 'tmp' ) os.makedirs(_A , exist_ok=_A ) snake_case__ = read_json(os.path.join(_A , 'params.json' ) ) snake_case__ = NUM_SHARDS[model_size] snake_case__ = params['n_layers'] snake_case__ = params['n_heads'] snake_case__ = n_heads // num_shards snake_case__ = params['dim'] snake_case__ = dim // n_heads snake_case__ = 10000.0 snake_case__ = 1.0 / (base ** (torch.arange(0 , _A , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: snake_case__ = params['n_kv_heads'] # for GQA / MQA snake_case__ = n_heads_per_shard // num_key_value_heads snake_case__ = dim // num_key_value_heads else: # compatibility with other checkpoints snake_case__ = n_heads snake_case__ = n_heads_per_shard snake_case__ = dim # permute for sliced rotary def permute(_A , _A=n_heads , _A=dim , _A=dim ): return w.view(_A , dima // n_heads // 2 , 2 , _A ).transpose(1 , 2 ).reshape(_A , _A ) print(f'''Fetching all parameters from the checkpoint at {input_base_path}.''' ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) snake_case__ = torch.load(os.path.join(_A , 'consolidated.00.pth' ) , map_location='cpu' ) else: # Sharded snake_case__ = [ torch.load(os.path.join(_A , f'''consolidated.{i:02d}.pth''' ) , map_location='cpu' ) for i in range(_A ) ] snake_case__ = 0 snake_case__ = {'weight_map': {}} for layer_i in range(_A ): snake_case__ = f'''pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded snake_case__ = { f'''model.layers.{layer_i}.self_attn.q_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wq.weight'''] ), f'''model.layers.{layer_i}.self_attn.k_proj.weight''': permute( loaded[f'''layers.{layer_i}.attention.wk.weight'''] ), f'''model.layers.{layer_i}.self_attn.v_proj.weight''': loaded[f'''layers.{layer_i}.attention.wv.weight'''], f'''model.layers.{layer_i}.self_attn.o_proj.weight''': loaded[f'''layers.{layer_i}.attention.wo.weight'''], f'''model.layers.{layer_i}.mlp.gate_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w1.weight'''], f'''model.layers.{layer_i}.mlp.down_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w2.weight'''], f'''model.layers.{layer_i}.mlp.up_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w3.weight'''], f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[f'''layers.{layer_i}.attention_norm.weight'''], f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[f'''layers.{layer_i}.ffn_norm.weight'''], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. snake_case__ = { f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.attention_norm.weight''' ].clone(), f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[0][ f'''layers.{layer_i}.ffn_norm.weight''' ].clone(), } snake_case__ = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wq.weight'''].view(_A , _A , _A ) for i in range(_A ) ] , dim=0 , ).reshape(_A , _A ) ) snake_case__ = permute( torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wk.weight'''].view( _A , _A , _A ) for i in range(_A ) ] , dim=0 , ).reshape(_A , _A ) , _A , _A , _A , ) snake_case__ = torch.cat( [ loaded[i][f'''layers.{layer_i}.attention.wv.weight'''].view( _A , _A , _A ) for i in range(_A ) ] , dim=0 , ).reshape(_A , _A ) snake_case__ = torch.cat( [loaded[i][f'''layers.{layer_i}.attention.wo.weight'''] for i in range(_A )] , dim=1 ) snake_case__ = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w1.weight'''] for i in range(_A )] , dim=0 ) snake_case__ = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w2.weight'''] for i in range(_A )] , dim=1 ) snake_case__ = torch.cat( [loaded[i][f'''layers.{layer_i}.feed_forward.w3.weight'''] for i in range(_A )] , dim=0 ) snake_case__ = inv_freq for k, v in state_dict.items(): snake_case__ = filename param_count += v.numel() torch.save(_A , os.path.join(_A , _A ) ) snake_case__ = f'''pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded snake_case__ = { 'model.embed_tokens.weight': loaded['tok_embeddings.weight'], 'model.norm.weight': loaded['norm.weight'], 'lm_head.weight': loaded['output.weight'], } else: snake_case__ = { 'model.norm.weight': loaded[0]['norm.weight'], 'model.embed_tokens.weight': torch.cat( [loaded[i]['tok_embeddings.weight'] for i in range(_A )] , dim=1 ), 'lm_head.weight': torch.cat([loaded[i]['output.weight'] for i in range(_A )] , dim=0 ), } for k, v in state_dict.items(): snake_case__ = filename param_count += v.numel() torch.save(_A , os.path.join(_A , _A ) ) # Write configs snake_case__ = {'total_size': param_count * 2} write_json(_A , os.path.join(_A , 'pytorch_model.bin.index.json' ) ) snake_case__ = params['ffn_dim_multiplier'] if 'ffn_dim_multiplier' in params else 1 snake_case__ = params['multiple_of'] if 'multiple_of' in params else 256 snake_case__ = LlamaConfig( hidden_size=_A , intermediate_size=compute_intermediate_size(_A , _A , _A ) , num_attention_heads=params['n_heads'] , num_hidden_layers=params['n_layers'] , rms_norm_eps=params['norm_eps'] , num_key_value_heads=_A , ) config.save_pretrained(_A ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print('Loading the checkpoint in a Llama model.' ) snake_case__ = LlamaForCausalLM.from_pretrained(_A , torch_dtype=torch.floataa , low_cpu_mem_usage=_A ) # Avoid saving this as part of the config. del model.config._name_or_path print('Saving in the Transformers format.' ) model.save_pretrained(_A , safe_serialization=_A ) shutil.rmtree(_A ) def a_ ( _A , _A ) -> Tuple: """simple docstring""" # Initialize the tokenizer based on the `spm` model snake_case__ = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(f'''Saving a {tokenizer_class.__name__} to {tokenizer_path}.''' ) snake_case__ = tokenizer_class(_A ) tokenizer.save_pretrained(_A ) def a_ ( ) -> str: """simple docstring""" snake_case__ = argparse.ArgumentParser() parser.add_argument( '--input_dir' , help='Location of LLaMA weights, which contains tokenizer.model and model folders' , ) parser.add_argument( '--model_size' , choices=['7B', '7Bf', '13B', '13Bf', '30B', '65B', '70B', '70Bf', 'tokenizer_only'] , ) parser.add_argument( '--output_dir' , help='Location to write HF model and tokenizer' , ) parser.add_argument('--safe_serialization' , type=_A , help='Whether or not to save using `safetensors`.' ) snake_case__ = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) snake_case__ = os.path.join(args.input_dir , 'tokenizer.model' ) write_tokenizer(args.output_dir , _A ) if __name__ == "__main__": main()
307
0
import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case__ : """simple docstring""" def __init__( self , __lowercase=2 , __lowercase=3 , __lowercase=6_4 , __lowercase=None ) -> str: """simple docstring""" a__ : Union[str, Any] = np.random.default_rng(__lowercase ) a__ : List[str] = length a__ : Optional[Any] = rng.normal(size=(length,) ).astype(np.floataa ) a__ : Union[str, Any] = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> int: """simple docstring""" return self.length def __getitem__( self , __lowercase ) -> List[str]: """simple docstring""" return {"x": self.x[i], "y": self.y[i]} class snake_case__ (torch.nn.Module ): """simple docstring""" def __init__( self , __lowercase=0 , __lowercase=0 , __lowercase=False ) -> List[str]: """simple docstring""" super().__init__() a__ : List[str] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) a__ : List[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) a__ : Tuple = True def SCREAMING_SNAKE_CASE__( self , __lowercase=None ) -> Any: """simple docstring""" if self.first_batch: print(F'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) a__ : Optional[int] = False return x * self.a[0] + self.b[0] class snake_case__ (torch.nn.Module ): """simple docstring""" def __init__( self , __lowercase=0 , __lowercase=0 , __lowercase=False ) -> Union[str, Any]: """simple docstring""" super().__init__() a__ : Tuple = torch.nn.Parameter(torch.tensor(__lowercase ).float() ) a__ : List[Any] = torch.nn.Parameter(torch.tensor(__lowercase ).float() ) a__ : List[str] = True def SCREAMING_SNAKE_CASE__( self , __lowercase=None ) -> int: """simple docstring""" if self.first_batch: print(F'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) a__ : Union[str, Any] = False return x * self.a + self.b def lowerCAmelCase_ ( _lowercase : Union[str, Any] , _lowercase : int = 16) -> int: """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer a__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""") a__ : Dict = {"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""} a__ : List[str] = load_dataset("""csv""" , data_files=_lowercase) a__ : str = datasets["""train"""].unique("""label""") a__ : Any = {v: i for i, v in enumerate(_lowercase)} def tokenize_function(_lowercase : Dict): # max_length=None => use the model max length (it's actually the default) a__ : str = tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=_lowercase , max_length=_lowercase , padding="""max_length""") if "label" in examples: a__ : Any = [label_to_id[l] for l in examples["""label"""]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset a__ : Dict = datasets.map( _lowercase , batched=_lowercase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(_lowercase : Optional[int]): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_lowercase , padding="""max_length""" , max_length=128 , return_tensors="""pt""") return tokenizer.pad(_lowercase , padding="""longest""" , return_tensors="""pt""") # Instantiate dataloaders. a__ : List[str] = DataLoader(tokenized_datasets["""train"""] , shuffle=_lowercase , collate_fn=_lowercase , batch_size=2) a__ : Any = DataLoader(tokenized_datasets["""validation"""] , shuffle=_lowercase , collate_fn=_lowercase , batch_size=1) return train_dataloader, eval_dataloader
266
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def lowerCAmelCase_ ( _lowercase : Union[str, Any] , _lowercase : Dict=False) -> Any: """simple docstring""" try: a__ : str = os.environ[key] except KeyError: # KEY isn't set, default to `default`. a__ : Optional[int] = default else: # KEY is set, convert it to True or False. try: a__ : Optional[int] = strtobool(_lowercase) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F'''If set, {key} must be yes or no.''') return _value _lowercase : Dict =parse_flag_from_env("RUN_SLOW", default=False) def lowerCAmelCase_ ( _lowercase : Any) -> str: """simple docstring""" return unittest.skip("""Test was skipped""")(_lowercase) def lowerCAmelCase_ ( _lowercase : str) -> List[str]: """simple docstring""" return unittest.skipUnless(_run_slow_tests , """test is slow""")(_lowercase) def lowerCAmelCase_ ( _lowercase : List[Any]) -> Union[str, Any]: """simple docstring""" return unittest.skipUnless(not torch.cuda.is_available() , """test requires only a CPU""")(_lowercase) def lowerCAmelCase_ ( _lowercase : List[Any]) -> List[Any]: """simple docstring""" return unittest.skipUnless(torch.cuda.is_available() , """test requires a GPU""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Optional[int]) -> Dict: """simple docstring""" return unittest.skipUnless(is_xpu_available() , """test requires a XPU""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Tuple) -> List[str]: """simple docstring""" return unittest.skipUnless(is_mps_available() , """test requires a `mps` backend support in `torch`""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Dict) -> Union[str, Any]: """simple docstring""" return unittest.skipUnless( is_transformers_available() and is_datasets_available() , """test requires the Hugging Face suite""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Tuple) -> Any: """simple docstring""" return unittest.skipUnless(is_bnb_available() , """test requires the bitsandbytes library""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Union[str, Any]) -> List[str]: """simple docstring""" return unittest.skipUnless(is_tpu_available() , """test requires TPU""")(_lowercase) def lowerCAmelCase_ ( _lowercase : str) -> int: """simple docstring""" return unittest.skipUnless(torch.cuda.device_count() == 1 , """test requires a GPU""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Any) -> List[str]: """simple docstring""" return unittest.skipUnless(torch.xpu.device_count() == 1 , """test requires a XPU""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Union[str, Any]) -> Union[str, Any]: """simple docstring""" return unittest.skipUnless(torch.cuda.device_count() > 1 , """test requires multiple GPUs""")(_lowercase) def lowerCAmelCase_ ( _lowercase : int) -> Tuple: """simple docstring""" return unittest.skipUnless(torch.xpu.device_count() > 1 , """test requires multiple XPUs""")(_lowercase) def lowerCAmelCase_ ( _lowercase : int) -> Optional[Any]: """simple docstring""" return unittest.skipUnless(is_safetensors_available() , """test requires safetensors""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Optional[int]) -> List[str]: """simple docstring""" return unittest.skipUnless(is_deepspeed_available() , """test requires DeepSpeed""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Union[str, Any]) -> Optional[Any]: """simple docstring""" return unittest.skipUnless(is_torch_version(""">=""" , """1.12.0""") , """test requires torch version >= 1.12.0""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Any=None , _lowercase : List[str]=None) -> Dict: """simple docstring""" if test_case is None: return partial(_lowercase , version=_lowercase) return unittest.skipUnless(is_torch_version(""">=""" , _lowercase) , F'''test requires torch version >= {version}''')(_lowercase) def lowerCAmelCase_ ( _lowercase : Any) -> int: """simple docstring""" return unittest.skipUnless(is_tensorboard_available() , """test requires Tensorboard""")(_lowercase) def lowerCAmelCase_ ( _lowercase : str) -> Union[str, Any]: """simple docstring""" return unittest.skipUnless(is_wandb_available() , """test requires wandb""")(_lowercase) def lowerCAmelCase_ ( _lowercase : Optional[int]) -> Union[str, Any]: """simple docstring""" return unittest.skipUnless(is_comet_ml_available() , """test requires comet_ml""")(_lowercase) _lowercase : List[str] =( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def lowerCAmelCase_ ( _lowercase : Optional[int]) -> Union[str, Any]: """simple docstring""" return unittest.skipUnless( _atleast_one_tracker_available , """test requires at least one tracker to be available and for `comet_ml` to not be installed""" , )(_lowercase) class snake_case__ (unittest.TestCase ): """simple docstring""" __lowerCAmelCase :Optional[Any] = True @classmethod def SCREAMING_SNAKE_CASE__( cls ) -> Optional[int]: """simple docstring""" a__ : Tuple = tempfile.mkdtemp() @classmethod def SCREAMING_SNAKE_CASE__( cls ) -> Dict: """simple docstring""" if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def SCREAMING_SNAKE_CASE__( self ) -> List[Any]: """simple docstring""" if self.clear_on_setup: for path in Path(self.tmpdir ).glob("""**/*""" ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(__lowercase ) class snake_case__ (unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE__( self ) -> Union[str, Any]: """simple docstring""" super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class snake_case__ (unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE__( self , __lowercase ) -> Union[str, Any]: """simple docstring""" a__ : Tuple = mocks if isinstance(__lowercase , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def lowerCAmelCase_ ( _lowercase : Optional[int]) -> List[Any]: """simple docstring""" a__ : Tuple = AcceleratorState() a__ : List[str] = tensor[None].clone().to(state.device) a__ : Any = gather(_lowercase).cpu() a__ : Optional[Any] = tensor[0].cpu() for i in range(tensors.shape[0]): if not torch.equal(tensors[i] , _lowercase): return False return True class snake_case__ : """simple docstring""" def __init__( self , __lowercase , __lowercase , __lowercase ) -> Any: """simple docstring""" a__ : Any = returncode a__ : List[Any] = stdout a__ : Any = stderr async def lowerCAmelCase_ ( _lowercase : str , _lowercase : str) -> List[Any]: """simple docstring""" while True: a__ : str = await stream.readline() if line: callback(_lowercase) else: break async def lowerCAmelCase_ ( _lowercase : Any , _lowercase : Union[str, Any]=None , _lowercase : List[str]=None , _lowercase : Tuple=None , _lowercase : Optional[Any]=False , _lowercase : Dict=False) -> _RunOutput: """simple docstring""" if echo: print("""\nRunning: """ , """ """.join(_lowercase)) a__ : int = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=_lowercase , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=_lowercase , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) a__ : int = [] a__ : Optional[int] = [] def tee(_lowercase : List[str] , _lowercase : Optional[int] , _lowercase : Any , _lowercase : Optional[Any]=""): a__ : int = line.decode("""utf-8""").rstrip() sink.append(_lowercase) if not quiet: print(_lowercase , _lowercase , file=_lowercase) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda _lowercase: tee(_lowercase , _lowercase , sys.stdout , label="""stdout:"""))), asyncio.create_task(_read_stream(p.stderr , lambda _lowercase: tee(_lowercase , _lowercase , sys.stderr , label="""stderr:"""))), ] , timeout=_lowercase , ) return _RunOutput(await p.wait() , _lowercase , _lowercase) def lowerCAmelCase_ ( _lowercase : Optional[int] , _lowercase : Optional[int]=None , _lowercase : Tuple=None , _lowercase : Any=180 , _lowercase : List[Any]=False , _lowercase : Dict=True) -> _RunOutput: """simple docstring""" a__ : Any = asyncio.get_event_loop() a__ : List[Any] = loop.run_until_complete( _stream_subprocess(_lowercase , env=_lowercase , stdin=_lowercase , timeout=_lowercase , quiet=_lowercase , echo=_lowercase)) a__ : Optional[int] = """ """.join(_lowercase) if result.returncode > 0: a__ : List[Any] = """\n""".join(result.stderr) raise RuntimeError( F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n''' F'''The combined stderr from workers follows:\n{stderr}''') return result class snake_case__ (A__ ): """simple docstring""" pass def lowerCAmelCase_ ( _lowercase : List[str] , _lowercase : Optional[int]=False) -> Dict: """simple docstring""" try: a__ : List[Any] = subprocess.check_output(_lowercase , stderr=subprocess.STDOUT) if return_stdout: if hasattr(_lowercase , """decode"""): a__ : Tuple = output.decode("""utf-8""") return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F'''Command `{' '.join(_lowercase)}` failed with the following error:\n\n{e.output.decode()}''') from e
266
1
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __A : def __init__( self , a__ , a__=sys.maxsize ): _lowerCAmelCase : str = """bilinear""" _lowerCAmelCase : List[str] = max_size _lowerCAmelCase : Optional[Any] = short_edge_length def __call__( self , a__ ): _lowerCAmelCase : int = [] for img in imgs: _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = img.shape[:2] # later: provide list and randomly choose index for resize _lowerCAmelCase : Tuple = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img _lowerCAmelCase : Union[str, Any] = size * 1.0 / min(a__ , a__ ) if h < w: _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = size, scale * w else: _lowerCAmelCase , _lowerCAmelCase : Optional[int] = scale * h, size if max(a__ , a__ ) > self.max_size: _lowerCAmelCase : Optional[Any] = self.max_size * 1.0 / max(a__ , a__ ) _lowerCAmelCase : List[str] = newh * scale _lowerCAmelCase : Union[str, Any] = neww * scale _lowerCAmelCase : List[Any] = int(neww + 0.5 ) _lowerCAmelCase : Optional[int] = int(newh + 0.5 ) if img.dtype == np.uinta: _lowerCAmelCase : Dict = Image.fromarray(a__ ) _lowerCAmelCase : Any = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) _lowerCAmelCase : List[Any] = np.asarray(a__ ) else: _lowerCAmelCase : Tuple = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw _lowerCAmelCase : Tuple = nn.functional.interpolate( a__ , (newh, neww) , mode=self.interp_method , align_corners=a__ ).squeeze(0 ) img_augs.append(a__ ) return img_augs class __A : def __init__( self , a__ ): _lowerCAmelCase : List[Any] = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) _lowerCAmelCase : List[str] = cfg.INPUT.FORMAT _lowerCAmelCase : List[Any] = cfg.SIZE_DIVISIBILITY _lowerCAmelCase : Any = cfg.PAD_VALUE _lowerCAmelCase : Union[str, Any] = cfg.INPUT.MAX_SIZE_TEST _lowerCAmelCase : List[str] = cfg.MODEL.DEVICE _lowerCAmelCase : Optional[int] = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) _lowerCAmelCase : List[str] = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) _lowerCAmelCase : Union[str, Any] = lambda a__ : (x - self.pixel_mean) / self.pixel_std def __A ( self , a__ ): _lowerCAmelCase : Optional[Any] = tuple(max(a__ ) for s in zip(*[img.shape for img in images] ) ) _lowerCAmelCase : Optional[Any] = [im.shape[-2:] for im in images] _lowerCAmelCase : Optional[Any] = [ nn.functional.pad( a__ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(a__ , a__ ) ] return torch.stack(a__ ), torch.tensor(a__ ) def __call__( self , a__ , a__=False ): with torch.no_grad(): if not isinstance(a__ , a__ ): _lowerCAmelCase : Optional[Any] = [images] if single_image: assert len(a__ ) == 1 for i in range(len(a__ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(a__ , images.pop(a__ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( a__ , torch.as_tensor(img_tensorize(images.pop(a__ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge _lowerCAmelCase : Union[str, Any] = torch.tensor([im.shape[:2] for im in images] ) _lowerCAmelCase : Optional[int] = self.aug(a__ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic _lowerCAmelCase : List[Any] = [self.normalizer(a__ ) for x in images] # now pad them to do the following operations _lowerCAmelCase , _lowerCAmelCase : Any = self.pad(a__ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad _lowerCAmelCase : Optional[int] = torch.true_divide(a__ , a__ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any] ,_lowerCamelCase : Any ) -> Dict: boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Tuple[int, int] ) -> Tuple: assert torch.isfinite(_lowerCamelCase ).all(), "Box tensor contains infinite or NaN!" _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = box_size tensor[:, 0].clamp_(min=0 ,max=_lowerCamelCase ) tensor[:, 1].clamp_(min=0 ,max=_lowerCamelCase ) tensor[:, 2].clamp_(min=0 ,max=_lowerCamelCase ) tensor[:, 3].clamp_(min=0 ,max=_lowerCamelCase )
44
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _a : List[Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Union[str, Any] = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } _a : Optional[Any] = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } _a : Any = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[Any] = ElectraTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ): super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) _lowerCAmelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , a__ ) != do_lower_case or normalizer_state.get("""strip_accents""" , a__ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , a__ ) != tokenize_chinese_chars ): _lowerCAmelCase : Dict = getattr(a__ , normalizer_state.pop("""type""" ) ) _lowerCAmelCase : int = do_lower_case _lowerCAmelCase : str = strip_accents _lowerCAmelCase : Dict = tokenize_chinese_chars _lowerCAmelCase : str = normalizer_class(**a__ ) _lowerCAmelCase : List[str] = do_lower_case def __A ( self , a__ , a__=None ): _lowerCAmelCase : int = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , a__ , a__ = None ): _lowerCAmelCase : List[str] = [self.sep_token_id] _lowerCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Optional[Any] = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
44
1
from typing import Any def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' if not input_list: return [] lowercase = [input_list.count(lowerCAmelCase__ ) for value in input_list] lowercase = max(lowerCAmelCase__ ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(lowerCAmelCase__ ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
370
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase__ :Any = { "configuration_distilbert": [ "DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DistilBertConfig", "DistilBertOnnxConfig", ], "tokenization_distilbert": ["DistilBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Tuple = ["DistilBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Union[str, Any] = [ "DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "DistilBertForMaskedLM", "DistilBertForMultipleChoice", "DistilBertForQuestionAnswering", "DistilBertForSequenceClassification", "DistilBertForTokenClassification", "DistilBertModel", "DistilBertPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Optional[int] = [ "TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDistilBertForMaskedLM", "TFDistilBertForMultipleChoice", "TFDistilBertForQuestionAnswering", "TFDistilBertForSequenceClassification", "TFDistilBertForTokenClassification", "TFDistilBertMainLayer", "TFDistilBertModel", "TFDistilBertPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Union[str, Any] = [ "FlaxDistilBertForMaskedLM", "FlaxDistilBertForMultipleChoice", "FlaxDistilBertForQuestionAnswering", "FlaxDistilBertForSequenceClassification", "FlaxDistilBertForTokenClassification", "FlaxDistilBertModel", "FlaxDistilBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys lowercase__ :List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
97
0
"""simple docstring""" from __future__ import annotations from math import ceil, floor, sqrt def a__ ( lowerCAmelCase = 2_00_00_00 ) -> int: UpperCAmelCase__ : list[int] = [0] UpperCAmelCase__ : int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target UpperCAmelCase__ : int = 0 # the area corresponding to the grid that gives the product closest to target UpperCAmelCase__ : int = 0 # an estimate of b, using the quadratic formula UpperCAmelCase__ : float # the largest integer less than b_estimate UpperCAmelCase__ : int # the largest integer less than b_estimate UpperCAmelCase__ : int # the triangle number corresponding to b_floor UpperCAmelCase__ : int # the triangle number corresponding to b_ceil UpperCAmelCase__ : int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): UpperCAmelCase__ : Any = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 UpperCAmelCase__ : Optional[Any] = floor(lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = ceil(lowerCAmelCase ) UpperCAmelCase__ : Any = triangle_numbers[b_floor] UpperCAmelCase__ : Dict = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): UpperCAmelCase__ : Dict = triangle_b_first_guess * triangle_a UpperCAmelCase__ : Optional[int] = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): UpperCAmelCase__ : int = triangle_b_second_guess * triangle_a UpperCAmelCase__ : List[Any] = idx_a * b_ceil return area if __name__ == "__main__": print(f'''{solution() = }''')
171
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) _A = { """sample_size""": 32, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": 10_00, """block_out_channels""": [32, 64], """attention_head_dim""": 8, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """sample_size""": 64, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 3, """num_class_embeds""": 10_00, """block_out_channels""": [1_92, 1_92 * 2, 1_92 * 3, 1_92 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """sample_size""": 2_56, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": None, """block_out_channels""": [2_56, 2_56, 2_56 * 2, 2_56 * 2, 2_56 * 4, 2_56 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """default""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _A = { """num_train_timesteps""": 40, """sigma_min""": 0.002, """sigma_max""": 80.0, } _A = { """num_train_timesteps""": 2_01, """sigma_min""": 0.002, """sigma_max""": 80.0, } _A = { """num_train_timesteps""": 1_51, """sigma_min""": 0.002, """sigma_max""": 80.0, } def a__ ( lowerCAmelCase ) -> Tuple: if isinstance(lowerCAmelCase , lowerCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("""boolean value expected""" ) def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False ) -> List[str]: UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.in_layers.0.weight"""] UpperCAmelCase__ : Optional[int] = checkpoint[F"""{old_prefix}.in_layers.0.bias"""] UpperCAmelCase__ : Optional[Any] = checkpoint[F"""{old_prefix}.in_layers.2.weight"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.in_layers.2.bias"""] UpperCAmelCase__ : Any = checkpoint[F"""{old_prefix}.emb_layers.1.weight"""] UpperCAmelCase__ : Optional[int] = checkpoint[F"""{old_prefix}.emb_layers.1.bias"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.out_layers.0.weight"""] UpperCAmelCase__ : List[Any] = checkpoint[F"""{old_prefix}.out_layers.0.bias"""] UpperCAmelCase__ : Dict = checkpoint[F"""{old_prefix}.out_layers.3.weight"""] UpperCAmelCase__ : Union[str, Any] = checkpoint[F"""{old_prefix}.out_layers.3.bias"""] if has_skip: UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.skip_connection.weight"""] UpperCAmelCase__ : Dict = checkpoint[F"""{old_prefix}.skip_connection.bias"""] return new_checkpoint def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=None ) -> Optional[int]: UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.qkv.weight"""].chunk(3 , dim=0 ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Any = checkpoint[F"""{old_prefix}.qkv.bias"""].chunk(3 , dim=0 ) UpperCAmelCase__ : List[Any] = checkpoint[F"""{old_prefix}.norm.weight"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.norm.bias"""] UpperCAmelCase__ : Union[str, Any] = weight_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Optional[Any] = bias_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Any = weight_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : int = bias_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Dict = weight_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : int = bias_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Any = ( checkpoint[F"""{old_prefix}.proj_out.weight"""].squeeze(-1 ).squeeze(-1 ) ) UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.proj_out.bias"""].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def a__ ( lowerCAmelCase , lowerCAmelCase ) -> str: UpperCAmelCase__ : Optional[Any] = torch.load(lowerCAmelCase , map_location="""cpu""" ) UpperCAmelCase__ : List[Any] = {} UpperCAmelCase__ : List[Any] = checkpoint["""time_embed.0.weight"""] UpperCAmelCase__ : str = checkpoint["""time_embed.0.bias"""] UpperCAmelCase__ : List[str] = checkpoint["""time_embed.2.weight"""] UpperCAmelCase__ : Dict = checkpoint["""time_embed.2.bias"""] if unet_config["num_class_embeds"] is not None: UpperCAmelCase__ : Dict = checkpoint["""label_emb.weight"""] UpperCAmelCase__ : str = checkpoint["""input_blocks.0.0.weight"""] UpperCAmelCase__ : List[str] = checkpoint["""input_blocks.0.0.bias"""] UpperCAmelCase__ : List[str] = unet_config["""down_block_types"""] UpperCAmelCase__ : Tuple = unet_config["""layers_per_block"""] UpperCAmelCase__ : int = unet_config["""attention_head_dim"""] UpperCAmelCase__ : Union[str, Any] = unet_config["""block_out_channels"""] UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : Union[str, Any] = channels_list[0] for i, layer_type in enumerate(lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = channels_list[i] UpperCAmelCase__ : int = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(lowerCAmelCase ): UpperCAmelCase__ : Tuple = F"""down_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : List[Any] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : Dict = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase__ : Optional[Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(lowerCAmelCase ): UpperCAmelCase__ : Any = F"""down_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Optional[Any] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : int = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) UpperCAmelCase__ : Dict = F"""down_blocks.{i}.attentions.{j}""" UpperCAmelCase__ : int = F"""input_blocks.{current_layer}.1""" UpperCAmelCase__ : Union[str, Any] = convert_attention( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : Any = F"""down_blocks.{i}.downsamplers.0""" UpperCAmelCase__ : List[str] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : Tuple = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 UpperCAmelCase__ : Tuple = current_channels # hardcoded the mid-block for now UpperCAmelCase__ : List[Any] = """mid_block.resnets.0""" UpperCAmelCase__ : str = """middle_block.0""" UpperCAmelCase__ : List[str] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : List[str] = """mid_block.attentions.0""" UpperCAmelCase__ : Any = """middle_block.1""" UpperCAmelCase__ : Optional[int] = convert_attention(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : List[Any] = """mid_block.resnets.1""" UpperCAmelCase__ : Tuple = """middle_block.2""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : Any = 0 UpperCAmelCase__ : Dict = unet_config["""up_block_types"""] for i, layer_type in enumerate(lowerCAmelCase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase__ : Tuple = F"""up_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Optional[Any] = F"""output_blocks.{current_layer}.0""" UpperCAmelCase__ : Dict = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : List[str] = F"""up_blocks.{i}.upsamplers.0""" UpperCAmelCase__ : Any = F"""output_blocks.{current_layer-1}.1""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase__ : List[str] = F"""up_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Dict = F"""output_blocks.{current_layer}.0""" UpperCAmelCase__ : Any = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , has_skip=lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = F"""up_blocks.{i}.attentions.{j}""" UpperCAmelCase__ : List[str] = F"""output_blocks.{current_layer}.1""" UpperCAmelCase__ : Dict = convert_attention( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) current_layer += 1 if i != len(lowerCAmelCase ) - 1: UpperCAmelCase__ : int = F"""up_blocks.{i}.upsamplers.0""" UpperCAmelCase__ : int = F"""output_blocks.{current_layer-1}.2""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = checkpoint["""out.0.weight"""] UpperCAmelCase__ : List[Any] = checkpoint["""out.0.bias"""] UpperCAmelCase__ : Tuple = checkpoint["""out.2.weight"""] UpperCAmelCase__ : Optional[Any] = checkpoint["""out.2.bias"""] return new_checkpoint if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument("""--unet_path""", default=None, type=str, required=True, help="""Path to the unet.pt to convert.""") parser.add_argument( """--dump_path""", default=None, type=str, required=True, help="""Path to output the converted UNet model.""" ) parser.add_argument("""--class_cond""", default=True, type=str, help="""Whether the model is class-conditional.""") _A = parser.parse_args() _A = strabool(args.class_cond) _A = os.path.basename(args.unet_path) print(f'''Checkpoint: {ckpt_name}''') # Get U-Net config if "imagenet64" in ckpt_name: _A = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): _A = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: _A = TEST_UNET_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') if not args.class_cond: _A = None _A = con_pt_to_diffuser(args.unet_path, unet_config) _A = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: _A = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: _A = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): _A = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') _A = CMStochasticIterativeScheduler(**scheduler_config) _A = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
171
1
from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(SCREAMING_SNAKE_CASE__ ): return ext raise Exception( f'Unable to determine file format from file extension {path}. ' f'Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) __lowerCamelCase : Dict = try_infer_format_from_ext(args.input ) if args.format == 'infer' else args.format __lowerCamelCase : str = PipelineDataFormat.from_str( format=SCREAMING_SNAKE_CASE__ , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: List[str] , a: Pipeline , a: PipelineDataFormat ): __lowerCamelCase : str = nlp __lowerCamelCase : int = reader @staticmethod def _snake_case ( a: ArgumentParser ): __lowerCamelCase : Optional[Any] = parser.add_parser('run' , help='Run a pipeline through the CLI' ) run_parser.add_argument('--task' , choices=get_supported_tasks() , help='Task to run' ) run_parser.add_argument('--input' , type=a , help='Path to the file to use for inference' ) run_parser.add_argument('--output' , type=a , help='Path to the file that will be used post to write results.' ) run_parser.add_argument('--model' , type=a , help='Name or path to the model to instantiate.' ) run_parser.add_argument('--config' , type=a , help='Name or path to the model\'s config to instantiate.' ) run_parser.add_argument( '--tokenizer' , type=a , help='Name of the tokenizer to use. (default: same as the model name)' ) run_parser.add_argument( '--column' , type=a , help='Name of the column to use as input. (For multi columns input as QA use column1,columns2)' , ) run_parser.add_argument( '--format' , type=a , default='infer' , choices=PipelineDataFormat.SUPPORTED_FORMATS , help='Input format to read from' , ) run_parser.add_argument( '--device' , type=a , default=-1 , help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)' , ) run_parser.add_argument('--overwrite' , action='store_true' , help='Allow overwriting the output file.' ) run_parser.set_defaults(func=a ) def _snake_case ( self: Dict ): __lowerCamelCase , __lowerCamelCase : Any = self._nlp, [] for entry in self._reader: __lowerCamelCase : Tuple = nlp(**a ) if self._reader.is_multi_columns else nlp(a ) if isinstance(a , a ): outputs.append(a ) else: outputs += output # Saving data if self._nlp.binary_output: __lowerCamelCase : List[str] = self._reader.save_binary(a ) logger.warning(F'Current pipeline requires output to be in binary format, saving at {binary_path}' ) else: self._reader.save(a )
194
import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowercase_ = logging.get_logger(__name__) class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: List[str] , *a: List[Any] , **a: Optional[Any] ): warnings.warn( 'The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use ChineseCLIPImageProcessor instead.' , a , ) super().__init__(*a , **a )
194
1
"""simple docstring""" def a_ ( lowerCamelCase ): if len(lowerCamelCase ) <= 1: return [tuple(lowerCamelCase )] UpperCAmelCase__ = [] def generate(lowerCamelCase , lowerCamelCase ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , lowerCamelCase ) for i in range(k - 1 ): if k % 2 == 0: # k is even UpperCAmelCase__ , UpperCAmelCase__ = arr[k - 1], arr[i] else: # k is odd UpperCAmelCase__ , UpperCAmelCase__ = arr[k - 1], arr[0] generate(k - 1 , lowerCamelCase ) generate(len(lowerCamelCase ) , lowerCamelCase ) return res if __name__ == "__main__": lowerCAmelCase__ : Tuple = input('Enter numbers separated by a comma:\n').strip() lowerCAmelCase__ : List[Any] = [int(item) for item in user_input.split(',')] print(heaps(arr))
98
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> int: lowerCamelCase__ : Optional[int] = [] embed.append( ( F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight""", F"""stage{idx}.patch_embed.proj.weight""", ) ) embed.append( ( F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias""", F"""stage{idx}.patch_embed.proj.bias""", ) ) embed.append( ( F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight""", F"""stage{idx}.patch_embed.norm.weight""", ) ) embed.append( ( F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias""", F"""stage{idx}.patch_embed.norm.bias""", ) ) return embed def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Tuple: lowerCamelCase__ : Tuple = [] attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight""", F"""stage{idx}.blocks.{cnt}.attn.proj_q.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias""", F"""stage{idx}.blocks.{cnt}.attn.proj_q.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight""", F"""stage{idx}.blocks.{cnt}.attn.proj_k.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias""", F"""stage{idx}.blocks.{cnt}.attn.proj_k.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight""", F"""stage{idx}.blocks.{cnt}.attn.proj_v.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias""", F"""stage{idx}.blocks.{cnt}.attn.proj_v.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight""", F"""stage{idx}.blocks.{cnt}.attn.proj.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias""", F"""stage{idx}.blocks.{cnt}.attn.proj.bias""", ) ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight""", F"""stage{idx}.blocks.{cnt}.mlp.fc1.weight""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias""", F"""stage{idx}.blocks.{cnt}.mlp.fc1.bias""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight""", F"""stage{idx}.blocks.{cnt}.mlp.fc2.weight""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias""", F"""stage{idx}.blocks.{cnt}.mlp.fc2.bias""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight""", F"""stage{idx}.blocks.{cnt}.norm1.weight""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias""", F"""stage{idx}.blocks.{cnt}.norm1.bias""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight""", F"""stage{idx}.blocks.{cnt}.norm2.weight""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias""", F"""stage{idx}.blocks.{cnt}.norm2.bias""") ) return attention_weights def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> Tuple: lowerCamelCase__ : Union[str, Any] = [] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", 'stage2.cls_token') ) return token def SCREAMING_SNAKE_CASE ( ) -> str: lowerCamelCase__ : str = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Optional[int]: lowerCamelCase__ : Tuple = 'imagenet-1k-id2label.json' lowerCamelCase__ : Union[str, Any] = 1000 lowerCamelCase__ : Optional[Any] = 'huggingface/label-files' lowerCamelCase__ : Any = num_labels lowerCamelCase__ : Dict = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase , _UpperCAmelCase , repo_type='dataset' ) ) , 'r' ) ) lowerCamelCase__ : int = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} lowerCamelCase__ : Tuple = idalabel lowerCamelCase__ : List[Any] = {v: k for k, v in idalabel.items()} lowerCamelCase__ : List[str] = CvtConfig(num_labels=_UpperCAmelCase , idalabel=_UpperCAmelCase , labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' , 1 )[-1][4:6] == "13": lowerCamelCase__ : List[Any] = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' , 1 )[-1][4:6] == "21": lowerCamelCase__ : Dict = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: lowerCamelCase__ : Optional[Any] = [2, 2, 20] lowerCamelCase__ : Optional[int] = [3, 12, 16] lowerCamelCase__ : str = [192, 768, 1024] lowerCamelCase__ : Any = CvtForImageClassification(_UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) lowerCamelCase__ : Tuple = image_size lowerCamelCase__ : List[str] = torch.load(_UpperCAmelCase , map_location=torch.device('cpu' ) ) lowerCamelCase__ : Optional[int] = OrderedDict() lowerCamelCase__ : Tuple = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: lowerCamelCase__ : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) lowerCamelCase__ : str = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): lowerCamelCase__ : str = list_of_state_dict + attention(_UpperCAmelCase , _UpperCAmelCase ) lowerCamelCase__ : int = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): lowerCamelCase__ : str = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": _UpperCAmelCase : List[str] = argparse.ArgumentParser() parser.add_argument( """--cvt_model""", default="""cvt-w24""", type=str, help="""Name of the cvt model you'd like to convert.""", ) parser.add_argument( """--image_size""", default=3_84, type=int, help="""Input Image Size""", ) parser.add_argument( """--cvt_file_name""", default=R"""cvtmodels\CvT-w24-384x384-IN-22k.pth""", type=str, help="""Input Image Size""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) _UpperCAmelCase : List[str] = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
50
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __magic_name__ ( unittest.TestCase ): def __init__( self : Any ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : List[str]=7 ,_UpperCAmelCase : Optional[int]=3 ,_UpperCAmelCase : Optional[int]=18 ,_UpperCAmelCase : str=30 ,_UpperCAmelCase : int=400 ,_UpperCAmelCase : List[Any]=True ,_UpperCAmelCase : List[str]=None ,_UpperCAmelCase : List[str]=True ,_UpperCAmelCase : Optional[int]=None ,): _a : Tuple = size if size is not None else {"""shortest_edge""": 20} _a : Union[str, Any] = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} _a : List[str] = parent _a : Union[str, Any] = batch_size _a : Dict = num_channels _a : Dict = image_size _a : Optional[Any] = min_resolution _a : Tuple = max_resolution _a : int = do_resize _a : int = size _a : List[str] = do_center_crop _a : Any = crop_size def __lowercase ( self : Union[str, Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __magic_name__ ( __UpperCamelCase , unittest.TestCase ): lowerCAmelCase : Tuple = MobileNetVaImageProcessor if is_vision_available() else None def __lowercase ( self : List[str] ): _a : Optional[int] = MobileNetVaImageProcessingTester(self ) @property def __lowercase ( self : Dict ): return self.image_processor_tester.prepare_image_processor_dict() def __lowercase ( self : Any ): _a : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCAmelCase ,'do_resize' ) ) self.assertTrue(hasattr(_lowerCAmelCase ,'size' ) ) self.assertTrue(hasattr(_lowerCAmelCase ,'do_center_crop' ) ) self.assertTrue(hasattr(_lowerCAmelCase ,'crop_size' ) ) def __lowercase ( self : Any ): _a : str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'shortest_edge': 20} ) self.assertEqual(image_processor.crop_size ,{'height': 18, 'width': 18} ) _a : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ,crop_size=84 ) self.assertEqual(image_processor.size ,{'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size ,{'height': 84, 'width': 84} ) def __lowercase ( self : Optional[int] ): pass def __lowercase ( self : Optional[int] ): # Initialize image_processing _a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _a : int = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase ,Image.Image ) # Test not batched input _a : List[str] = image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) # Test batched _a : Optional[Any] = image_processing(_lowerCAmelCase ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) def __lowercase ( self : int ): # Initialize image_processing _a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _a : Optional[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_lowerCAmelCase ,numpify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase ,np.ndarray ) # Test not batched input _a : int = image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) # Test batched _a : int = image_processing(_lowerCAmelCase ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) def __lowercase ( self : Dict ): # Initialize image_processing _a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _a : str = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_lowerCAmelCase ,torchify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase ,torch.Tensor ) # Test not batched input _a : int = image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,) # Test batched _a : Tuple = image_processing(_lowerCAmelCase ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) ,)
370
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Any class __magic_name__ : def __init__( self : Dict ,_UpperCAmelCase : Any ): _a : Any = data _a : Node | None = None class __magic_name__ : def __init__( self : Any ): _a : int = None _a : Optional[int] = None def __iter__( self : Optional[int] ): _a : List[Any] = self.head while self.head: yield node.data _a : str = node.next if node == self.head: break def __len__( self : Any ): return sum(1 for _ in self ) def __repr__( self : int ): return "->".join(str(_UpperCAmelCase ) for item in iter(self ) ) def __lowercase ( self : Optional[Any] ,_UpperCAmelCase : Any ): self.insert_nth(len(self ) ,_UpperCAmelCase ) def __lowercase ( self : str ,_UpperCAmelCase : Any ): self.insert_nth(0 ,_UpperCAmelCase ) def __lowercase ( self : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if index < 0 or index > len(self ): raise IndexError('list index out of range.' ) _a : List[str] = Node(_UpperCAmelCase ) if self.head is None: _a : Tuple = new_node # first node points itself _a : int = new_node elif index == 0: # insert at head _a : Any = self.head _a : Tuple = new_node else: _a : Any = self.head for _ in range(index - 1 ): _a : int = temp.next _a : Optional[int] = temp.next _a : int = new_node if index == len(self ) - 1: # insert at tail _a : Optional[int] = new_node def __lowercase ( self : List[Any] ): return self.delete_nth(0 ) def __lowercase ( self : Dict ): return self.delete_nth(len(self ) - 1 ) def __lowercase ( self : Union[str, Any] ,_UpperCAmelCase : int = 0 ): if not 0 <= index < len(self ): raise IndexError('list index out of range.' ) _a : Optional[int] = self.head if self.head == self.tail: # just one node _a : Optional[int] = None elif index == 0: # delete head node _a : Dict = self.tail.next.next _a : Dict = self.head.next else: _a : List[Any] = self.head for _ in range(index - 1 ): _a : Union[str, Any] = temp.next _a : Optional[int] = temp.next _a : List[str] = temp.next.next if index == len(self ) - 1: # delete at tail _a : int = temp return delete_node.data def __lowercase ( self : int ): return len(self ) == 0 def __lowerCamelCase ( ) -> None: _a : int = CircularLinkedList() assert len(lowerCAmelCase_ ) == 0 assert circular_linked_list.is_empty() is True assert str(lowerCAmelCase_ ) == "" 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(lowerCAmelCase_ ) == i circular_linked_list.insert_nth(lowerCAmelCase_ , i + 1 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
107
0
import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class lowercase_ ( A__ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = 0 UpperCAmelCase_ : str = False UpperCAmelCase_ : List[str] = 3.0 class lowercase_ ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE_ ( self ) ->Union[str, Any]: # If no defaults are changed, `to_kwargs` returns an empty dict. self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {'''a''': 2} ) self.assertDictEqual(MockClass(a=2 , b=__lowerCamelCase ).to_kwargs() , {'''a''': 2, '''b''': True} ) self.assertDictEqual(MockClass(a=2 , c=2.2_5 ).to_kwargs() , {'''a''': 2, '''c''': 2.2_5} ) @require_cuda def SCREAMING_SNAKE_CASE_ ( self ) ->Tuple: # If no defaults are changed, `to_kwargs` returns an empty dict. lowerCAmelCase = GradScalerKwargs(init_scale=1024 , growth_factor=2 ) AcceleratorState._reset_state() lowerCAmelCase = Accelerator(mixed_precision='''fp16''' , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) lowerCAmelCase = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 1_0_2_4.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2000 ) self.assertEqual(scaler._enabled , __lowerCamelCase ) @require_multi_gpu def SCREAMING_SNAKE_CASE_ ( self ) ->int: lowerCAmelCase = ['''torchrun''', F"--nproc_per_node={torch.cuda.device_count()}", inspect.getfile(self.__class__ )] execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() ) if __name__ == "__main__": lowercase__ : List[str] = DistributedDataParallelKwargs(bucket_cap_mb=1_5, find_unused_parameters=True) lowercase__ : str = Accelerator(kwargs_handlers=[ddp_scaler]) lowercase__ : List[Any] = torch.nn.Linear(1_0_0, 2_0_0) lowercase__ : Dict = accelerator.prepare(model) # Check the values changed in kwargs lowercase__ : Dict = '''''' lowercase__ : str = model.bucket_bytes_cap // (1_0_2_4 * 1_0_2_4) if observed_bucket_cap_map != 1_5: error_msg += f"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += f"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += f"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += f"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += f"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
338
from __future__ import annotations def UpperCAmelCase_ ( _A , _A = None ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = word_bank or [] # create a table SCREAMING_SNAKE_CASE__ = len(_A ) + 1 SCREAMING_SNAKE_CASE__ = [] for _ in range(_A ): table.append([] ) # seed value SCREAMING_SNAKE_CASE__ = [[]] # because empty string has empty combination # iterate through the indices for i in range(_A ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(_A )] == word: SCREAMING_SNAKE_CASE__ = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(_A )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(_A )]: combination.reverse() return table[len(_A )] if __name__ == "__main__": print(all_construct('''jwajalapa''', ['''jwa''', '''j''', '''w''', '''a''', '''la''', '''lapa'''])) print(all_construct('''rajamati''', ['''s''', '''raj''', '''amat''', '''raja''', '''ma''', '''i''', '''t'''])) print( all_construct( '''hexagonosaurus''', ['''h''', '''ex''', '''hex''', '''ag''', '''ago''', '''ru''', '''auru''', '''rus''', '''go''', '''no''', '''o''', '''s'''], ) )
314
0
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase_ = { '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' }, } lowerCamelCase_ = {'allegro/herbert-base-cased': 5_14} lowerCamelCase_ = {} class lowercase_ ( A ): """simple docstring""" lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_INIT_CONFIGURATION lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = HerbertTokenizer def __init__( self : Union[str, Any] , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : Tuple="<s>" , __lowerCamelCase : Optional[int]="<unk>" , __lowerCamelCase : int="<pad>" , __lowerCamelCase : int="<mask>" , __lowerCamelCase : Tuple="</s>" , **__lowerCamelCase : str , ): """simple docstring""" super().__init__( __lowerCamelCase , __lowerCamelCase , tokenizer_file=__lowerCamelCase , cls_token=__lowerCamelCase , unk_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , sep_token=__lowerCamelCase , **__lowerCamelCase , ) def lowerCAmelCase_ ( self : str , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): """simple docstring""" _SCREAMING_SNAKE_CASE = [self.cls_token_id] _SCREAMING_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 : Optional[int] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1] def lowerCAmelCase_ ( self : Dict , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): """simple docstring""" _SCREAMING_SNAKE_CASE = [self.sep_token_id] _SCREAMING_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 : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): """simple docstring""" _SCREAMING_SNAKE_CASE = self._tokenizer.model.save(__lowerCamelCase , name=__lowerCamelCase ) return tuple(__lowerCamelCase )
111
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase_ = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ 'CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'CTRLForSequenceClassification', 'CTRLLMHeadModel', 'CTRLModel', 'CTRLPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ 'TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCTRLForSequenceClassification', 'TFCTRLLMHeadModel', 'TFCTRLModel', 'TFCTRLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
111
1
def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = [] __A = set({"(", "[", "{"} ) __A = set({")", "]", "}"} ) __A = {"{": "}", "[": "]", "(": ")"} for i in range(len(a_ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(a_ ) == 0 or (len(a_ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(a_ ) == 0 def UpperCAmelCase ( ) -> str: """simple docstring""" __A = input("Enter sequence of brackets: " ) if is_balanced(a_ ): print(a_ , "is balanced" ) else: print(a_ , "is not balanced" ) if __name__ == "__main__": main()
15
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def lowerCamelCase__ (_UpperCAmelCase=None): if subparsers is not None: SCREAMING_SNAKE_CASE = subparsers.add_parser('env') else: SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Accelerate env command') parser.add_argument( '--config_file' , default=_UpperCAmelCase , help='The config file to use for the default values in the launching script.') if subparsers is not None: parser.set_defaults(func=_UpperCAmelCase) return parser def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.__version__ SCREAMING_SNAKE_CASE = torch.cuda.is_available() SCREAMING_SNAKE_CASE = is_xpu_available() SCREAMING_SNAKE_CASE = is_npu_available() SCREAMING_SNAKE_CASE = 'Not found' # Get the default from the config file. if args.config_file is not None or os.path.isfile(_UpperCAmelCase): SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file).to_dict() SCREAMING_SNAKE_CASE = { '`Accelerate` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'Numpy version': np.__version__, 'PyTorch version (GPU?)': F'''{pt_version} ({pt_cuda_available})''', 'PyTorch XPU available': str(_UpperCAmelCase), 'PyTorch NPU available': str(_UpperCAmelCase), 'System RAM': F'''{psutil.virtual_memory().total / 1024 ** 3:.2f} GB''', } if pt_cuda_available: SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print('\nCopy-and-paste the text below in your GitHub issue\n') print('\n'.join([F'''- {prop}: {val}''' for prop, val in info.items()])) print('- `Accelerate` default config:' if args.config_file is None else '- `Accelerate` config passed:') SCREAMING_SNAKE_CASE = ( '\n'.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]) if isinstance(_UpperCAmelCase , _UpperCAmelCase) else F'''\t{accelerate_config}''' ) print(_UpperCAmelCase) SCREAMING_SNAKE_CASE = accelerate_config return info def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = env_command_parser() SCREAMING_SNAKE_CASE = parser.parse_args() env_command(_UpperCAmelCase) return 0 if __name__ == "__main__": raise SystemExit(main())
137
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def SCREAMING_SNAKE_CASE__ ( __A ) -> str: _snake_case = SwinvaConfig() _snake_case = swinva_name.split('_' ) _snake_case = name_split[1] if "to" in name_split[3]: _snake_case = int(name_split[3][-3:] ) else: _snake_case = int(name_split[3] ) if "to" in name_split[2]: _snake_case = int(name_split[2][-2:] ) else: _snake_case = int(name_split[2][6:] ) if model_size == "tiny": _snake_case = 96 _snake_case = (2, 2, 6, 2) _snake_case = (3, 6, 12, 24) elif model_size == "small": _snake_case = 96 _snake_case = (2, 2, 18, 2) _snake_case = (3, 6, 12, 24) elif model_size == "base": _snake_case = 128 _snake_case = (2, 2, 18, 2) _snake_case = (4, 8, 16, 32) else: _snake_case = 192 _snake_case = (2, 2, 18, 2) _snake_case = (6, 12, 24, 48) if "to" in swinva_name: _snake_case = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): _snake_case = 21_841 _snake_case = 'huggingface/label-files' _snake_case = 'imagenet-22k-id2label.json' _snake_case = json.load(open(hf_hub_download(__A , __A , repo_type='dataset' ) , 'r' ) ) _snake_case = {int(__A ): v for k, v in idalabel.items()} _snake_case = idalabel _snake_case = {v: k for k, v in idalabel.items()} else: _snake_case = 1_000 _snake_case = 'huggingface/label-files' _snake_case = 'imagenet-1k-id2label.json' _snake_case = json.load(open(hf_hub_download(__A , __A , repo_type='dataset' ) , 'r' ) ) _snake_case = {int(__A ): v for k, v in idalabel.items()} _snake_case = idalabel _snake_case = {v: k for k, v in idalabel.items()} _snake_case = img_size _snake_case = num_classes _snake_case = embed_dim _snake_case = depths _snake_case = num_heads _snake_case = window_size return config def SCREAMING_SNAKE_CASE__ ( __A ) -> str: if "patch_embed.proj" in name: _snake_case = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: _snake_case = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: _snake_case = 'encoder.' + name if "attn.proj" in name: _snake_case = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: _snake_case = name.replace('attn' , 'attention.self' ) if "norm1" in name: _snake_case = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: _snake_case = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: _snake_case = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: _snake_case = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: _snake_case = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: _snake_case = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: _snake_case = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: _snake_case = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if name == "norm.weight": _snake_case = 'layernorm.weight' if name == "norm.bias": _snake_case = 'layernorm.bias' if "head" in name: _snake_case = name.replace('head' , 'classifier' ) else: _snake_case = 'swinv2.' + name return name def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> Dict: for key in orig_state_dict.copy().keys(): _snake_case = orig_state_dict.pop(__A ) if "mask" in key: continue elif "qkv" in key: _snake_case = key.split('.' ) _snake_case = int(key_split[1] ) _snake_case = int(key_split[3] ) _snake_case = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _snake_case = val[:dim, :] _snake_case = val[dim : dim * 2, :] _snake_case = val[-dim:, :] else: _snake_case = val[:dim] _snake_case = val[ dim : dim * 2 ] _snake_case = val[-dim:] else: _snake_case = val return orig_state_dict def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> Union[str, Any]: _snake_case = timm.create_model(__A , pretrained=__A ) timm_model.eval() _snake_case = get_swinva_config(__A ) _snake_case = SwinvaForImageClassification(__A ) model.eval() _snake_case = convert_state_dict(timm_model.state_dict() , __A ) model.load_state_dict(__A ) _snake_case = 'http://images.cocodataset.org/val2017/000000039769.jpg' _snake_case = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) ) _snake_case = Image.open(requests.get(__A , stream=__A ).raw ) _snake_case = image_processor(images=__A , return_tensors='pt' ) _snake_case = timm_model(inputs['pixel_values'] ) _snake_case = model(**__A ).logits assert torch.allclose(__A , __A , atol=1e-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__A ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__A ) model.push_to_hub( repo_path_or_name=Path(__A , __A ) , organization='nandwalritik' , commit_message='Add model' , ) if __name__ == "__main__": lowercase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swinv2_name", default="swinv2_tiny_patch4_window8_256", type=str, help="Name of the Swinv2 timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) lowercase : str = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
160
'''simple docstring''' def SCREAMING_SNAKE_CASE__ ( ) -> int: return [ a * b * (1_000 - a - b) for a in range(1 , 999 ) for b in range(__A , 999 ) if (a * a + b * b == (1_000 - a - b) ** 2) ][0] if __name__ == "__main__": print(F'''{solution() = }''')
160
1
'''simple docstring''' import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Any , __lowercase : Union[str, Any] , __lowercase : str=13 , __lowercase : Optional[Any]=7 , __lowercase : str=True , __lowercase : Any=True , __lowercase : Tuple=True , __lowercase : Any=True , __lowercase : Optional[int]=True , __lowercase : List[str]=False , __lowercase : Tuple=False , __lowercase : int=False , __lowercase : Optional[int]=2 , __lowercase : Any=99 , __lowercase : str=0 , __lowercase : Dict=32 , __lowercase : int=5 , __lowercase : Optional[int]=4 , __lowercase : Any=0.1 , __lowercase : str=0.1 , __lowercase : int=5_12 , __lowercase : str=2 , __lowercase : Optional[int]=0.02 , __lowercase : Optional[Any]=2 , __lowercase : List[str]=4 , __lowercase : Dict="last" , __lowercase : int=True , __lowercase : Dict=None , __lowercase : Union[str, Any]=0 , ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[int] =parent SCREAMING_SNAKE_CASE__ : Dict =batch_size SCREAMING_SNAKE_CASE__ : Tuple =seq_length SCREAMING_SNAKE_CASE__ : Tuple =is_training SCREAMING_SNAKE_CASE__ : Optional[Any] =use_input_lengths SCREAMING_SNAKE_CASE__ : List[str] =use_token_type_ids SCREAMING_SNAKE_CASE__ : Dict =use_labels SCREAMING_SNAKE_CASE__ : int =gelu_activation SCREAMING_SNAKE_CASE__ : Optional[int] =sinusoidal_embeddings SCREAMING_SNAKE_CASE__ : Tuple =causal SCREAMING_SNAKE_CASE__ : Optional[Any] =asm SCREAMING_SNAKE_CASE__ : int =n_langs SCREAMING_SNAKE_CASE__ : Tuple =vocab_size SCREAMING_SNAKE_CASE__ : List[Any] =n_special SCREAMING_SNAKE_CASE__ : List[Any] =hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] =num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict =num_attention_heads SCREAMING_SNAKE_CASE__ : int =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Dict =max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] =type_sequence_label_size SCREAMING_SNAKE_CASE__ : str =initializer_range SCREAMING_SNAKE_CASE__ : List[str] =num_labels SCREAMING_SNAKE_CASE__ : List[str] =num_choices SCREAMING_SNAKE_CASE__ : Optional[int] =summary_type SCREAMING_SNAKE_CASE__ : Any =use_proj SCREAMING_SNAKE_CASE__ : Optional[Any] =scope SCREAMING_SNAKE_CASE__ : Dict =bos_token_id def __magic_name__ ( self : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Any =None if self.use_input_lengths: SCREAMING_SNAKE_CASE__ : Optional[Any] =( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE__ : str =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[Any] =ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) SCREAMING_SNAKE_CASE__ : int =None SCREAMING_SNAKE_CASE__ : Optional[int] =None SCREAMING_SNAKE_CASE__ : Optional[int] =None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple =ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[int] =ids_tensor([self.batch_size] , 2 ).float() SCREAMING_SNAKE_CASE__ : str =ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Dict =self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __magic_name__ ( self : Tuple ) -> List[Any]: return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def __magic_name__ ( self : int , __lowercase : Optional[Any] , __lowercase : Tuple , __lowercase : Optional[int] , __lowercase : Union[str, Any] , __lowercase : Dict , __lowercase : Optional[Any] , __lowercase : int , __lowercase : int , __lowercase : List[str] , ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[str] =XLMModel(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Any =model(__lowercase , lengths=__lowercase , langs=__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase , langs=__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : Union[str, Any] , __lowercase : Optional[Any] , __lowercase : Optional[int] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Any , __lowercase : List[Any] , __lowercase : Tuple , __lowercase : Tuple , __lowercase : Dict , ) -> int: SCREAMING_SNAKE_CASE__ : str =XLMWithLMHeadModel(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase , token_type_ids=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : Optional[int] , __lowercase : Optional[int] , __lowercase : Dict , __lowercase : Optional[int] , __lowercase : Any , __lowercase : Optional[int] , __lowercase : Union[str, Any] , __lowercase : List[str] , __lowercase : str , __lowercase : Dict , ) -> List[str]: SCREAMING_SNAKE_CASE__ : Dict =XLMForQuestionAnsweringSimple(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : str =model(__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase , start_positions=__lowercase , end_positions=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =outputs 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 __magic_name__ ( self : List[str] , __lowercase : Dict , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : Optional[Any] , __lowercase : str , __lowercase : List[str] , __lowercase : List[Any] , __lowercase : Any , __lowercase : Optional[int] , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Union[str, Any] =XLMForQuestionAnswering(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] =model(__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =model( __lowercase , start_positions=__lowercase , end_positions=__lowercase , cls_index=__lowercase , is_impossible=__lowercase , p_mask=__lowercase , ) SCREAMING_SNAKE_CASE__ : Any =model( __lowercase , start_positions=__lowercase , end_positions=__lowercase , cls_index=__lowercase , is_impossible=__lowercase , ) (SCREAMING_SNAKE_CASE__ ) : List[str] =result_with_labels.to_tuple() SCREAMING_SNAKE_CASE__ : Union[str, Any] =model(__lowercase , start_positions=__lowercase , end_positions=__lowercase ) (SCREAMING_SNAKE_CASE__ ) : List[Any] =result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def __magic_name__ ( self : Dict , __lowercase : Dict , __lowercase : Optional[Any] , __lowercase : Optional[Any] , __lowercase : List[str] , __lowercase : List[str] , __lowercase : Any , __lowercase : Union[str, Any] , __lowercase : str , __lowercase : List[str] , ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] =XLMForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =model(__lowercase ) SCREAMING_SNAKE_CASE__ : Tuple =model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __magic_name__ ( self : Optional[Any] , __lowercase : str , __lowercase : int , __lowercase : str , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : List[str] , __lowercase : List[str] , __lowercase : Dict , __lowercase : Union[str, Any] , ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.num_labels SCREAMING_SNAKE_CASE__ : Tuple =XLMForTokenClassification(__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __magic_name__ ( self : str , __lowercase : Tuple , __lowercase : str , __lowercase : Any , __lowercase : str , __lowercase : str , __lowercase : str , __lowercase : str , __lowercase : List[str] , __lowercase : List[Any] , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : List[Any] =self.num_choices SCREAMING_SNAKE_CASE__ : Optional[Any] =XLMForMultipleChoice(config=__lowercase ) model.to(__lowercase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : List[str] =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Dict =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Any =model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __magic_name__ ( self : Tuple ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE__ ) : Union[str, Any] =config_and_inputs SCREAMING_SNAKE_CASE__ : Any ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): snake_case_ = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) snake_case_ = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable snake_case_ = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def __magic_name__ ( self : Any , __lowercase : List[Any] , __lowercase : Optional[Any] , __lowercase : str , __lowercase : str , __lowercase : str ) -> int: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('''Fast''' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __magic_name__ ( self : Any , __lowercase : Optional[Any] , __lowercase : Tuple , __lowercase : Tuple=False ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[Any] =super()._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": SCREAMING_SNAKE_CASE__ : str =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase ) return inputs_dict def __magic_name__ ( self : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : int =XLMModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[int] =ConfigTester(self , config_class=__lowercase , emb_dim=37 ) def __magic_name__ ( self : List[str] ) -> List[Any]: self.config_tester.run_common_tests() def __magic_name__ ( self : Dict ) -> List[Any]: SCREAMING_SNAKE_CASE__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*__lowercase ) def __magic_name__ ( self : List[Any] ) -> int: SCREAMING_SNAKE_CASE__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*__lowercase ) def __magic_name__ ( self : Tuple ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*__lowercase ) def __magic_name__ ( self : Optional[Any] ) -> Any: SCREAMING_SNAKE_CASE__ : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*__lowercase ) def __magic_name__ ( self : Tuple ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*__lowercase ) def __magic_name__ ( self : Any ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*__lowercase ) def __magic_name__ ( self : Optional[Any] , __lowercase : int , __lowercase : Tuple , __lowercase : Union[str, Any] , __lowercase : Dict , __lowercase : Optional[Any] , __lowercase : Optional[int]=False , __lowercase : Dict=1 ) -> Dict: self.assertIsInstance(__lowercase , __lowercase ) self.assertListEqual( [isinstance(__lowercase , __lowercase ) for iter_attentions in attentions] , [True] * len(__lowercase ) ) self.assertEqual(len(__lowercase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(__lowercase ): # adds PAD dummy token SCREAMING_SNAKE_CASE__ : int =min_length + idx + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] =min_length + idx + 1 SCREAMING_SNAKE_CASE__ : Any =( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(__lowercase ) ) def __magic_name__ ( self : Dict , __lowercase : int , __lowercase : Union[str, Any] , __lowercase : Union[str, Any] , __lowercase : Any , __lowercase : Optional[Any] , __lowercase : str=False , __lowercase : Optional[int]=1 ) -> Union[str, Any]: self.assertIsInstance(__lowercase , __lowercase ) self.assertListEqual( [isinstance(__lowercase , __lowercase ) for iter_hidden_states in hidden_states] , [True] * len(__lowercase ) , ) self.assertEqual(len(__lowercase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(__lowercase ): # adds PAD dummy token SCREAMING_SNAKE_CASE__ : Any =min_length + idx + 1 SCREAMING_SNAKE_CASE__ : str =(batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(__lowercase ) , ) pass @slow def __magic_name__ ( self : int ) -> Tuple: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] =XLMModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def __magic_name__ ( self : Tuple ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] =XLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048''' ) model.to(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =torch.tensor([[14, 4_47]] , dtype=torch.long , device=__lowercase ) # the president SCREAMING_SNAKE_CASE__ : Union[str, Any] =[ 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference SCREAMING_SNAKE_CASE__ : str =model.generate(__lowercase , do_sample=__lowercase ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , __lowercase )
152
import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL _a = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def _a ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : tuple , SCREAMING_SNAKE_CASE : Path , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[int]=False , ) -> str: """simple docstring""" output_path.parent.mkdir(parents=SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , f=output_path.as_posix() , input_names=SCREAMING_SNAKE_CASE , output_names=SCREAMING_SNAKE_CASE , dynamic_axes=SCREAMING_SNAKE_CASE , do_constant_folding=SCREAMING_SNAKE_CASE , use_external_data_format=SCREAMING_SNAKE_CASE , enable_onnx_checker=SCREAMING_SNAKE_CASE , opset_version=SCREAMING_SNAKE_CASE , ) else: export( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , f=output_path.as_posix() , input_names=SCREAMING_SNAKE_CASE , output_names=SCREAMING_SNAKE_CASE , dynamic_axes=SCREAMING_SNAKE_CASE , do_constant_folding=SCREAMING_SNAKE_CASE , opset_version=SCREAMING_SNAKE_CASE , ) @torch.no_grad() def _a ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : bool = False ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase: List[Any] = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): __lowerCAmelCase: str = 'cuda' elif fpaa and not torch.cuda.is_available(): raise ValueError('`float16` model export is only supported on GPUs with CUDA' ) else: __lowerCAmelCase: Dict = 'cpu' __lowerCAmelCase: Optional[int] = Path(SCREAMING_SNAKE_CASE ) # VAE DECODER __lowerCAmelCase: Optional[Any] = AutoencoderKL.from_pretrained(model_path + '/vae' ) __lowerCAmelCase: Union[str, Any] = vae_decoder.config.latent_channels # forward only through the decoder part __lowerCAmelCase: Any = vae_decoder.decode onnx_export( SCREAMING_SNAKE_CASE , model_args=( torch.randn(1 , SCREAMING_SNAKE_CASE , 25 , 25 ).to(device=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE ), False, ) , output_path=output_path / 'vae_decoder' / 'model.onnx' , ordered_input_names=['latent_sample', 'return_dict'] , output_names=['sample'] , dynamic_axes={ 'latent_sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'}, } , opset=SCREAMING_SNAKE_CASE , ) del vae_decoder if __name__ == "__main__": _a = argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=1_4, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') _a = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print('''SD: Done: ONNX''')
322
0
import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class lowercase : def __init__( self , A_ , A_=13 , A_=7 , A_=6 , A_=17 , A_=23 , A_=11 , A_=True , ) -> List[Any]: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = act_dim UpperCamelCase = state_dim UpperCamelCase = hidden_size UpperCamelCase = max_length UpperCamelCase = is_training def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, 1) ) UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, 1) ) UpperCamelCase = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1_000 ) UpperCamelCase = random_attention_mask((self.batch_size, self.seq_length) ) UpperCamelCase = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def __UpperCamelCase ( self ) -> Any: """simple docstring""" return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def __UpperCamelCase ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) -> Optional[int]: """simple docstring""" UpperCamelCase = DecisionTransformerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase = model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() ( UpperCamelCase ) = config_and_inputs UpperCamelCase = { '''states''': states, '''actions''': actions, '''rewards''': rewards, '''returns_to_go''': returns_to_go, '''timesteps''': timesteps, '''attention_mask''': attention_mask, } return config, inputs_dict @require_torch class lowercase ( a__ , a__ , a__ , unittest.TestCase ): __lowercase : Dict = (DecisionTransformerModel,) if is_torch_available() else () __lowercase : Tuple = () __lowercase : str = {'feature-extraction': DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids __lowercase : List[str] = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features __lowercase : int = False __lowercase : Optional[int] = False __lowercase : Optional[int] = False __lowercase : List[Any] = False __lowercase : Tuple = False __lowercase : str = False __lowercase : int = False __lowercase : List[str] = False __lowercase : List[Any] = False def __UpperCamelCase ( self ) -> Dict: """simple docstring""" UpperCamelCase = DecisionTransformerModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=37 ) def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) @slow def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = DecisionTransformerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_lowerCamelCase ) UpperCamelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = [ '''states''', '''actions''', '''rewards''', '''returns_to_go''', '''timesteps''', '''attention_mask''', ] self.assertListEqual(arg_names[: len(_lowerCamelCase )] , _lowerCamelCase ) @require_torch class lowercase ( unittest.TestCase ): @slow def __UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = 2 # number of steps of autoregressive prediction we will perform UpperCamelCase = 10 # defined by the RL environment, may be normalized UpperCamelCase = DecisionTransformerModel.from_pretrained('edbeeching/decision-transformer-gym-hopper-expert' ) UpperCamelCase = model.to(_lowerCamelCase ) UpperCamelCase = model.config torch.manual_seed(0 ) UpperCamelCase = torch.randn(1 , 1 , config.state_dim ).to(device=_lowerCamelCase , dtype=torch.floataa ) # env.reset() UpperCamelCase = torch.tensor( [[0.24_2793, -0.2869_3074, 0.874_2613], [0.6781_5274, -0.0810_1085, -0.1295_2147]] , device=_lowerCamelCase ) UpperCamelCase = torch.tensor(_lowerCamelCase , device=_lowerCamelCase , dtype=torch.floataa ).reshape(1 , 1 , 1 ) UpperCamelCase = state UpperCamelCase = torch.zeros(1 , 0 , config.act_dim , device=_lowerCamelCase , dtype=torch.floataa ) UpperCamelCase = torch.zeros(1 , 0 , device=_lowerCamelCase , dtype=torch.floataa ) UpperCamelCase = torch.tensor(0 , device=_lowerCamelCase , dtype=torch.long ).reshape(1 , 1 ) for step in range(_lowerCamelCase ): UpperCamelCase = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=_lowerCamelCase )] , dim=1 ) UpperCamelCase = torch.cat([rewards, torch.zeros(1 , 1 , device=_lowerCamelCase )] , dim=1 ) UpperCamelCase = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): UpperCamelCase = model( states=_lowerCamelCase , actions=_lowerCamelCase , rewards=_lowerCamelCase , returns_to_go=_lowerCamelCase , timesteps=_lowerCamelCase , attention_mask=_lowerCamelCase , return_dict=_lowerCamelCase , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1e-4 ) ) UpperCamelCase = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=_lowerCamelCase , dtype=torch.floataa ), 1.0, False, {}, ) UpperCamelCase = action_pred[0, -1] UpperCamelCase = torch.cat([states, state] , dim=1 ) UpperCamelCase = returns_to_go[0, -1] - reward UpperCamelCase = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) UpperCamelCase = torch.cat( [timesteps, torch.ones((1, 1) , device=_lowerCamelCase , dtype=torch.long ) * (step + 1)] , dim=1 )
369
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _UpperCAmelCase : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model") @require_sentencepiece @require_tokenizers class lowercase ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): __lowercase : Optional[Any] = GPTSwaTokenizer __lowercase : Optional[Any] = False __lowercase : Union[str, Any] = True __lowercase : Tuple = False def __UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase = GPTSwaTokenizer(A_ , eos_token='<unk>' , bos_token='<unk>' , pad_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self , A_ ) -> List[str]: """simple docstring""" UpperCamelCase = 'This is a test' UpperCamelCase = 'This is a test' return input_text, output_text def __UpperCamelCase ( self ) -> int: """simple docstring""" UpperCamelCase = '<s>' UpperCamelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_ ) , A_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_ ) , A_ ) def __UpperCamelCase ( self ) -> Dict: """simple docstring""" UpperCamelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(A_ ) , 2_000 ) def __UpperCamelCase ( self ) -> Any: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 2_000 ) def __UpperCamelCase ( self ) -> int: """simple docstring""" UpperCamelCase = GPTSwaTokenizer(A_ ) UpperCamelCase = tokenizer.tokenize('This is a test' ) self.assertListEqual(A_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [465, 287, 265, 631, 842] ) UpperCamelCase = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) # fmt: off self.assertListEqual( A_ , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] , ) # fmt: on UpperCamelCase = tokenizer.convert_tokens_to_ids(A_ ) self.assertListEqual( A_ , [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) UpperCamelCase = tokenizer.convert_ids_to_tokens(A_ ) # fmt: off self.assertListEqual( A_ , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] ) # fmt: on def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" UpperCamelCase = GPTSwaTokenizer(A_ ) UpperCamelCase = ['This is a test', 'I was born in 92000, and this is falsé.'] UpperCamelCase = [ [465, 287, 265, 631, 842], [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(A_ , A_ ): self.assertListEqual(tokenizer.encode_fast(A_ ) , A_ ) # Test that decode_fast returns the input text for text, token_ids in zip(A_ , A_ ): self.assertEqual(tokenizer.decode_fast(A_ ) , A_ ) @slow def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = [ '<|python|>def fibonacci(n)\n if n < 0:\n print(\'Incorrect input\')', 'Hey there, how are you doing this fine day?', 'This is a text with a trailing spaces followed by a dot .', 'Häj sväjs lillebrör! =)', 'Det är inget fel på Mr. Cool', ] # fmt: off UpperCamelCase = {'input_ids': [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=A_ , model_name='AI-Sweden/gpt-sw3-126m' , sequences=A_ , )
110
0
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __a :str = logging.get_logger(__name__) __a :Union[str, Any] = OrderedDict( [ ('audio-spectrogram-transformer', 'ASTFeatureExtractor'), ('beit', 'BeitFeatureExtractor'), ('chinese_clip', 'ChineseCLIPFeatureExtractor'), ('clap', 'ClapFeatureExtractor'), ('clip', 'CLIPFeatureExtractor'), ('clipseg', 'ViTFeatureExtractor'), ('conditional_detr', 'ConditionalDetrFeatureExtractor'), ('convnext', 'ConvNextFeatureExtractor'), ('cvt', 'ConvNextFeatureExtractor'), ('data2vec-audio', 'Wav2Vec2FeatureExtractor'), ('data2vec-vision', 'BeitFeatureExtractor'), ('deformable_detr', 'DeformableDetrFeatureExtractor'), ('deit', 'DeiTFeatureExtractor'), ('detr', 'DetrFeatureExtractor'), ('dinat', 'ViTFeatureExtractor'), ('donut-swin', 'DonutFeatureExtractor'), ('dpt', 'DPTFeatureExtractor'), ('encodec', 'EncodecFeatureExtractor'), ('flava', 'FlavaFeatureExtractor'), ('glpn', 'GLPNFeatureExtractor'), ('groupvit', 'CLIPFeatureExtractor'), ('hubert', 'Wav2Vec2FeatureExtractor'), ('imagegpt', 'ImageGPTFeatureExtractor'), ('layoutlmv2', 'LayoutLMv2FeatureExtractor'), ('layoutlmv3', 'LayoutLMv3FeatureExtractor'), ('levit', 'LevitFeatureExtractor'), ('maskformer', 'MaskFormerFeatureExtractor'), ('mctct', 'MCTCTFeatureExtractor'), ('mobilenet_v1', 'MobileNetV1FeatureExtractor'), ('mobilenet_v2', 'MobileNetV2FeatureExtractor'), ('mobilevit', 'MobileViTFeatureExtractor'), ('nat', 'ViTFeatureExtractor'), ('owlvit', 'OwlViTFeatureExtractor'), ('perceiver', 'PerceiverFeatureExtractor'), ('poolformer', 'PoolFormerFeatureExtractor'), ('regnet', 'ConvNextFeatureExtractor'), ('resnet', 'ConvNextFeatureExtractor'), ('segformer', 'SegformerFeatureExtractor'), ('sew', 'Wav2Vec2FeatureExtractor'), ('sew-d', 'Wav2Vec2FeatureExtractor'), ('speech_to_text', 'Speech2TextFeatureExtractor'), ('speecht5', 'SpeechT5FeatureExtractor'), ('swiftformer', 'ViTFeatureExtractor'), ('swin', 'ViTFeatureExtractor'), ('swinv2', 'ViTFeatureExtractor'), ('table-transformer', 'DetrFeatureExtractor'), ('timesformer', 'VideoMAEFeatureExtractor'), ('tvlt', 'TvltFeatureExtractor'), ('unispeech', 'Wav2Vec2FeatureExtractor'), ('unispeech-sat', 'Wav2Vec2FeatureExtractor'), ('van', 'ConvNextFeatureExtractor'), ('videomae', 'VideoMAEFeatureExtractor'), ('vilt', 'ViltFeatureExtractor'), ('vit', 'ViTFeatureExtractor'), ('vit_mae', 'ViTFeatureExtractor'), ('vit_msn', 'ViTFeatureExtractor'), ('wav2vec2', 'Wav2Vec2FeatureExtractor'), ('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'), ('wavlm', 'Wav2Vec2FeatureExtractor'), ('whisper', 'WhisperFeatureExtractor'), ('xclip', 'CLIPFeatureExtractor'), ('yolos', 'YolosFeatureExtractor'), ] ) __a :Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def __snake_case ( __UpperCamelCase : str ): """simple docstring""" for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: A_ = model_type_to_module_name(__UpperCamelCase ) A_ = importlib.import_module(f'''.{module_name}''' ,"transformers.models" ) try: return getattr(__UpperCamelCase ,__UpperCamelCase ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(__UpperCamelCase ,"__name__" ,__UpperCamelCase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. A_ = importlib.import_module("transformers" ) if hasattr(__UpperCamelCase ,__UpperCamelCase ): return getattr(__UpperCamelCase ,__UpperCamelCase ) return None def __snake_case ( __UpperCamelCase : Union[str, os.PathLike] ,__UpperCamelCase : Optional[Union[str, os.PathLike]] = None ,__UpperCamelCase : bool = False ,__UpperCamelCase : bool = False ,__UpperCamelCase : Optional[Dict[str, str]] = None ,__UpperCamelCase : Optional[Union[bool, str]] = None ,__UpperCamelCase : Optional[str] = None ,__UpperCamelCase : bool = False ,**__UpperCamelCase : List[Any] ,): """simple docstring""" A_ = get_file_from_repo( __UpperCamelCase ,__UpperCamelCase ,cache_dir=__UpperCamelCase ,force_download=__UpperCamelCase ,resume_download=__UpperCamelCase ,proxies=__UpperCamelCase ,use_auth_token=__UpperCamelCase ,revision=__UpperCamelCase ,local_files_only=__UpperCamelCase ,) if resolved_config_file is None: logger.info( "Could not locate the feature extractor configuration file, will try to use the model config instead." ) return {} with open(__UpperCamelCase ,encoding="utf-8" ) as reader: return json.load(__UpperCamelCase ) class _a : """simple docstring""" def __init__( self : List[str] ): raise EnvironmentError( "AutoFeatureExtractor is designed to be instantiated " "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(SCREAMING_SNAKE_CASE_ ) def __A ( cls : int , UpperCAmelCase : List[str] , **UpperCAmelCase : int ): A_ = kwargs.pop("config" , SCREAMING_SNAKE_CASE_ ) A_ = kwargs.pop("trust_remote_code" , SCREAMING_SNAKE_CASE_ ) A_ = True A_ , A_ = FeatureExtractionMixin.get_feature_extractor_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A_ = config_dict.get("feature_extractor_type" , SCREAMING_SNAKE_CASE_ ) A_ = None if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): A_ = config_dict["auto_map"]["AutoFeatureExtractor"] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # It could be in `config.feature_extractor_type`` A_ = getattr(SCREAMING_SNAKE_CASE_ , "feature_extractor_type" , SCREAMING_SNAKE_CASE_ ) if hasattr(SCREAMING_SNAKE_CASE_ , "auto_map" ) and "AutoFeatureExtractor" in config.auto_map: A_ = config.auto_map["AutoFeatureExtractor"] if feature_extractor_class is not None: A_ = feature_extractor_class_from_name(SCREAMING_SNAKE_CASE_ ) A_ = feature_extractor_auto_map is not None A_ = feature_extractor_class is not None or type(SCREAMING_SNAKE_CASE_ ) in FEATURE_EXTRACTOR_MAPPING A_ = resolve_trust_remote_code( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if has_remote_code and trust_remote_code: A_ = get_class_from_dynamic_module( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A_ = kwargs.pop("code_revision" , SCREAMING_SNAKE_CASE_ ) if os.path.isdir(SCREAMING_SNAKE_CASE_ ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(SCREAMING_SNAKE_CASE_ ) in FEATURE_EXTRACTOR_MAPPING: A_ = FEATURE_EXTRACTOR_MAPPING[type(SCREAMING_SNAKE_CASE_ )] return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) raise ValueError( f'''Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ''' f'''`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def __A ( UpperCAmelCase : Optional[Any] , UpperCAmelCase : List[Any] ): FEATURE_EXTRACTOR_MAPPING.register(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
312
def A_ ( snake_case : int ) -> None: '''simple docstring''' __UpperCamelCase = generate_pascal_triangle(snake_case ) for row_idx in range(snake_case ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=''' ''' ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=''' ''' ) else: print(triangle[row_idx][col_idx] , end='''''' ) print() def A_ ( snake_case : int ) -> list[list[int]]: '''simple docstring''' if not isinstance(snake_case , snake_case ): raise TypeError('''The input value of \'num_rows\' should be \'int\'''' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( '''The input value of \'num_rows\' should be greater than or equal to 0''' ) __UpperCamelCase = [] for current_row_idx in range(snake_case ): __UpperCamelCase = populate_current_row(snake_case , snake_case ) triangle.append(snake_case ) return triangle def A_ ( snake_case : list[list[int]] , snake_case : int ) -> list[int]: '''simple docstring''' __UpperCamelCase = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 __UpperCamelCase , __UpperCamelCase = 1, 1 for current_col_idx in range(1 , snake_case ): calculate_current_element( snake_case , snake_case , snake_case , snake_case ) return current_row def A_ ( snake_case : list[list[int]] , snake_case : list[int] , snake_case : int , snake_case : int , ) -> None: '''simple docstring''' __UpperCamelCase = triangle[current_row_idx - 1][current_col_idx - 1] __UpperCamelCase = triangle[current_row_idx - 1][current_col_idx] __UpperCamelCase = above_to_left_elt + above_to_right_elt def A_ ( snake_case : int ) -> list[list[int]]: '''simple docstring''' if not isinstance(snake_case , snake_case ): raise TypeError('''The input value of \'num_rows\' should be \'int\'''' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( '''The input value of \'num_rows\' should be greater than or equal to 0''' ) __UpperCamelCase = [[1]] for row_index in range(1 , snake_case ): __UpperCamelCase = [0] + result[-1] + [0] __UpperCamelCase = row_index + 1 # Calculate the number of distinct elements in a row __UpperCamelCase = sum(divmod(snake_case , 2 ) ) __UpperCamelCase = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] __UpperCamelCase = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() __UpperCamelCase = row_first_half + row_second_half result.append(snake_case ) return result def A_ ( ) -> None: '''simple docstring''' from collections.abc import Callable from timeit import timeit def benchmark_a_function(snake_case : Callable , snake_case : int ) -> None: __UpperCamelCase = f"{func.__name__}({value})" __UpperCamelCase = timeit(f"__main__.{call}" , setup='''import __main__''' ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f"{call:38} -- {timing:.4f} seconds" ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(snake_case , snake_case ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
328
0
'''simple docstring''' from __future__ import annotations class _lowerCAmelCase : '''simple docstring''' def __init__(self , UpperCAmelCase ) -> None: _snake_case = order # a_{0} ... a_{k} _snake_case = [1.0] + [0.0] * order # b_{0} ... b_{k} _snake_case = [1.0] + [0.0] * order # x[n-1] ... x[n-k] _snake_case = [0.0] * self.order # y[n-1] ... y[n-k] _snake_case = [0.0] * self.order def lowercase (self , UpperCAmelCase , UpperCAmelCase ) -> None: if len(UpperCAmelCase ) < self.order: _snake_case = [1.0, *a_coeffs] if len(UpperCAmelCase ) != self.order + 1: _snake_case = ( f"""Expected a_coeffs to have {self.order + 1} elements """ f"""for {self.order}-order filter, got {len(UpperCAmelCase )}""" ) raise ValueError(UpperCAmelCase ) if len(UpperCAmelCase ) != self.order + 1: _snake_case = ( f"""Expected b_coeffs to have {self.order + 1} elements """ f"""for {self.order}-order filter, got {len(UpperCAmelCase )}""" ) raise ValueError(UpperCAmelCase ) _snake_case = a_coeffs _snake_case = b_coeffs def lowercase (self , UpperCAmelCase ) -> float: _snake_case = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) _snake_case = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] _snake_case = self.input_history[:-1] _snake_case = self.output_history[:-1] _snake_case = sample _snake_case = result return result
353
'''simple docstring''' import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( 'The `inpainting.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionInpaintPipeline` instead.' )
270
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { '''Salesforce/instruct-blip-flan-t5''': '''https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json''', } class A__ ( _snake_case ): lowercase = "instructblip_vision_model" def __init__( self , UpperCamelCase__=1408 , UpperCamelCase__=6144 , UpperCamelCase__=39 , UpperCamelCase__=16 , UpperCamelCase__=224 , UpperCamelCase__=14 , UpperCamelCase__="gelu" , UpperCamelCase__=1e-6 , UpperCamelCase__=0.0 , UpperCamelCase__=1e-1_0 , UpperCamelCase__=True , **UpperCamelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__(**UpperCamelCase__ ) A_ = hidden_size A_ = intermediate_size A_ = num_hidden_layers A_ = num_attention_heads A_ = patch_size A_ = image_size A_ = initializer_range A_ = attention_dropout A_ = layer_norm_eps A_ = hidden_act A_ = qkv_bias @classmethod def snake_case_ ( cls , UpperCamelCase__ , **UpperCamelCase__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(UpperCamelCase__ ) A_ , A_ = cls.get_config_dict(UpperCamelCase__ , **UpperCamelCase__ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get("""model_type""" ) == "instructblip": A_ = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCamelCase__ , **UpperCamelCase__ ) class A__ ( _snake_case ): lowercase = "instructblip_qformer" def __init__( self , UpperCamelCase__=30522 , UpperCamelCase__=768 , UpperCamelCase__=12 , UpperCamelCase__=12 , UpperCamelCase__=3072 , UpperCamelCase__="gelu" , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=512 , UpperCamelCase__=0.02 , UpperCamelCase__=1e-1_2 , UpperCamelCase__=0 , UpperCamelCase__="absolute" , UpperCamelCase__=2 , UpperCamelCase__=1408 , **UpperCamelCase__ , ) -> int: '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) A_ = vocab_size A_ = hidden_size A_ = num_hidden_layers A_ = num_attention_heads A_ = hidden_act A_ = intermediate_size A_ = hidden_dropout_prob A_ = attention_probs_dropout_prob A_ = max_position_embeddings A_ = initializer_range A_ = layer_norm_eps A_ = position_embedding_type A_ = cross_attention_frequency A_ = encoder_hidden_size @classmethod def snake_case_ ( cls , UpperCamelCase__ , **UpperCamelCase__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(UpperCamelCase__ ) A_ , A_ = cls.get_config_dict(UpperCamelCase__ , **UpperCamelCase__ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get("""model_type""" ) == "instructblip": A_ = config_dict["""qformer_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(UpperCamelCase__ , **UpperCamelCase__ ) class A__ ( _snake_case ): lowercase = "instructblip" lowercase = True def __init__( self , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=32 , **UpperCamelCase__ ) -> Any: '''simple docstring''' super().__init__(**UpperCamelCase__ ) if vision_config is None: A_ = {} logger.info("""vision_config is None. initializing the InstructBlipVisionConfig with default values.""" ) if qformer_config is None: A_ = {} logger.info("""qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.""" ) if text_config is None: A_ = {} logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" ) A_ = InstructBlipVisionConfig(**UpperCamelCase__ ) A_ = InstructBlipQFormerConfig(**UpperCamelCase__ ) A_ = text_config["""model_type"""] if """model_type""" in text_config else """opt""" A_ = CONFIG_MAPPING[text_model_type](**UpperCamelCase__ ) A_ = self.text_config.tie_word_embeddings A_ = self.text_config.is_encoder_decoder A_ = num_query_tokens A_ = self.vision_config.hidden_size A_ = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES A_ = 1.0 A_ = 0.02 @classmethod def snake_case_ ( cls , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ , ) -> str: '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **UpperCamelCase__ , ) def snake_case_ ( self ) -> List[str]: '''simple docstring''' A_ = copy.deepcopy(self.__dict__ ) A_ = self.vision_config.to_dict() A_ = self.qformer_config.to_dict() A_ = self.text_config.to_dict() A_ = self.__class__.model_type return output
162
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( _snake_case ): lowercase = "roc_bert" def __init__( self , UpperCamelCase__=30522 , UpperCamelCase__=768 , UpperCamelCase__=12 , UpperCamelCase__=12 , UpperCamelCase__=3072 , UpperCamelCase__="gelu" , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=512 , UpperCamelCase__=2 , UpperCamelCase__=0.02 , UpperCamelCase__=1e-1_2 , UpperCamelCase__=True , UpperCamelCase__=0 , UpperCamelCase__="absolute" , UpperCamelCase__=None , UpperCamelCase__=True , UpperCamelCase__=True , UpperCamelCase__=768 , UpperCamelCase__=910 , UpperCamelCase__=512 , UpperCamelCase__=24858 , UpperCamelCase__=True , **UpperCamelCase__ , ) -> Tuple: '''simple docstring''' A_ = vocab_size A_ = max_position_embeddings A_ = hidden_size A_ = num_hidden_layers A_ = num_attention_heads A_ = intermediate_size A_ = hidden_act A_ = hidden_dropout_prob A_ = attention_probs_dropout_prob A_ = initializer_range A_ = type_vocab_size A_ = layer_norm_eps A_ = use_cache A_ = enable_pronunciation A_ = enable_shape A_ = pronunciation_embed_dim A_ = pronunciation_vocab_size A_ = shape_embed_dim A_ = shape_vocab_size A_ = concat_input A_ = position_embedding_type A_ = classifier_dropout super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
162
1
from typing import Union import fire import torch from tqdm import tqdm def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = "cpu" , UpperCamelCase__ = None ) -> None: __lowerCamelCase = torch.load(UpperCamelCase__ , map_location=UpperCamelCase__ ) for k, v in tqdm(state_dict.items() ): if not isinstance(UpperCamelCase__ , torch.Tensor ): raise TypeError('''FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin''' ) __lowerCamelCase = v.half() if save_path is None: # overwrite src_path __lowerCamelCase = src_path torch.save(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": fire.Fire(convert)
363
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase ={ "configuration_whisper": ["WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP", "WhisperConfig", "WhisperOnnxConfig"], "feature_extraction_whisper": ["WhisperFeatureExtractor"], "processing_whisper": ["WhisperProcessor"], "tokenization_whisper": ["WhisperTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =["WhisperTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST", "WhisperForConditionalGeneration", "WhisperModel", "WhisperPreTrainedModel", "WhisperForAudioClassification", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWhisperForConditionalGeneration", "TFWhisperModel", "TFWhisperPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "FlaxWhisperForConditionalGeneration", "FlaxWhisperModel", "FlaxWhisperPreTrainedModel", "FlaxWhisperForAudioClassification", ] if TYPE_CHECKING: from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig from .feature_extraction_whisper import WhisperFeatureExtractor from .processing_whisper import WhisperProcessor from .tokenization_whisper import WhisperTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_whisper_fast import WhisperTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForAudioClassification, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_whisper import ( FlaxWhisperForAudioClassification, FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
237
0
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> int: """simple docstring""" lowerCamelCase__ , lowerCamelCase__: int =len(__a ), len(grid[0] ) if ( min(__a , __a ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) lowerCamelCase__: Dict =0 count += depth_first_search(__a , row + 1 , __a , __a ) count += depth_first_search(__a , row - 1 , __a , __a ) count += depth_first_search(__a , __a , col + 1 , __a ) count += depth_first_search(__a , __a , col - 1 , __a ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
10
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE__ : int = { 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE__ : str = { 'xlnet-base-cased': None, 'xlnet-large-cased': None, } # Segments (not really needed) SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = 1 SCREAMING_SNAKE_CASE__ : Optional[int] = 2 SCREAMING_SNAKE_CASE__ : List[str] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = 4 class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Dict = VOCAB_FILES_NAMES lowerCamelCase_ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ : List[str] = """left""" def __init__( self , UpperCamelCase__ , UpperCamelCase__=False , UpperCamelCase__=True , UpperCamelCase__=False , UpperCamelCase__="<s>" , UpperCamelCase__="</s>" , UpperCamelCase__="<unk>" , UpperCamelCase__="<sep>" , UpperCamelCase__="<pad>" , UpperCamelCase__="<cls>" , UpperCamelCase__="<mask>" , UpperCamelCase__=["<eop>", "<eod>"] , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase : str = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else mask_token lowerCamelCase : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCamelCase__ , remove_space=UpperCamelCase__ , keep_accents=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase__ , ) lowerCamelCase : Any = 3 lowerCamelCase : Optional[Any] = do_lower_case lowerCamelCase : List[Any] = remove_space lowerCamelCase : str = keep_accents lowerCamelCase : List[Any] = vocab_file lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCamelCase__ ) @property def _lowercase ( self ) -> Optional[Any]: return len(self.sp_model ) def _lowercase ( self ) -> Optional[int]: lowerCamelCase : int = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Optional[Any]: lowerCamelCase : Optional[int] = self.__dict__.copy() lowerCamelCase : Union[str, Any] = None return state def __setstate__( self , UpperCamelCase__ ) -> int: lowerCamelCase : int = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase : Any = {} lowerCamelCase : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowercase ( self , UpperCamelCase__ ) -> Any: if self.remove_space: lowerCamelCase : Dict = " ".join(inputs.strip().split() ) else: lowerCamelCase : Union[str, Any] = inputs lowerCamelCase : Optional[Any] = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: lowerCamelCase : Optional[int] = unicodedata.normalize("NFKD" , UpperCamelCase__ ) lowerCamelCase : List[Any] = "".join([c for c in outputs if not unicodedata.combining(UpperCamelCase__ )] ) if self.do_lower_case: lowerCamelCase : List[str] = outputs.lower() return outputs def _lowercase ( self , UpperCamelCase__ ) -> List[str]: lowerCamelCase : Optional[Any] = self.preprocess_text(UpperCamelCase__ ) lowerCamelCase : Dict = self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ ) lowerCamelCase : Dict = [] for piece in pieces: if len(UpperCamelCase__ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): lowerCamelCase : List[Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase__ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: lowerCamelCase : Optional[int] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCamelCase__ ) else: new_pieces.append(UpperCamelCase__ ) return new_pieces def _lowercase ( self , UpperCamelCase__ ) -> int: return self.sp_model.PieceToId(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ ) -> Tuple: return self.sp_model.IdToPiece(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ ) -> List[str]: lowerCamelCase : Union[str, Any] = "".join(UpperCamelCase__ ).replace(UpperCamelCase__ , " " ).strip() return out_string def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = False , UpperCamelCase__ = None , UpperCamelCase__ = True , **UpperCamelCase__ , ) -> str: lowerCamelCase : Optional[int] = kwargs.pop("use_source_tokenizer" , UpperCamelCase__ ) lowerCamelCase : Optional[int] = self.convert_ids_to_tokens(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCamelCase : Any = [] lowerCamelCase : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__ ) ) lowerCamelCase : int = [] sub_texts.append(UpperCamelCase__ ) else: current_sub_text.append(UpperCamelCase__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase : Union[str, Any] = "".join(UpperCamelCase__ ) lowerCamelCase : Tuple = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase : int = self.clean_up_tokenization(UpperCamelCase__ ) return clean_text else: return text def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> List[int]: lowerCamelCase : str = [self.sep_token_id] lowerCamelCase : Optional[int] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase__ , token_ids_a=UpperCamelCase__ , already_has_special_tokens=UpperCamelCase__ ) if token_ids_a is not None: return ([0] * len(UpperCamelCase__ )) + [1] + ([0] * len(UpperCamelCase__ )) + [1, 1] return ([0] * len(UpperCamelCase__ )) + [1, 1] def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> List[int]: lowerCamelCase : Any = [self.sep_token_id] lowerCamelCase : List[str] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> Tuple[str]: if not os.path.isdir(UpperCamelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase : Union[str, Any] = os.path.join( UpperCamelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase__ , "wb" ) as fi: lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase__ ) return (out_vocab_file,)
48
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys _A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
355
from math import pow, sqrt def lowerCamelCase__ ( *a__ : float ) -> bool: UpperCamelCase_ = len(a__ ) > 0 and all(value > 0.0 for value in values ) return result def lowerCamelCase__ ( a__ : float , a__ : float ) -> float | ValueError: return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(a__ , a__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def lowerCamelCase__ ( a__ : float , a__ : float , a__ : float ) -> float | ValueError: return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(a__ , a__ , a__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase__ ( a__ : float , a__ : float , a__ : float ) -> float | ValueError: return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(a__ , a__ , a__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase__ ( a__ : float , a__ : float , a__ : float ) -> float | ValueError: return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(a__ , a__ , a__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase__ ( a__ : float , a__ : float , a__ : float ) -> float | ValueError: return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(a__ , a__ , a__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
261
0
import random def _a ( a :int ) -> bool: a = num - 1 a = 0 while s % 2 == 0: a = s // 2 t += 1 for _ in range(5 ): a = random.randrange(2 , num - 1 ) a = pow(a , a , a ) if v != 1: a = 0 while v != (num - 1): if i == t - 1: return False else: a = i + 1 a = (v**2) % num return True def _a ( a :int ) -> bool: if num < 2: return False a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(a ) def _a ( a :int = 1_024 ) -> int: while True: a = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(a ): return num if __name__ == "__main__": UpperCAmelCase__ = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
0
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class _a ( unittest.TestCase ): def __snake_case (self ) -> Tuple: if self.framework == "pytorch": subprocess.run( f'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split(), encoding="""utf-8""", check=lowerCamelCase__, ) assert hasattr(self, """env""" ) def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Any: # configuration for running training on smdistributed Model Parallel UpperCAmelCase_: Optional[Any] = { """enabled""": True, """processes_per_host""": 8, } UpperCAmelCase_: int = { """enabled""": True, """parameters""": { """microbatches""": 4, """placement_strategy""": """spread""", """pipeline""": """interleaved""", """optimize""": """speed""", """partitions""": 4, """ddp""": True, }, } UpperCAmelCase_: Dict = {"""smdistributed""": {"""modelparallel""": smp_options}, """mpi""": mpi_options} UpperCAmelCase_: int = """trainer""" if self.script == """run_glue.py""" else """smtrainer""" # creates estimator return HuggingFace( entry_point=self.script, source_dir=self.env.test_path, role=self.env.role, image_uri=self.env.image_uri, base_job_name=f'{self.env.base_job_name}-{instance_count}-smp-{name_extension}', instance_count=lowerCamelCase__, instance_type=self.instance_type, debugger_hook_config=lowerCamelCase__, hyperparameters={ **self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path, """max_steps""": 500, }, metric_definitions=self.env.metric_definitions, distribution=lowerCamelCase__, py_version="""py36""", ) def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Tuple: TrainingJobAnalytics(lowerCamelCase__ ).export_csv(f'{self.env.test_path}/{job_name}_metrics.csv' ) @parameterized.expand([(1,)] ) def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: # create estimator UpperCAmelCase_: Any = self.create_estimator(lowerCamelCase__ ) # run training estimator.fit() # result dataframe UpperCAmelCase_: Any = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis UpperCAmelCase_: Optional[Any] = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""] ) UpperCAmelCase_: Optional[Any] = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping UpperCAmelCase_: Union[str, Any] = ( Session().describe_training_job(estimator.latest_training_job.name ).get("""TrainingTimeInSeconds""", 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy ) assert all(t <= self.results["""eval_loss"""] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'{estimator.latest_training_job.name}.json', """w""" ) as outfile: json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss}, lowerCamelCase__ )
357
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer a : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a : str = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } a : Dict = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } a : Optional[Any] = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class _a ( _lowerCAmelCase ): A = VOCAB_FILES_NAMES A = PRETRAINED_VOCAB_FILES_MAP A = PRETRAINED_INIT_CONFIGURATION A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A = ElectraTokenizer def __init__(self, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_="[UNK]", SCREAMING_SNAKE_CASE_="[SEP]", SCREAMING_SNAKE_CASE_="[PAD]", SCREAMING_SNAKE_CASE_="[CLS]", SCREAMING_SNAKE_CASE_="[MASK]", SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=None, **SCREAMING_SNAKE_CASE_, ) -> Optional[int]: super().__init__( SCREAMING_SNAKE_CASE_, tokenizer_file=SCREAMING_SNAKE_CASE_, do_lower_case=SCREAMING_SNAKE_CASE_, unk_token=SCREAMING_SNAKE_CASE_, sep_token=SCREAMING_SNAKE_CASE_, pad_token=SCREAMING_SNAKE_CASE_, cls_token=SCREAMING_SNAKE_CASE_, mask_token=SCREAMING_SNAKE_CASE_, tokenize_chinese_chars=SCREAMING_SNAKE_CASE_, strip_accents=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, ) UpperCAmelCase_: List[str] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""", SCREAMING_SNAKE_CASE_ ) != do_lower_case or normalizer_state.get("""strip_accents""", SCREAMING_SNAKE_CASE_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""", SCREAMING_SNAKE_CASE_ ) != tokenize_chinese_chars ): UpperCAmelCase_: Optional[int] = getattr(SCREAMING_SNAKE_CASE_, normalizer_state.pop("""type""" ) ) UpperCAmelCase_: Union[str, Any] = do_lower_case UpperCAmelCase_: Dict = strip_accents UpperCAmelCase_: List[Any] = tokenize_chinese_chars UpperCAmelCase_: int = normalizer_class(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Tuple = do_lower_case def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=None ) -> Optional[Any]: UpperCAmelCase_: Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> List[int]: UpperCAmelCase_: Optional[int] = [self.sep_token_id] UpperCAmelCase_: Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: UpperCAmelCase_: Tuple = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_, name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
82
0
import unittest from transformers import DonutProcessor lowerCamelCase = '''naver-clova-ix/donut-base''' class _a ( unittest.TestCase): def UpperCAmelCase__( self : str )-> int: lowerCAmelCase__ : Any = DonutProcessor.from_pretrained(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__( self : Optional[int] )-> List[Any]: lowerCAmelCase__ : Dict = { '''name''': '''John Doe''', '''age''': '''99''', '''city''': '''Atlanta''', '''state''': '''GA''', '''zip''': '''30301''', '''phone''': '''123-4567''', '''nicknames''': [{'''nickname''': '''Johnny'''}, {'''nickname''': '''JD'''}], } lowerCAmelCase__ : Any = ( '''<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>''' '''<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>''' '''<s_nicknames><s_nickname>Johnny</s_nickname>''' '''<sep/><s_nickname>JD</s_nickname></s_nicknames>''' ) lowerCAmelCase__ : str = self.processor.tokenajson(_SCREAMING_SNAKE_CASE ) self.assertDictEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
131
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase = logging.get_logger() @dataclass class _a : _a : nn.Module _a : List[nn.Module] = field(default_factory=_lowercase) _a : list = field(default_factory=_lowercase) def UpperCAmelCase__( self : Tuple , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Tensor , _SCREAMING_SNAKE_CASE : Tensor )-> Any: lowerCAmelCase__ : str = len(list(m.modules() ) ) == 1 or isinstance(_SCREAMING_SNAKE_CASE , nn.Convad ) or isinstance(_SCREAMING_SNAKE_CASE , nn.BatchNormad ) if has_not_submodules: self.traced.append(_SCREAMING_SNAKE_CASE ) def __call__( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : Tensor )-> str: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(_SCREAMING_SNAKE_CASE ) [x.remove() for x in self.handles] return self @property def UpperCAmelCase__( self : Any )-> Union[str, Any]: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda _SCREAMING_SNAKE_CASE : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class _a : _a : nn.Module _a : nn.Module _a : int = 1 _a : List = field(default_factory=_lowercase) _a : List = field(default_factory=_lowercase) _a : bool = True def __call__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : Tensor )-> str: lowerCAmelCase__ : List[Any] = Tracker(self.dest )(_SCREAMING_SNAKE_CASE ).parametrized lowerCAmelCase__ : str = Tracker(self.src )(_SCREAMING_SNAKE_CASE ).parametrized lowerCAmelCase__ : List[str] = list(filter(lambda _SCREAMING_SNAKE_CASE : type(_SCREAMING_SNAKE_CASE ) not in self.src_skip , _SCREAMING_SNAKE_CASE ) ) lowerCAmelCase__ : str = list(filter(lambda _SCREAMING_SNAKE_CASE : type(_SCREAMING_SNAKE_CASE ) not in self.dest_skip , _SCREAMING_SNAKE_CASE ) ) if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ) and self.raise_if_mismatch: raise Exception( F'Numbers of operations are different. Source module has {len(_SCREAMING_SNAKE_CASE )} operations while' F' destination module has {len(_SCREAMING_SNAKE_CASE )}.' ) for dest_m, src_m in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'Transfered from={src_m} to={dest_m}' ) class _a ( nn.Module): def __init__( self : List[Any] , _SCREAMING_SNAKE_CASE : nn.Module )-> Optional[int]: super().__init__() lowerCAmelCase__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('''conv1''', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('''block''' ), F'Unexpected layer name {k}' lowerCAmelCase__ : Optional[int] = len(_SCREAMING_SNAKE_CASE ) + 1 feature_blocks.append((F'res{block_index}', v) ) lowerCAmelCase__ : List[str] = nn.ModuleDict(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__( self : int , _SCREAMING_SNAKE_CASE : Tensor )-> List[str]: return get_trunk_forward_outputs( _SCREAMING_SNAKE_CASE , out_feat_keys=_SCREAMING_SNAKE_CASE , feature_blocks=self._feature_blocks , ) class _a ( _lowercase): def UpperCAmelCase__( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : str )-> str: lowerCAmelCase__ : int = x.split('''-''' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : str )-> Callable[[], Tuple[nn.Module, Dict]]: # default to timm! if x not in self: lowerCAmelCase__ : Optional[Any] = self.convert_name_to_timm(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : List[str] = partial(lambda: (timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ).eval(), None) ) else: lowerCAmelCase__ : Any = super().__getitem__(_SCREAMING_SNAKE_CASE ) return val class _a ( _lowercase): def __getitem__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : str )-> Callable[[], nn.Module]: if "seer" in x and "in1k" not in x: lowerCAmelCase__ : int = RegNetModel else: lowerCAmelCase__ : List[str] = RegNetForImageClassification return val def lowerCamelCase_ ( _a , _a , _a ): """simple docstring""" for from_key, to_key in keys: lowerCAmelCase__ : Optional[Any] = from_state_dict[from_key].clone() print(f'Copied key={from_key} to={to_key}' ) return to_state_dict def lowerCamelCase_ ( _a , _a , _a , _a , _a , _a = True , ): """simple docstring""" print(f'Converting {name}...' ) with torch.no_grad(): lowerCAmelCase__ , lowerCAmelCase__ : int = from_model_func() lowerCAmelCase__ : Optional[Any] = our_model_func(_a ).eval() lowerCAmelCase__ : int = ModuleTransfer(src=_a , dest=_a , raise_if_mismatch=_a ) lowerCAmelCase__ : str = torch.randn((1, 3, 224, 224) ) module_transfer(_a ) if from_state_dict is not None: lowerCAmelCase__ : Any = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: lowerCAmelCase__ : List[Any] = [('''0.clf.0.weight''', '''classifier.1.weight'''), ('''0.clf.0.bias''', '''classifier.1.bias''')] lowerCAmelCase__ : int = manually_copy_vissl_head(_a , our_model.state_dict() , _a ) our_model.load_state_dict(_a ) lowerCAmelCase__ : List[str] = our_model(_a , output_hidden_states=_a ) lowerCAmelCase__ : Dict = ( our_outputs.logits if isinstance(_a , _a ) else our_outputs.last_hidden_state ) lowerCAmelCase__ : Tuple = from_model(_a ) lowerCAmelCase__ : int = from_output[-1] if type(_a ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: lowerCAmelCase__ : Optional[int] = our_outputs.hidden_states[-1] assert torch.allclose(_a , _a ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='''Add model''' , use_temp_dir=_a , ) lowerCAmelCase__ : Optional[int] = 224 if '''seer''' not in name else 384 # we can use the convnext one lowerCAmelCase__ : int = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' , size=_a ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='''Add image processor''' , use_temp_dir=_a , ) print(f'Pushed {name}' ) def lowerCamelCase_ ( _a , _a = None , _a = True ): """simple docstring""" lowerCAmelCase__ : str = '''imagenet-1k-id2label.json''' lowerCAmelCase__ : Dict = 1_000 lowerCAmelCase__ : Optional[int] = (1, num_labels) lowerCAmelCase__ : Optional[int] = '''huggingface/label-files''' lowerCAmelCase__ : Tuple = num_labels lowerCAmelCase__ : List[Any] = json.load(open(cached_download(hf_hub_url(_a , _a , repo_type='''dataset''' ) ) , '''r''' ) ) lowerCAmelCase__ : Dict = {int(_a ): v for k, v in idalabel.items()} lowerCAmelCase__ : List[Any] = idalabel lowerCAmelCase__ : Union[str, Any] = {v: k for k, v in idalabel.items()} lowerCAmelCase__ : Dict = partial(_a , num_labels=_a , idalabel=_a , labelaid=_a ) lowerCAmelCase__ : Tuple = { '''regnet-x-002''': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type='''x''' ), '''regnet-x-004''': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type='''x''' ), '''regnet-x-006''': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type='''x''' ), '''regnet-x-008''': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type='''x''' ), '''regnet-x-016''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type='''x''' ), '''regnet-x-032''': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1_008] , groups_width=48 , layer_type='''x''' ), '''regnet-x-040''': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1_360] , groups_width=40 , layer_type='''x''' ), '''regnet-x-064''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1_624] , groups_width=56 , layer_type='''x''' ), '''regnet-x-080''': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1_920] , groups_width=120 , layer_type='''x''' ), '''regnet-x-120''': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2_240] , groups_width=112 , layer_type='''x''' ), '''regnet-x-160''': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2_048] , groups_width=128 , layer_type='''x''' ), '''regnet-x-320''': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1_344, 2_520] , groups_width=168 , layer_type='''x''' ), # y variant '''regnet-y-002''': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), '''regnet-y-004''': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), '''regnet-y-006''': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), '''regnet-y-008''': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), '''regnet-y-016''': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), '''regnet-y-032''': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1_512] , groups_width=24 ), '''regnet-y-040''': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1_088] , groups_width=64 ), '''regnet-y-064''': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1_296] , groups_width=72 ), '''regnet-y-080''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2_016] , groups_width=56 ), '''regnet-y-120''': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2_240] , groups_width=112 ), '''regnet-y-160''': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1_232, 3_024] , groups_width=112 ), '''regnet-y-320''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 '''regnet-y-320-seer''': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), '''regnet-y-640-seer''': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1_968, 4_920] , groups_width=328 ), '''regnet-y-1280-seer''': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1_056, 2_904, 7_392] , groups_width=264 ), '''regnet-y-2560-seer''': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1_696, 2_544, 5_088] , groups_width=640 ), '''regnet-y-10b-seer''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2_020, 4_040, 11_110, 28_280] , groups_width=1_010 ), # finetuned on imagenet '''regnet-y-320-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), '''regnet-y-640-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1_968, 4_920] , groups_width=328 ), '''regnet-y-1280-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1_056, 2_904, 7_392] , groups_width=264 ), '''regnet-y-2560-seer-in1k''': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1_696, 2_544, 5_088] , groups_width=640 ), '''regnet-y-10b-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2_020, 4_040, 11_110, 28_280] , groups_width=1_010 ), } lowerCAmelCase__ : Optional[Any] = NameToOurModelFuncMap() lowerCAmelCase__ : Optional[Any] = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(_a , _a ) -> Tuple[nn.Module, Dict]: lowerCAmelCase__ : Tuple = torch.hub.load_state_dict_from_url(_a , model_dir=str(_a ) , map_location='''cpu''' ) lowerCAmelCase__ : int = model_func() # check if we have a head, if yes add it lowerCAmelCase__ : int = files['''classy_state_dict''']['''base_model''']['''model'''] lowerCAmelCase__ : Tuple = model_state_dict['''trunk'''] model.load_state_dict(_a ) return model.eval(), model_state_dict["heads"] # pretrained lowerCAmelCase__ : int = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ : Optional[int] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ : Optional[int] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) lowerCAmelCase__ : Tuple = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch''' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1_010 , w_a=1_744 , w_a=6_20.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned lowerCAmelCase__ : List[Any] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ : Optional[int] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ : Union[str, Any] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) lowerCAmelCase__ : Union[str, Any] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch''' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1_010 , w_a=1_744 , w_a=6_20.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( _a , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , _a , _a , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( _a , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , _a , _a , _a , ) return config, expected_shape if __name__ == "__main__": lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported regnet* architecture,''' ''' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) lowerCamelCase = parser.parse_args() lowerCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
131
1
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __lowercase (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" @register_to_config def __init__( self , *, lowerCAmelCase__ = 4 , lowerCAmelCase__ = 7_6_8 , lowerCAmelCase__ , lowerCAmelCase__ , ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ : Optional[int] = nn.Parameter(torch.zeros(lowerCAmelCase__ ) ) # parameters for additional clip time embeddings SCREAMING_SNAKE_CASE_ : Tuple = nn.Linear(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = nn.Linear(lowerCAmelCase__ , lowerCAmelCase__ ) # parameters for encoder hidden states SCREAMING_SNAKE_CASE_ : Optional[Any] = clip_extra_context_tokens SCREAMING_SNAKE_CASE_ : Union[str, Any] = nn.Linear( lowerCAmelCase__ , self.clip_extra_context_tokens * cross_attention_dim ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = nn.Linear(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : List[str] = nn.LayerNorm(lowerCAmelCase__ ) def UpperCamelCase__ ( self , *, lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings SCREAMING_SNAKE_CASE_ : Optional[Any] = image_embeddings.shape[0] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) SCREAMING_SNAKE_CASE_ : int = classifier_free_guidance_embeddings.expand( lowerCAmelCase__ , -1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] SCREAMING_SNAKE_CASE_ : Union[str, Any] = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... SCREAMING_SNAKE_CASE_ : Optional[Any] = self.embedding_proj(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.clip_image_embeddings_project_to_time_embeddings(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : List[str] = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" SCREAMING_SNAKE_CASE_ : str = self.clip_extra_context_tokens_proj(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = clip_extra_context_tokens.reshape(lowerCAmelCase__ , -1 , self.clip_extra_context_tokens ) SCREAMING_SNAKE_CASE_ : int = clip_extra_context_tokens.permute(0 , 2 , 1 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.encoder_hidden_states_proj(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_encoder_hidden_states_norm(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : str = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
162
import math import unittest def a__ ( A__ ): assert isinstance(A__, A__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(A__ ) + 1 ), 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class __lowercase (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self ): """simple docstring""" self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(1_1 ) ) self.assertTrue(is_prime(1_3 ) ) self.assertTrue(is_prime(1_7 ) ) self.assertTrue(is_prime(1_9 ) ) self.assertTrue(is_prime(2_3 ) ) self.assertTrue(is_prime(2_9 ) ) def UpperCamelCase__ ( self ): """simple docstring""" with self.assertRaises(lowerCAmelCase__ ): is_prime(-1_9 ) self.assertFalse( is_prime(0 ) , 'Zero doesn\'t have any positive factors, primes must have exactly two.' , ) self.assertFalse( is_prime(1 ) , 'One only has 1 positive factor, primes must have exactly two.' , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
162
1
'''simple docstring''' import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) lowerCAmelCase__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowercase_ : """simple docstring""" SCREAMING_SNAKE_CASE : str = field( default=lowerCamelCase__ , metadata={'help': 'Model type selected in the list: ' + ', '.join(lowerCamelCase__ )} ) SCREAMING_SNAKE_CASE : str = field( default=lowerCamelCase__ , metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} ) SCREAMING_SNAKE_CASE : int = field( default=1_2_8 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) SCREAMING_SNAKE_CASE : int = field( default=1_2_8 , metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'} , ) SCREAMING_SNAKE_CASE : int = field( default=6_4 , metadata={ 'help': ( 'The maximum number of tokens for the question. Questions longer than this will ' 'be truncated to this length.' ) } , ) SCREAMING_SNAKE_CASE : int = field( default=3_0 , metadata={ 'help': ( 'The maximum length of an answer that can be generated. This is needed because the start ' 'and end predictions are not conditioned on one another.' ) } , ) SCREAMING_SNAKE_CASE : bool = field( default=lowerCamelCase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) SCREAMING_SNAKE_CASE : bool = field( default=lowerCamelCase__ , metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} ) SCREAMING_SNAKE_CASE : float = field( default=0.0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} ) SCREAMING_SNAKE_CASE : int = field( default=2_0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} ) SCREAMING_SNAKE_CASE : int = field( default=0 , metadata={ 'help': ( 'language id of input for language-specific xlm models (see' ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)' ) } , ) SCREAMING_SNAKE_CASE : int = field(default=1 , metadata={'help': 'multiple threads for converting example to features'} ) class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 'train' SCREAMING_SNAKE_CASE : List[Any] = 'dev' class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : SquadDataTrainingArguments SCREAMING_SNAKE_CASE : List[SquadFeatures] SCREAMING_SNAKE_CASE : Split SCREAMING_SNAKE_CASE : bool def __init__( self : Optional[Any] ,lowercase__ : SquadDataTrainingArguments ,lowercase__ : PreTrainedTokenizer ,lowercase__ : Optional[int] = None ,lowercase__ : Union[str, Split] = Split.train ,lowercase__ : Optional[bool] = False ,lowercase__ : Optional[str] = None ,lowercase__ : Optional[str] = "pt" ,): __lowercase = args __lowercase = is_language_sensitive __lowercase = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(lowercase__ ,lowercase__ ): try: __lowercase = Split[mode] except KeyError: raise KeyError('''mode is not a valid split name''' ) __lowercase = mode # Load data features from cache or dataset file __lowercase = '''v2''' if args.version_2_with_negative else '''v1''' __lowercase = os.path.join( cache_dir if cache_dir is not None else args.data_dir ,F"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}" ,) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowercase = cached_features_file + '''.lock''' with FileLock(lowercase__ ): if os.path.exists(lowercase__ ) and not args.overwrite_cache: __lowercase = time.time() __lowercase = torch.load(lowercase__ ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. __lowercase = self.old_features['''features'''] __lowercase = self.old_features.get('''dataset''' ,lowercase__ ) __lowercase = self.old_features.get('''examples''' ,lowercase__ ) logger.info( F"Loading features from cached file {cached_features_file} [took %.3f s]" ,time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( F"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in" ''' future run''' ) else: if mode == Split.dev: __lowercase = self.processor.get_dev_examples(args.data_dir ) else: __lowercase = self.processor.get_train_examples(args.data_dir ) __lowercase , __lowercase = squad_convert_examples_to_features( examples=self.examples ,tokenizer=lowercase__ ,max_seq_length=args.max_seq_length ,doc_stride=args.doc_stride ,max_query_length=args.max_query_length ,is_training=mode == Split.train ,threads=args.threads ,return_dataset=lowercase__ ,) __lowercase = time.time() torch.save( {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples} ,lowercase__ ,) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" ) def __len__( self : Tuple ): return len(self.features ) def __getitem__( self : Tuple ,lowercase__ : str ): # Convert to Tensors and build dataset __lowercase = self.features[i] __lowercase = torch.tensor(feature.input_ids ,dtype=torch.long ) __lowercase = torch.tensor(feature.attention_mask ,dtype=torch.long ) __lowercase = torch.tensor(feature.token_type_ids ,dtype=torch.long ) __lowercase = torch.tensor(feature.cls_index ,dtype=torch.long ) __lowercase = torch.tensor(feature.p_mask ,dtype=torch.float ) __lowercase = torch.tensor(feature.is_impossible ,dtype=torch.float ) __lowercase = { '''input_ids''': input_ids, '''attention_mask''': attention_mask, '''token_type_ids''': token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask} ) if self.args.version_2_with_negative: inputs.update({'''is_impossible''': is_impossible} ) if self.is_language_sensitive: inputs.update({'''langs''': (torch.ones(input_ids.shape ,dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: __lowercase = torch.tensor(feature.start_position ,dtype=torch.long ) __lowercase = torch.tensor(feature.end_position ,dtype=torch.long ) inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions} ) return inputs
104
'''simple docstring''' import torch from torch import nn class lowercase_ (nn.Module ): """simple docstring""" def __init__( self : Optional[int] ,lowercase__ : List[str] ,lowercase__ : Any ,lowercase__ : Union[str, Any] ,lowercase__ : Optional[int] ,lowercase__ : Optional[int]=1 ,lowercase__ : Optional[Any]=False ): super().__init__() __lowercase = n_token __lowercase = d_embed __lowercase = d_proj __lowercase = cutoffs + [n_token] __lowercase = [0] + self.cutoffs __lowercase = div_val __lowercase = self.cutoffs[0] __lowercase = len(self.cutoffs ) - 1 __lowercase = self.shortlist_size + self.n_clusters if self.n_clusters > 0: __lowercase = nn.Parameter(torch.zeros(self.n_clusters ,self.d_embed ) ) __lowercase = nn.Parameter(torch.zeros(self.n_clusters ) ) __lowercase = nn.ModuleList() __lowercase = nn.ParameterList() if div_val == 1: for i in range(len(self.cutoffs ) ): if d_proj != d_embed: self.out_projs.append(nn.Parameter(torch.FloatTensor(lowercase__ ,lowercase__ ) ) ) else: self.out_projs.append(lowercase__ ) self.out_layers.append(nn.Linear(lowercase__ ,lowercase__ ) ) else: for i in range(len(self.cutoffs ) ): __lowercase , __lowercase = self.cutoff_ends[i], self.cutoff_ends[i + 1] __lowercase = d_embed // (div_val**i) self.out_projs.append(nn.Parameter(torch.FloatTensor(lowercase__ ,lowercase__ ) ) ) self.out_layers.append(nn.Linear(lowercase__ ,r_idx - l_idx ) ) __lowercase = keep_order def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : List[Any] ,lowercase__ : Dict ,lowercase__ : List[Any] ,lowercase__ : Any ): if proj is None: __lowercase = nn.functional.linear(lowercase__ ,lowercase__ ,bias=lowercase__ ) else: # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1: __lowercase = nn.functional.linear(lowercase__ ,proj.t().contiguous() ) __lowercase = nn.functional.linear(lowercase__ ,lowercase__ ,bias=lowercase__ ) # else: # logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t())) # if bias is not None: # logit = logit + bias return logit def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : Optional[Any] ,lowercase__ : Any=None ,lowercase__ : List[str]=False ): if labels is not None: # Shift so that tokens < n predict n __lowercase = hidden[..., :-1, :].contiguous() __lowercase = labels[..., 1:].contiguous() __lowercase = hidden.view(-1 ,hidden.size(-1 ) ) __lowercase = labels.view(-1 ) if hidden.size(0 ) != labels.size(0 ): raise RuntimeError('''Input and labels should have the same size in the batch dimension.''' ) else: __lowercase = hidden.view(-1 ,hidden.size(-1 ) ) if self.n_clusters == 0: __lowercase = self._compute_logit(lowercase__ ,self.out_layers[0].weight ,self.out_layers[0].bias ,self.out_projs[0] ) if labels is not None: __lowercase = labels != -1_0_0 __lowercase = torch.zeros_like(lowercase__ ,dtype=hidden.dtype ,device=hidden.device ) __lowercase = ( -nn.functional.log_softmax(lowercase__ ,dim=-1 )[mask].gather(1 ,labels[mask].unsqueeze(1 ) ).squeeze(1 ) ) else: __lowercase = nn.functional.log_softmax(lowercase__ ,dim=-1 ) else: # construct weights and biases __lowercase , __lowercase = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: __lowercase , __lowercase = self.cutoff_ends[i], self.cutoff_ends[i + 1] __lowercase = self.out_layers[0].weight[l_idx:r_idx] __lowercase = self.out_layers[0].bias[l_idx:r_idx] else: __lowercase = self.out_layers[i].weight __lowercase = self.out_layers[i].bias if i == 0: __lowercase = torch.cat([weight_i, self.cluster_weight] ,dim=0 ) __lowercase = torch.cat([bias_i, self.cluster_bias] ,dim=0 ) weights.append(lowercase__ ) biases.append(lowercase__ ) __lowercase , __lowercase , __lowercase = weights[0], biases[0], self.out_projs[0] __lowercase = self._compute_logit(lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ) __lowercase = nn.functional.log_softmax(lowercase__ ,dim=1 ) if labels is None: __lowercase = hidden.new_empty((head_logit.size(0 ), self.n_token) ) else: __lowercase = torch.zeros_like(lowercase__ ,dtype=hidden.dtype ,device=hidden.device ) __lowercase = 0 __lowercase = [0] + self.cutoffs for i in range(len(lowercase__ ) - 1 ): __lowercase , __lowercase = cutoff_values[i], cutoff_values[i + 1] if labels is not None: __lowercase = (labels >= l_idx) & (labels < r_idx) __lowercase = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue __lowercase = labels.index_select(0 ,lowercase__ ) - l_idx __lowercase = head_logprob.index_select(0 ,lowercase__ ) __lowercase = hidden.index_select(0 ,lowercase__ ) else: __lowercase = hidden if i == 0: if labels is not None: __lowercase = head_logprob_i.gather(1 ,target_i[:, None] ).squeeze(1 ) else: __lowercase = head_logprob[:, : self.cutoffs[0]] else: __lowercase , __lowercase , __lowercase = weights[i], biases[i], self.out_projs[i] __lowercase = self._compute_logit(lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ) __lowercase = nn.functional.log_softmax(lowercase__ ,dim=1 ) __lowercase = self.cutoffs[0] + i - 1 # No probability for the head cluster if labels is not None: __lowercase = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather( 1 ,target_i[:, None] ).squeeze(1 ) else: __lowercase = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i __lowercase = logprob_i if labels is not None: if (hasattr(self ,'''keep_order''' ) and self.keep_order) or keep_order: out.index_copy_(0 ,lowercase__ ,-logprob_i ) else: out[offset : offset + logprob_i.size(0 )].copy_(-logprob_i ) offset += logprob_i.size(0 ) return out def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : Union[str, Any] ): if self.n_clusters == 0: __lowercase = self._compute_logit(lowercase__ ,self.out_layers[0].weight ,self.out_layers[0].bias ,self.out_projs[0] ) return nn.functional.log_softmax(lowercase__ ,dim=-1 ) else: # construct weights and biases __lowercase , __lowercase = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: __lowercase , __lowercase = self.cutoff_ends[i], self.cutoff_ends[i + 1] __lowercase = self.out_layers[0].weight[l_idx:r_idx] __lowercase = self.out_layers[0].bias[l_idx:r_idx] else: __lowercase = self.out_layers[i].weight __lowercase = self.out_layers[i].bias if i == 0: __lowercase = torch.cat([weight_i, self.cluster_weight] ,dim=0 ) __lowercase = torch.cat([bias_i, self.cluster_bias] ,dim=0 ) weights.append(lowercase__ ) biases.append(lowercase__ ) __lowercase , __lowercase , __lowercase = weights[0], biases[0], self.out_projs[0] __lowercase = self._compute_logit(lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ) __lowercase = hidden.new_empty((head_logit.size(0 ), self.n_token) ) __lowercase = nn.functional.log_softmax(lowercase__ ,dim=1 ) __lowercase = [0] + self.cutoffs for i in range(len(lowercase__ ) - 1 ): __lowercase , __lowercase = cutoff_values[i], cutoff_values[i + 1] if i == 0: __lowercase = head_logprob[:, : self.cutoffs[0]] else: __lowercase , __lowercase , __lowercase = weights[i], biases[i], self.out_projs[i] __lowercase = self._compute_logit(lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ) __lowercase = nn.functional.log_softmax(lowercase__ ,dim=1 ) __lowercase = head_logprob[:, -i] + tail_logprob_i __lowercase = logprob_i return out
104
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase: Optional[int] = {'configuration_unispeech': ['UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP', 'UniSpeechConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Optional[Any] = [ 'UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST', 'UniSpeechForCTC', 'UniSpeechForPreTraining', 'UniSpeechForSequenceClassification', 'UniSpeechModel', 'UniSpeechPreTrainedModel', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowerCAmelCase: Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
96
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase: Any = logging.get_logger(__name__) class a__( lowerCamelCase__ ): lowercase__ = """encoder-decoder""" lowercase__ = True def __init__( self : Dict , **__snake_case : Union[str, Any] ): super().__init__(**__snake_case ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" a : List[str] = kwargs.pop('encoder' ) a : Optional[Any] = encoder_config.pop('model_type' ) a : Tuple = kwargs.pop('decoder' ) a : Optional[int] = decoder_config.pop('model_type' ) from ..auto.configuration_auto import AutoConfig a : Any = AutoConfig.for_model(__snake_case , **__snake_case ) a : Optional[int] = AutoConfig.for_model(__snake_case , **__snake_case ) a : Tuple = True @classmethod def lowercase_ ( cls : int , __snake_case : PretrainedConfig , __snake_case : PretrainedConfig , **__snake_case : Union[str, Any] ): logger.info('Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config' ) a : List[Any] = True a : Tuple = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__snake_case ) def lowercase_ ( self : List[Any] ): a : int = copy.deepcopy(self.__dict__ ) a : List[str] = self.encoder.to_dict() a : Optional[int] = self.decoder.to_dict() a : Optional[Any] = self.__class__.model_type return output
96
1
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker A : str = "CompVis/stable-diffusion-v1-1" A : Any = "CompVis/stable-diffusion-v1-2" A : Tuple = "CompVis/stable-diffusion-v1-3" A : Tuple = "CompVis/stable-diffusion-v1-4" class lowerCamelCase (SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self : Optional[int] , __magic_name__ : AutoencoderKL , __magic_name__ : CLIPTextModel , __magic_name__ : CLIPTokenizer , __magic_name__ : UNetaDConditionModel , __magic_name__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __magic_name__ : StableDiffusionSafetyChecker , __magic_name__ : CLIPImageProcessor , __magic_name__ : bool = True , ) -> int: super()._init_() SCREAMING_SNAKE_CASE_ = StableDiffusionPipeline.from_pretrained(__magic_name__ ) SCREAMING_SNAKE_CASE_ = StableDiffusionPipeline.from_pretrained(__magic_name__ ) SCREAMING_SNAKE_CASE_ = StableDiffusionPipeline.from_pretrained(__magic_name__ ) SCREAMING_SNAKE_CASE_ = StableDiffusionPipeline( vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , unet=__magic_name__ , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , requires_safety_checker=__magic_name__ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def __A ( self : Any ) -> Dict[str, Any]: return {k: getattr(self , __magic_name__ ) for k in self.config.keys() if not k.startswith("_" )} def __A ( self : Union[str, Any] , __magic_name__ : Optional[Union[str, int]] = "auto" ) -> Optional[Any]: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__magic_name__ ) def __A ( self : Dict ) -> Any: self.enable_attention_slicing(__magic_name__ ) @torch.no_grad() def __A ( self : str , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 512 , __magic_name__ : int = 512 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> Union[str, Any]: return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def __A ( self : Union[str, Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 512 , __magic_name__ : int = 512 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : List[str] , ) -> int: return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def __A ( self : List[str] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 512 , __magic_name__ : int = 512 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Tuple , ) -> Any: return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def __A ( self : Tuple , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 512 , __magic_name__ : int = 512 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Dict , ) -> List[str]: return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def __A ( self : Dict , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 512 , __magic_name__ : int = 512 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Dict , ) -> Tuple: SCREAMING_SNAKE_CASE_ = "cuda" if torch.cuda.is_available() else "cpu" self.to(__magic_name__ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` must be divisible by 8 but are {height} and {width}.''' ) # Get first result from Stable Diffusion Checkpoint v1.1 SCREAMING_SNAKE_CASE_ = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.2 SCREAMING_SNAKE_CASE_ = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.3 SCREAMING_SNAKE_CASE_ = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.4 SCREAMING_SNAKE_CASE_ = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
118
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class lowerCamelCase (SCREAMING_SNAKE_CASE__ ): """simple docstring""" lowerCamelCase__ = 42 lowerCamelCase__ = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
118
1
"""simple docstring""" import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict _a = namedtuple( """_TestCommandArgs""", [ """dataset""", """name""", """cache_dir""", """data_dir""", """all_configs""", """save_infos""", """ignore_verifications""", """force_redownload""", """clear_cache""", ], defaults=[None, None, None, False, False, False, False, False], ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]: """simple docstring""" return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def lowerCamelCase__ ( __snake_case ) -> Dict: """simple docstring""" _UpperCamelCase = _TestCommandArgs(dataset=__snake_case, all_configs=__snake_case, save_infos=__snake_case ) _UpperCamelCase = TestCommand(*__snake_case ) test_command.run() _UpperCamelCase = os.path.join(__snake_case, '''README.md''' ) assert os.path.exists(__snake_case ) _UpperCamelCase = DatasetInfosDict.from_directory(__snake_case ) _UpperCamelCase = DatasetInfosDict( { '''default''': DatasetInfo( features=Features( { '''tokens''': Sequence(Value('''string''' ) ), '''ner_tags''': Sequence( ClassLabel(names=['''O''', '''B-PER''', '''I-PER''', '''B-ORG''', '''I-ORG''', '''B-LOC''', '''I-LOC'''] ) ), '''langs''': Sequence(Value('''string''' ) ), '''spans''': Sequence(Value('''string''' ) ), } ), splits=[ { '''name''': '''train''', '''num_bytes''': 2_35_15_63, '''num_examples''': 1_00_00, }, { '''name''': '''validation''', '''num_bytes''': 23_84_18, '''num_examples''': 10_00, }, ], download_size=3_94_06_80, dataset_size=2_58_99_81, ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: _UpperCamelCase , _UpperCamelCase = getattr(dataset_infos['''default'''], __snake_case ), getattr(expected_dataset_infos['''default'''], __snake_case ) if key == "num_bytes": assert is_apercent_close(__snake_case, __snake_case ) elif key == "splits": assert list(__snake_case ) == list(__snake_case ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes, expected[split].num_bytes ) else: result == expected
100
"""simple docstring""" import numpy class _UpperCAmelCase: def __init__( self , __a , __a) -> None: '''simple docstring''' _UpperCamelCase = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. _UpperCamelCase = numpy.random.rand( self.input_array.shape[1] , 4) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. _UpperCamelCase = numpy.random.rand( 4 , 3) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. _UpperCamelCase = numpy.random.rand(3 , 1) # Real output values provided. _UpperCamelCase = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. _UpperCamelCase = numpy.zeros(output_array.shape) def UpperCAmelCase ( self) -> numpy.ndarray: '''simple docstring''' _UpperCamelCase = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights)) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. _UpperCamelCase = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , )) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. _UpperCamelCase = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , )) return self.layer_between_second_hidden_layer_and_output def UpperCAmelCase ( self) -> None: '''simple docstring''' _UpperCamelCase = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , ) _UpperCamelCase = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer) , ) _UpperCamelCase = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def UpperCAmelCase ( self , __a , __a , __a) -> None: '''simple docstring''' for iteration in range(1 , iterations + 1): _UpperCamelCase = self.feedforward() self.back_propagation() if give_loss: _UpperCamelCase = numpy.mean(numpy.square(output - self.feedforward())) print(F'''Iteration {iteration} Loss: {loss}''') def UpperCAmelCase ( self , __a) -> int: '''simple docstring''' _UpperCamelCase = input_arr _UpperCamelCase = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights)) _UpperCamelCase = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , )) _UpperCamelCase = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , )) return int(self.layer_between_second_hidden_layer_and_output > 0.6) def lowerCamelCase__ ( __snake_case ) -> numpy.ndarray: """simple docstring""" return 1 / (1 + numpy.exp(-value )) def lowerCamelCase__ ( __snake_case ) -> numpy.ndarray: """simple docstring""" return (value) * (1 - (value)) def lowerCamelCase__ ( ) -> int: """simple docstring""" _UpperCamelCase = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ), dtype=numpy.floataa, ) # True output values for the given input values. _UpperCamelCase = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.floataa ) # Calling neural network class. _UpperCamelCase = TwoHiddenLayerNeuralNetwork( input_array=__snake_case, output_array=__snake_case ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=__snake_case, iterations=10, give_loss=__snake_case ) return neural_network.predict(numpy.array(([1, 1, 1]), dtype=numpy.floataa ) ) if __name__ == "__main__": example()
100
1
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase_ ) class lowerCamelCase__ ( lowerCamelCase_ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization a__ : str = field(default="""summarization""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) a__ : ClassVar[Features] = Features({"""text""": Value("""string""" )} ) a__ : ClassVar[Features] = Features({"""summary""": Value("""string""" )} ) a__ : str = "text" a__ : str = "summary" @property def lowerCamelCase_ ( self ): """simple docstring""" return {self.text_column: "text", self.summary_column: "summary"}
148
"""simple docstring""" import os import numpy import onnx def UpperCamelCase__ ( lowercase__ : List[str] , lowercase__ : Optional[int] ): snake_case : Any = a.name snake_case : Any = b.name snake_case : str = "" snake_case : Dict = "" snake_case : Optional[Any] = a == b snake_case : Union[str, Any] = name_a snake_case : List[str] = name_b return res def UpperCamelCase__ ( lowercase__ : List[Any] , lowercase__ : Tuple , lowercase__ : int ): for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(lowercase__ , lowercase__ ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , lowercase__ , lowercase__ ) _graph_replace_input_with(node_proto.attribute[1].g , lowercase__ , lowercase__ ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , lowercase__ , lowercase__ ) def UpperCamelCase__ ( lowercase__ : List[str] , lowercase__ : Union[str, Any] , lowercase__ : List[Any] ): for n in graph_proto.node: _node_replace_input_with(lowercase__ , lowercase__ , lowercase__ ) def UpperCamelCase__ ( lowercase__ : Any , lowercase__ : str , lowercase__ : List[str] ): snake_case : str = list(model.graph.initializer ) snake_case : int = list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i snake_case : str = inits[i].name snake_case : str = inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph , lowercase__ , lowercase__ ) def UpperCamelCase__ ( lowercase__ : Optional[int] ): snake_case : List[str] = os.path.dirname(lowercase__ ) snake_case : Any = os.path.basename(lowercase__ ) snake_case : Optional[int] = onnx.load(os.path.join(lowercase__ , lowercase__ ) ) snake_case : Optional[Any] = list(model.graph.initializer ) snake_case : int = set() snake_case : Any = {} snake_case : Optional[Any] = [] snake_case : str = 0 for i in range(len(lowercase__ ) ): if i in dup_set: continue for j in range(i + 1 , len(lowercase__ ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(lowercase__ ) dup_set.add(lowercase__ ) snake_case : Union[str, Any] = inits[j].data_type snake_case : Tuple = numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 11: mem_size *= 8 else: print("unexpected data type: " , lowercase__ ) total_reduced_size += mem_size snake_case : Tuple = inits[i].name snake_case : Optional[Any] = inits[j].name if name_i in dup_map: dup_map[name_i].append(lowercase__ ) else: snake_case : Optional[int] = [name_j] ind_to_replace.append((j, i) ) print("total reduced size: " , total_reduced_size / 1024 / 1024 / 1024 , "GB" ) snake_case : Tuple = sorted(lowercase__ ) _remove_dup_initializers_from_model(lowercase__ , lowercase__ , lowercase__ ) snake_case : Optional[Any] = "optimized_" + model_file_name snake_case : Tuple = os.path.join(lowercase__ , lowercase__ ) onnx.save(lowercase__ , lowercase__ ) return new_model
148
1
from __future__ import annotations __snake_case : Optional[int] =[-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] __snake_case : Tuple =[-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def lowerCAmelCase__ ( lowerCamelCase_ : list[float]): '''simple docstring''' lowerCAmelCase__ : Optional[int] = [] lowerCAmelCase__ : Optional[Any] = len(lowerCamelCase_) for i in range(lowerCamelCase_): lowerCAmelCase__ : float = -1 for j in range(i + 1 ,lowerCamelCase_): if arr[i] < arr[j]: lowerCAmelCase__ : Optional[int] = arr[j] break result.append(lowerCamelCase_) return result def lowerCAmelCase__ ( lowerCamelCase_ : list[float]): '''simple docstring''' lowerCAmelCase__ : Any = [] for i, outer in enumerate(lowerCamelCase_): lowerCAmelCase__ : float = -1 for inner in arr[i + 1 :]: if outer < inner: lowerCAmelCase__ : Tuple = inner break result.append(lowerCamelCase_) return result def lowerCAmelCase__ ( lowerCamelCase_ : list[float]): '''simple docstring''' lowerCAmelCase__ : List[Any] = len(lowerCamelCase_) lowerCAmelCase__ : list[float] = [] lowerCAmelCase__ : list[float] = [-1] * arr_size for index in reversed(range(lowerCamelCase_)): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: lowerCAmelCase__ : List[Any] = stack[-1] stack.append(arr[index]) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __snake_case : List[Any] =( 'from __main__ import arr, next_greatest_element_slow, ' 'next_greatest_element_fast, next_greatest_element' ) print( 'next_greatest_element_slow():', timeit('next_greatest_element_slow(arr)', setup=setup), ) print( 'next_greatest_element_fast():', timeit('next_greatest_element_fast(arr)', setup=setup), ) print( ' next_greatest_element():', timeit('next_greatest_element(arr)', setup=setup), )
94
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __snake_case : Tuple =logging.get_logger(__name__) def lowerCAmelCase__ ( lowerCamelCase_ : Tuple ,lowerCamelCase_ : Dict=False ,lowerCamelCase_ : List[Any]=False ,lowerCamelCase_ : int=False): '''simple docstring''' lowerCAmelCase__ : Tuple = [] for i in range(config.num_hidden_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""transformer.blocks.{i}.norm1.weight""", f"""vilt.encoder.layer.{i}.layernorm_before.weight""")) rename_keys.append((f"""transformer.blocks.{i}.norm1.bias""", f"""vilt.encoder.layer.{i}.layernorm_before.bias""")) rename_keys.append( (f"""transformer.blocks.{i}.attn.proj.weight""", f"""vilt.encoder.layer.{i}.attention.output.dense.weight""")) rename_keys.append( (f"""transformer.blocks.{i}.attn.proj.bias""", f"""vilt.encoder.layer.{i}.attention.output.dense.bias""")) rename_keys.append((f"""transformer.blocks.{i}.norm2.weight""", f"""vilt.encoder.layer.{i}.layernorm_after.weight""")) rename_keys.append((f"""transformer.blocks.{i}.norm2.bias""", f"""vilt.encoder.layer.{i}.layernorm_after.bias""")) rename_keys.append( (f"""transformer.blocks.{i}.mlp.fc1.weight""", f"""vilt.encoder.layer.{i}.intermediate.dense.weight""")) rename_keys.append((f"""transformer.blocks.{i}.mlp.fc1.bias""", f"""vilt.encoder.layer.{i}.intermediate.dense.bias""")) rename_keys.append((f"""transformer.blocks.{i}.mlp.fc2.weight""", f"""vilt.encoder.layer.{i}.output.dense.weight""")) rename_keys.append((f"""transformer.blocks.{i}.mlp.fc2.bias""", f"""vilt.encoder.layer.{i}.output.dense.bias""")) # embeddings rename_keys.extend( [ # text embeddings ('''text_embeddings.word_embeddings.weight''', '''vilt.embeddings.text_embeddings.word_embeddings.weight'''), ( '''text_embeddings.position_embeddings.weight''', '''vilt.embeddings.text_embeddings.position_embeddings.weight''', ), ('''text_embeddings.position_ids''', '''vilt.embeddings.text_embeddings.position_ids'''), ( '''text_embeddings.token_type_embeddings.weight''', '''vilt.embeddings.text_embeddings.token_type_embeddings.weight''', ), ('''text_embeddings.LayerNorm.weight''', '''vilt.embeddings.text_embeddings.LayerNorm.weight'''), ('''text_embeddings.LayerNorm.bias''', '''vilt.embeddings.text_embeddings.LayerNorm.bias'''), # patch embeddings ('''transformer.cls_token''', '''vilt.embeddings.cls_token'''), ('''transformer.patch_embed.proj.weight''', '''vilt.embeddings.patch_embeddings.projection.weight'''), ('''transformer.patch_embed.proj.bias''', '''vilt.embeddings.patch_embeddings.projection.bias'''), ('''transformer.pos_embed''', '''vilt.embeddings.position_embeddings'''), # token type embeddings ('''token_type_embeddings.weight''', '''vilt.embeddings.token_type_embeddings.weight'''), ]) # final layernorm + pooler rename_keys.extend( [ ('''transformer.norm.weight''', '''vilt.layernorm.weight'''), ('''transformer.norm.bias''', '''vilt.layernorm.bias'''), ('''pooler.dense.weight''', '''vilt.pooler.dense.weight'''), ('''pooler.dense.bias''', '''vilt.pooler.dense.bias'''), ]) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('''vqa_classifier.0.weight''', '''classifier.0.weight'''), ('''vqa_classifier.0.bias''', '''classifier.0.bias'''), ('''vqa_classifier.1.weight''', '''classifier.1.weight'''), ('''vqa_classifier.1.bias''', '''classifier.1.bias'''), ('''vqa_classifier.3.weight''', '''classifier.3.weight'''), ('''vqa_classifier.3.bias''', '''classifier.3.bias'''), ]) elif nlvr_model: # classification head rename_keys.extend( [ ('''nlvr2_classifier.0.weight''', '''classifier.0.weight'''), ('''nlvr2_classifier.0.bias''', '''classifier.0.bias'''), ('''nlvr2_classifier.1.weight''', '''classifier.1.weight'''), ('''nlvr2_classifier.1.bias''', '''classifier.1.bias'''), ('''nlvr2_classifier.3.weight''', '''classifier.3.weight'''), ('''nlvr2_classifier.3.bias''', '''classifier.3.bias'''), ]) else: pass return rename_keys def lowerCAmelCase__ ( lowerCamelCase_ : Dict ,lowerCamelCase_ : Optional[Any]): '''simple docstring''' for i in range(config.num_hidden_layers): lowerCAmelCase__ : Optional[Any] = '''vilt.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCAmelCase__ : Dict = state_dict.pop(f"""transformer.blocks.{i}.attn.qkv.weight""") lowerCAmelCase__ : Tuple = state_dict.pop(f"""transformer.blocks.{i}.attn.qkv.bias""") # next, add query, keys and values (in that order) to the state dict lowerCAmelCase__ : Dict = in_proj_weight[ : config.hidden_size, : ] lowerCAmelCase__ : Tuple = in_proj_bias[: config.hidden_size] lowerCAmelCase__ : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCAmelCase__ : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCAmelCase__ : str = in_proj_weight[ -config.hidden_size :, : ] lowerCAmelCase__ : Union[str, Any] = in_proj_bias[-config.hidden_size :] def lowerCAmelCase__ ( lowerCamelCase_ : List[str]): '''simple docstring''' lowerCAmelCase__ : List[Any] = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(lowerCamelCase_ ,lowerCamelCase_) def lowerCAmelCase__ ( lowerCamelCase_ : Optional[Any] ,lowerCamelCase_ : Optional[int] ,lowerCamelCase_ : int): '''simple docstring''' lowerCAmelCase__ : int = dct.pop(lowerCamelCase_) lowerCAmelCase__ : List[Any] = val @torch.no_grad() def lowerCAmelCase__ ( lowerCamelCase_ : int ,lowerCamelCase_ : Union[str, Any]): '''simple docstring''' lowerCAmelCase__ : Optional[int] = ViltConfig(image_size=384 ,patch_size=32 ,tie_word_embeddings=lowerCamelCase_) lowerCAmelCase__ : Optional[Any] = False lowerCAmelCase__ : Union[str, Any] = False lowerCAmelCase__ : Dict = False lowerCAmelCase__ : Any = False if "vqa" in checkpoint_url: lowerCAmelCase__ : List[Any] = True lowerCAmelCase__ : List[Any] = 3129 lowerCAmelCase__ : List[Any] = '''huggingface/label-files''' lowerCAmelCase__ : Union[str, Any] = '''vqa2-id2label.json''' lowerCAmelCase__ : Optional[int] = json.load(open(hf_hub_download(lowerCamelCase_ ,lowerCamelCase_ ,repo_type='''dataset''') ,'''r''')) lowerCAmelCase__ : Optional[Any] = {int(lowerCamelCase_): v for k, v in idalabel.items()} lowerCAmelCase__ : Dict = idalabel lowerCAmelCase__ : List[Any] = {v: k for k, v in idalabel.items()} lowerCAmelCase__ : Optional[int] = ViltForQuestionAnswering(lowerCamelCase_) elif "nlvr" in checkpoint_url: lowerCAmelCase__ : str = True lowerCAmelCase__ : Optional[Any] = 2 lowerCAmelCase__ : Optional[Any] = {0: '''False''', 1: '''True'''} lowerCAmelCase__ : Union[str, Any] = {v: k for k, v in config.idalabel.items()} lowerCAmelCase__ : int = 3 lowerCAmelCase__ : int = ViltForImagesAndTextClassification(lowerCamelCase_) elif "irtr" in checkpoint_url: lowerCAmelCase__ : str = True lowerCAmelCase__ : List[str] = ViltForImageAndTextRetrieval(lowerCamelCase_) elif "mlm_itm" in checkpoint_url: lowerCAmelCase__ : Any = True lowerCAmelCase__ : int = ViltForMaskedLM(lowerCamelCase_) else: raise ValueError('''Unknown model type''') # load state_dict of original model, remove and rename some keys lowerCAmelCase__ : Tuple = torch.hub.load_state_dict_from_url(lowerCamelCase_ ,map_location='''cpu''')['''state_dict'''] lowerCAmelCase__ : Tuple = create_rename_keys(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_) for src, dest in rename_keys: rename_key(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_) read_in_q_k_v(lowerCamelCase_ ,lowerCamelCase_) if mlm_model or irtr_model: lowerCAmelCase__ : int = ['''itm_score.fc.weight''', '''itm_score.fc.bias'''] for k in ignore_keys: state_dict.pop(lowerCamelCase_ ,lowerCamelCase_) # load state dict into HuggingFace model model.eval() if mlm_model: lowerCAmelCase__ , lowerCAmelCase__ : str = model.load_state_dict(lowerCamelCase_ ,strict=lowerCamelCase_) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowerCamelCase_) # Define processor lowerCAmelCase__ : List[str] = ViltImageProcessor(size=384) lowerCAmelCase__ : Tuple = BertTokenizer.from_pretrained('''bert-base-uncased''') lowerCAmelCase__ : Union[str, Any] = ViltProcessor(lowerCamelCase_ ,lowerCamelCase_) # Forward pass on example inputs (image + text) if nlvr_model: lowerCAmelCase__ : int = Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg''' ,stream=lowerCamelCase_).raw) lowerCAmelCase__ : Union[str, Any] = Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg''' ,stream=lowerCamelCase_).raw) lowerCAmelCase__ : Union[str, Any] = ( '''The left image contains twice the number of dogs as the right image, and at least two dogs in total are''' ''' standing.''' ) lowerCAmelCase__ : Optional[int] = processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''') lowerCAmelCase__ : Tuple = processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''') lowerCAmelCase__ : Union[str, Any] = model( input_ids=encoding_a.input_ids ,pixel_values=encoding_a.pixel_values ,pixel_values_a=encoding_a.pixel_values ,) else: lowerCAmelCase__ : Dict = Image.open(requests.get('''http://images.cocodataset.org/val2017/000000039769.jpg''' ,stream=lowerCamelCase_).raw) if mlm_model: lowerCAmelCase__ : int = '''a bunch of [MASK] laying on a [MASK].''' else: lowerCAmelCase__ : Optional[int] = '''How many cats are there?''' lowerCAmelCase__ : Optional[int] = processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''') lowerCAmelCase__ : Any = model(**lowerCamelCase_) # Verify outputs if mlm_model: lowerCAmelCase__ : Dict = torch.Size([1, 11, 30522]) lowerCAmelCase__ : int = torch.tensor([-12.5061, -12.5123, -12.5174]) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] ,lowerCamelCase_ ,atol=1E-4) # verify masked token prediction equals "cats" lowerCAmelCase__ : Optional[Any] = outputs.logits[0, 4, :].argmax(-1).item() assert tokenizer.decode([predicted_id]) == "cats" elif vqa_model: lowerCAmelCase__ : List[Any] = torch.Size([1, 3129]) lowerCAmelCase__ : str = torch.tensor([-15.9495, -18.1472, -10.3041]) assert torch.allclose(outputs.logits[0, :3] ,lowerCamelCase_ ,atol=1E-4) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] ,lowerCamelCase_ ,atol=1E-4) # verify vqa prediction equals "2" lowerCAmelCase__ : List[Any] = outputs.logits.argmax(-1).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: lowerCAmelCase__ : Union[str, Any] = torch.Size([1, 2]) lowerCAmelCase__ : Dict = torch.tensor([-2.8721, 2.1291]) assert torch.allclose(outputs.logits[0, :3] ,lowerCamelCase_ ,atol=1E-4) assert outputs.logits.shape == expected_shape Path(lowerCamelCase_).mkdir(exist_ok=lowerCamelCase_) print(f"""Saving model and processor to {pytorch_dump_folder_path}""") model.save_pretrained(lowerCamelCase_) processor.save_pretrained(lowerCamelCase_) if __name__ == "__main__": __snake_case : Dict =argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __snake_case : Union[str, Any] =parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
94
1
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __UpperCamelCase : List[Any] = logging.get_logger(__name__) __UpperCamelCase : List[Any] = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = "t5" lowercase__ = ["past_key_values"] lowercase__ = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : Dict ,lowercase_ : List[Any]=3_2_1_2_8 ,lowercase_ : List[str]=5_1_2 ,lowercase_ : List[str]=6_4 ,lowercase_ : str=2_0_4_8 ,lowercase_ : Any=6 ,lowercase_ : Any=None ,lowercase_ : Any=8 ,lowercase_ : List[Any]=3_2 ,lowercase_ : Dict=1_2_8 ,lowercase_ : List[Any]=0.1 ,lowercase_ : Any=1E-6 ,lowercase_ : Any=1.0 ,lowercase_ : List[Any]="relu" ,lowercase_ : List[str]=True ,lowercase_ : List[Any]=True ,lowercase_ : Union[str, Any]=0 ,lowercase_ : Tuple=1 ,**lowercase_ : Optional[int] ,): lowerCAmelCase__ : List[str] = vocab_size lowerCAmelCase__ : Union[str, Any] = d_model lowerCAmelCase__ : int = d_kv lowerCAmelCase__ : str = d_ff lowerCAmelCase__ : Optional[Any] = num_layers lowerCAmelCase__ : Any = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase__ : Dict = num_heads lowerCAmelCase__ : Optional[Any] = relative_attention_num_buckets lowerCAmelCase__ : Optional[Any] = relative_attention_max_distance lowerCAmelCase__ : Any = dropout_rate lowerCAmelCase__ : Optional[Any] = layer_norm_epsilon lowerCAmelCase__ : Dict = initializer_factor lowerCAmelCase__ : str = feed_forward_proj lowerCAmelCase__ : List[Any] = use_cache lowerCAmelCase__ : Optional[Any] = self.feed_forward_proj.split('''-''' ) lowerCAmelCase__ : Tuple = act_info[-1] lowerCAmelCase__ : List[Any] = act_info[0] == '''gated''' if len(lowercase_ ) > 1 and act_info[0] != "gated" or len(lowercase_ ) > 2: raise ValueError( F'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.' '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": lowerCAmelCase__ : Optional[Any] = '''gelu_new''' super().__init__( pad_token_id=lowercase_ ,eos_token_id=lowercase_ ,is_encoder_decoder=lowercase_ ,**lowercase_ ,) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" @property def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : List[Any] = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: lowerCAmelCase__ : Tuple = '''past_encoder_sequence + sequence''' lowerCAmelCase__ : List[Any] = {0: '''batch'''} lowerCAmelCase__ : List[str] = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: lowerCAmelCase__ : Optional[Any] = {0: '''batch''', 1: '''decoder_sequence'''} lowerCAmelCase__ : Dict = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(lowercase_ ,direction='''inputs''' ) return common_inputs @property def __lowerCAmelCase ( self : Any ): return 1_3
106
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING _lowercase: Any = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase ) class _lowercase ( lowerCAmelCase ): """simple docstring""" def __init__(self , **lowerCamelCase_ ): """simple docstring""" super().__init__(**lowerCamelCase_ ) requires_backends(self , "vision" ) requires_backends(self , "torch" ) if self.framework != "pt": raise ValueError(F'''The {self.__class__} is only available in PyTorch.''' ) self.check_model_type(lowerCamelCase_ ) def UpperCamelCase_ (self , **lowerCamelCase_ ): """simple docstring""" a = {} a = {} a = {} # preprocess args if "points_per_batch" in kwargs: a = kwargs["points_per_batch"] if "points_per_crop" in kwargs: a = kwargs["points_per_crop"] if "crops_n_layers" in kwargs: a = kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: a = kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: a = kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: a = kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: a = kwargs["stability_score_offset"] if "mask_threshold" in kwargs: a = kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: a = kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: a = kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: a = kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: a = kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self , lowerCamelCase_ , *lowerCamelCase_ , lowerCamelCase_=None , lowerCamelCase_=None , **lowerCamelCase_ ): """simple docstring""" return super().__call__(lowerCamelCase_ , *lowerCamelCase_ , num_workers=lowerCamelCase_ , batch_size=lowerCamelCase_ , **lowerCamelCase_ ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_=64 , lowerCamelCase_ = 0 , lowerCamelCase_ = 512 / 1500 , lowerCamelCase_ = 32 , lowerCamelCase_ = 1 , ): """simple docstring""" a = load_image(lowerCamelCase_ ) a = self.image_processor.size["longest_edge"] a , a , a , a = self.image_processor.generate_crop_boxes( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) a = self.image_processor(images=lowerCamelCase_ , return_tensors="pt" ) with self.device_placement(): if self.framework == "pt": a = self.get_inference_context() with inference_context(): a = self._ensure_tensor_on_device(lowerCamelCase_ , device=self.device ) a = self.model.get_image_embeddings(model_inputs.pop("pixel_values" ) ) a = image_embeddings a = grid_points.shape[1] a = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None" ) for i in range(0 , lowerCamelCase_ , lowerCamelCase_ ): a = grid_points[:, i : i + points_per_batch, :, :] a = input_labels[:, i : i + points_per_batch] a = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_=0.88 , lowerCamelCase_=0.95 , lowerCamelCase_=0 , lowerCamelCase_=1 , ): """simple docstring""" a = model_inputs.pop("input_boxes" ) a = model_inputs.pop("is_last" ) a = model_inputs.pop("original_sizes" ).tolist() a = model_inputs.pop("reshaped_input_sizes" ).tolist() a = self.model(**lowerCamelCase_ ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks a = model_outputs["pred_masks"] a = self.image_processor.post_process_masks( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , binarize=lowerCamelCase_ ) a = model_outputs["iou_scores"] a , a , a = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_=False , lowerCamelCase_=False , lowerCamelCase_=0.7 , ): """simple docstring""" a = [] a = [] a = [] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores" ) ) all_masks.extend(model_output.pop("masks" ) ) all_boxes.append(model_output.pop("boxes" ) ) a = torch.cat(lowerCamelCase_ ) a = torch.cat(lowerCamelCase_ ) a , a , a , a = self.image_processor.post_process_for_mask_generation( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) a = defaultdict(lowerCamelCase_ ) for output in model_outputs: for k, v in output.items(): extra[k].append(lowerCamelCase_ ) a = {} if output_rle_mask: a = rle_mask if output_bboxes_mask: a = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
227
0
"""simple docstring""" import torch from transformers import AutoModel class _lowerCamelCase ( torch.nn.Module ): def __init__(self , __a="sayef/fsner-bert-base-uncased" ) -> Tuple: super(__a , self ).__init__() UpperCamelCase = AutoModel.from_pretrained(__a , return_dict=__a ) UpperCamelCase = torch.nn.CosineSimilarity(3 , 1e-0_8 ) UpperCamelCase = torch.nn.Softmax(dim=1 ) def snake_case_ (self , **__a ) -> int: return self.bert(**__a ).last_hidden_state def snake_case_ (self , __a ) -> str: return token_embeddings.sum(2 , keepdim=__a ) def snake_case_ (self , __a , __a , __a=1 ) -> int: return self.softmax(T * self.cos(__a , __a ) ) def snake_case_ (self , __a , __a ) -> List[Any]: UpperCamelCase = W_supports["sizes"].tolist() UpperCamelCase = W_supports["start_token_id"].item() UpperCamelCase = W_supports["end_token_id"].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase = self.BERT(**__a ) UpperCamelCase = self.BERT(**__a ) UpperCamelCase = None UpperCamelCase = None UpperCamelCase = W_supports["input_ids"] == start_token_id UpperCamelCase = W_supports["input_ids"] == end_token_id for i, size in enumerate(__a ): if i == 0: UpperCamelCase = 0 else: UpperCamelCase = support_sizes[i - 1] UpperCamelCase = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase = torch.vstack((p_starts, p_start) ) UpperCamelCase = torch.vstack((p_ends, p_end) ) else: UpperCamelCase = p_start UpperCamelCase = p_end return p_starts, p_ends
244
"""simple docstring""" import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict lowerCAmelCase__ = namedtuple( '''_TestCommandArgs''', [ '''dataset''', '''name''', '''cache_dir''', '''data_dir''', '''all_configs''', '''save_infos''', '''ignore_verifications''', '''force_redownload''', '''clear_cache''', ], defaults=[None, None, None, False, False, False, False, False], ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = _TestCommandArgs(dataset=_SCREAMING_SNAKE_CASE , all_configs=_SCREAMING_SNAKE_CASE , save_infos=_SCREAMING_SNAKE_CASE ) UpperCamelCase = TestCommand(*_SCREAMING_SNAKE_CASE ) test_command.run() UpperCamelCase = os.path.join(_SCREAMING_SNAKE_CASE , "README.md" ) assert os.path.exists(_SCREAMING_SNAKE_CASE ) UpperCamelCase = DatasetInfosDict.from_directory(_SCREAMING_SNAKE_CASE ) UpperCamelCase = DatasetInfosDict( { "default": DatasetInfo( features=Features( { "tokens": Sequence(Value("string" ) ), "ner_tags": Sequence( ClassLabel(names=["O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] ) ), "langs": Sequence(Value("string" ) ), "spans": Sequence(Value("string" ) ), } ) , splits=[ { "name": "train", "num_bytes": 2_351_563, "num_examples": 10_000, }, { "name": "validation", "num_bytes": 238_418, "num_examples": 1_000, }, ] , download_size=3_940_680 , dataset_size=2_589_981 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: UpperCamelCase , UpperCamelCase = getattr(dataset_infos["default"] , _SCREAMING_SNAKE_CASE ), getattr(expected_dataset_infos["default"] , _SCREAMING_SNAKE_CASE ) if key == "num_bytes": assert is_apercent_close(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif key == "splits": assert list(_SCREAMING_SNAKE_CASE ) == list(_SCREAMING_SNAKE_CASE ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
244
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __A = logging.get_logger(__name__) __A = '''▁''' __A = {'''vocab_file''': '''sentencepiece.bpe.model''', '''monolingual_vocab_file''': '''dict.txt'''} __A = { '''vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model''', }, '''monolingual_vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt''', }, } __A = {'''vinai/bartpho-syllable''': 10_24} class __lowerCAmelCase ( __a ): """simple docstring""" snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ['''input_ids''', '''attention_mask'''] def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__="<s>" , lowerCamelCase__="</s>" , lowerCamelCase__="</s>" , lowerCamelCase__="<s>" , lowerCamelCase__="<unk>" , lowerCamelCase__="<pad>" , lowerCamelCase__="<mask>" , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> None: '''simple docstring''' __lowerCamelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else mask_token __lowerCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , cls_token=__a , pad_token=__a , mask_token=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) __lowerCamelCase = vocab_file __lowerCamelCase = monolingual_vocab_file __lowerCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__a ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __lowerCamelCase = {} __lowerCamelCase = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(__a ) not in self.fairseq_tokens_to_ids: __lowerCamelCase = cnt cnt += 1 with open(__a , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __lowerCamelCase = line.strip().split()[0] __lowerCamelCase = len(self.fairseq_tokens_to_ids ) if str(__a ) not in self.fairseq_tokens_to_ids: __lowerCamelCase = len(self.fairseq_tokens_to_ids ) __lowerCamelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Dict: '''simple docstring''' __lowerCamelCase = self.__dict__.copy() __lowerCamelCase = None __lowerCamelCase = self.sp_model.serialized_model_proto() return state def __setstate__( self , lowerCamelCase__ ) -> Any: '''simple docstring''' __lowerCamelCase = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __lowerCamelCase = {} __lowerCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) if token_ids_a is None: return [1] + ([0] * len(__a )) + [1] return [1] + ([0] * len(__a )) + [1, 1] + ([0] * len(__a )) + [1] def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None ) -> List[int]: '''simple docstring''' __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowercase_ ( self ) -> List[Any]: '''simple docstring''' return len(self.fairseq_ids_to_tokens ) def lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowercase_ ( self , lowerCamelCase__ ) -> List[str]: '''simple docstring''' return self.sp_model.encode(__a , out_type=__a ) def lowercase_ ( self , lowerCamelCase__ ) -> Any: '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def lowercase_ ( self , lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.fairseq_ids_to_tokens[index] def lowercase_ ( self , lowerCamelCase__ ) -> Tuple: '''simple docstring''' __lowerCamelCase = """""".join(__a ).replace(__a , ' ' ).strip() return out_string def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(__a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( __a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase = os.path.join( __a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __a ) elif not os.path.isfile(self.vocab_file ): with open(__a , 'wb' ) as fi: __lowerCamelCase = self.sp_model.serialized_model_proto() fi.write(__a ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( __a ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , __a ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(__a , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f"""{str(__a )} \n""" ) return out_vocab_file, out_monolingual_vocab_file
90
import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_utils import GenerationTesterMixin 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 MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder def snake_case_ ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : str , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : Any=None , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : Optional[Any]=None , lowerCAmelCase_ : Tuple=None , ): if attention_mask is None: __lowercase : Tuple = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __lowercase : Any = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __lowercase : Any = torch.ones(config.encoder_layers , config.encoder_attention_heads , device=lowerCAmelCase_ ) if decoder_head_mask is None: __lowercase : List[Any] = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=lowerCAmelCase_ ) if cross_attn_head_mask is None: __lowercase : List[Any] = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=lowerCAmelCase_ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } class lowerCAmelCase : '''simple docstring''' def __init__( self : Union[str, Any] , __a : str , __a : Tuple=13 , __a : List[Any]=7 , __a : Any=True , __a : List[str]=False , __a : Optional[Any]=99 , __a : Tuple=16 , __a : int=2 , __a : Optional[Any]=4 , __a : int=4 , __a : Any="relu" , __a : Optional[int]=0.1 , __a : List[str]=0.1 , __a : Dict=0.0 , __a : List[str]=0.0 , __a : Union[str, Any]=20 , __a : str=2 , __a : str=1 , __a : Optional[int]=0 , ) -> Optional[int]: """simple docstring""" __lowercase : Any = parent __lowercase : Tuple = batch_size __lowercase : Any = seq_length __lowercase : Tuple = is_training __lowercase : Optional[Any] = use_labels __lowercase : Dict = vocab_size __lowercase : Optional[Any] = hidden_size __lowercase : Dict = num_hidden_layers __lowercase : Dict = num_attention_heads __lowercase : Dict = intermediate_size __lowercase : Union[str, Any] = hidden_act __lowercase : Union[str, Any] = hidden_dropout_prob __lowercase : Tuple = attention_probs_dropout_prob __lowercase : Tuple = encoder_layerdrop __lowercase : List[str] = decoder_layerdrop __lowercase : Any = max_position_embeddings __lowercase : Any = eos_token_id __lowercase : Dict = pad_token_id __lowercase : List[str] = bos_token_id def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" __lowercase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase : str = self.eos_token_id # Eos Token __lowercase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for M2M100 the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __lowercase : Tuple = input_ids.clamp(self.pad_token_id + 1 ) __lowercase : Optional[int] = decoder_input_ids.clamp(self.pad_token_id + 1 ) __lowercase : List[str] = self.get_config() __lowercase : str = prepare_mam_aaa_inputs_dict(__a , __a , __a ) return config, inputs_dict def lowerCAmelCase ( self : str ) -> Dict: """simple docstring""" return MaMaaaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , encoder_layerdrop=self.encoder_layerdrop , decoder_layerdrop=self.decoder_layerdrop , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , ) def lowerCAmelCase ( self : Dict ) -> str: """simple docstring""" __lowercase , __lowercase : int = self.prepare_config_and_inputs() return config, inputs_dict def lowerCAmelCase ( self : int , __a : str , __a : str ) -> int: """simple docstring""" __lowercase : Optional[Any] = MaMaaaModel(config=__a ).get_decoder().to(__a ).eval() __lowercase : List[str] = inputs_dict["""input_ids"""] __lowercase : Dict = inputs_dict["""attention_mask"""] __lowercase : List[Any] = inputs_dict["""head_mask"""] # first forward pass __lowercase : List[str] = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a ) __lowercase , __lowercase : str = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __lowercase : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __lowercase : str = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __lowercase : List[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowercase : Optional[Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __lowercase : Optional[int] = model(__a , attention_mask=__a )["""last_hidden_state"""] __lowercase : Union[str, Any] = model(__a , attention_mask=__a , past_key_values=__a )[ """last_hidden_state""" ] # select random slice __lowercase : Optional[int] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __lowercase : int = output_from_no_past[:, -3:, random_slice_idx].detach() __lowercase : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__a , __a , atol=1E-2 ) ) def lowerCAmelCase ( self : List[str] , __a : Tuple , __a : List[str] ) -> str: """simple docstring""" __lowercase : Dict = MaMaaaModel(config=__a ).to(__a ).eval() __lowercase : Any = model(**__a ) __lowercase : str = outputs.encoder_last_hidden_state __lowercase : Optional[Any] = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: __lowercase : str = model.get_encoder() encoder.save_pretrained(__a ) __lowercase : List[Any] = MaMaaaEncoder.from_pretrained(__a ).to(__a ) __lowercase : Tuple = encoder(inputs_dict["""input_ids"""] , attention_mask=inputs_dict["""attention_mask"""] )[ 0 ] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) with tempfile.TemporaryDirectory() as tmpdirname: __lowercase : Tuple = model.get_decoder() decoder.save_pretrained(__a ) __lowercase : Tuple = MaMaaaDecoder.from_pretrained(__a ).to(__a ) __lowercase : Tuple = decoder( input_ids=inputs_dict["""decoder_input_ids"""] , attention_mask=inputs_dict["""decoder_attention_mask"""] , encoder_hidden_states=__a , encoder_attention_mask=inputs_dict["""attention_mask"""] , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class lowerCAmelCase ( __a , __a , __a , unittest.TestCase ): '''simple docstring''' _A : int = ( ( MaMaaaModel, MaMaaaForConditionalGeneration, ) if is_torch_available() else () ) _A : int = (MaMaaaForConditionalGeneration,) if is_torch_available() else () _A : Union[str, Any] = ( { '''conversational''': MaMaaaForConditionalGeneration, '''feature-extraction''': MaMaaaModel, '''summarization''': MaMaaaForConditionalGeneration, '''text2text-generation''': MaMaaaForConditionalGeneration, '''translation''': MaMaaaForConditionalGeneration, } if is_torch_available() else {} ) _A : Optional[int] = True _A : Union[str, Any] = True _A : Any = False _A : int = False def lowerCAmelCase ( self : str , __a : Union[str, Any] , __a : Optional[int] , __a : List[Any] , __a : Tuple , __a : Optional[int] ) -> Any: """simple docstring""" if pipeline_test_casse_name == "TranslationPipelineTests": # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`. # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer. return True return False def lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __lowercase : int = MaMaaaModelTester(self ) __lowercase : Union[str, Any] = ConfigTester(self , config_class=__a ) def lowerCAmelCase ( self : Any ) -> str: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" __lowercase , __lowercase : Any = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: __lowercase : List[str] = model_class(__a ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__a ) __lowercase , __lowercase : str = model_class.from_pretrained(__a , output_loading_info=__a ) self.assertEqual(info["""missing_keys"""] , [] ) def lowerCAmelCase ( self : int ) -> List[Any]: """simple docstring""" __lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*__a ) def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*__a ) def lowerCAmelCase ( self : int ) -> Any: """simple docstring""" __lowercase , __lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration): __lowercase : Union[str, Any] = model_class(__a ) model.to(__a ) model.eval() __lowercase : Any = copy.deepcopy(self._prepare_for_class(__a , __a ) ) if not self.is_encoder_decoder: __lowercase : int = inputs["""input_ids"""] del inputs["input_ids"] else: __lowercase : Optional[int] = inputs["""input_ids"""] __lowercase : Optional[Any] = inputs.get("""decoder_input_ids""" , __a ) del inputs["input_ids"] inputs.pop("""decoder_input_ids""" , __a ) __lowercase : Union[str, Any] = model.get_input_embeddings() if not self.is_encoder_decoder: __lowercase : Dict = wte(__a ) else: __lowercase : str = wte(__a ) __lowercase : Union[str, Any] = wte(__a ) with torch.no_grad(): model(**__a )[0] def lowerCAmelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" __lowercase , __lowercase : str = self.model_tester.prepare_config_and_inputs() __lowercase : List[str] = input_dict["""input_ids"""] __lowercase : Optional[int] = input_ids.ne(1 ).to(__a ) __lowercase : List[Any] = MaMaaaForConditionalGeneration(__a ).eval().to(__a ) if torch_device == "cuda": model.half() model.generate(__a , attention_mask=__a ) model.generate(num_beams=4 , do_sample=__a , early_stopping=__a , num_return_sequences=3 ) def snake_case_ ( lowerCAmelCase_ : Optional[Any] ): return torch.tensor(lowerCAmelCase_ , dtype=torch.long , device=lowerCAmelCase_ ) lowerCamelCase : Dict = 1E-4 @require_torch @require_sentencepiece @require_tokenizers @slow class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" ) def lowerCAmelCase ( self : Any ) -> Tuple: """simple docstring""" __lowercase : List[str] = MaMaaaModel.from_pretrained("""facebook/m2m100_418M""" ).to(__a ) __lowercase : Union[str, Any] = _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]] ) __lowercase : int = _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]] ) __lowercase : int = prepare_mam_aaa_inputs_dict(model.config , __a , __a ) with torch.no_grad(): __lowercase : int = model(**__a )[0] __lowercase : int = torch.Size((1, 11, 1024) ) self.assertEqual(output.shape , __a ) # change to expected output here __lowercase : Dict = torch.tensor( [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]] , device=__a ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=__a ) ) def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __lowercase : Tuple = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(__a ) # change to intended input __lowercase : Any = _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]] ) __lowercase : Union[str, Any] = _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]] ) __lowercase : Tuple = prepare_mam_aaa_inputs_dict(model.config , __a , __a ) with torch.no_grad(): __lowercase : Optional[Any] = model(**__a )[0] __lowercase : Tuple = torch.Size((1, 11, model.config.vocab_size) ) self.assertEqual(output.shape , __a ) # change to expected output here __lowercase : Union[str, Any] = torch.tensor( [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]] , device=__a ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=__a ) ) def lowerCAmelCase ( self : Optional[int] ) -> int: """simple docstring""" __lowercase : List[str] = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(__a ) __lowercase : Tuple = MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" , src_lang="""fr""" , tgt_lang="""en""" ) __lowercase : Dict = [ """L'affaire NSA souligne l'absence totale de débat sur le renseignement""", """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""", """Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent""" """ Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de""" """ l'ampleur de la surveillance américaine sur l'ensemble des communications en France.""", ] # The below article tests that we don't add any hypotheses outside of the top n_beams __lowercase : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors="""pt""" ) __lowercase : Dict = model.generate( input_ids=dct["""input_ids"""].to(__a ) , attention_mask=dct["""attention_mask"""].to(__a ) , num_beams=5 , forced_bos_token_id=tokenizer.get_lang_id("""en""" ) , ) __lowercase : Any = [ """The NSA case highlights the total absence of intelligence debate""", """I think there are two levels of response from the French government.""", """When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.""" """ Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all""" """ communications in France.""", ] __lowercase : Dict = tokenizer.batch_decode( hypotheses_batch.tolist() , clean_up_tokenization_spaces=__a , skip_special_tokens=__a ) assert generated == expected_en
233
0
def lowerCamelCase__ ( UpperCamelCase__ : float ) -> float: '''simple docstring''' if edge <= 0 or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError('Length must be a positive.' ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def lowerCamelCase__ ( UpperCamelCase__ : float ) -> float: '''simple docstring''' if edge <= 0 or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError('Length must be a positive.' ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
295
def lowerCamelCase__ ( UpperCamelCase__ : list[list[int]] , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : list[int] ) -> bool: '''simple docstring''' if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def lowerCamelCase__ ( UpperCamelCase__ : list[list[int]] , UpperCamelCase__ : list[int] , UpperCamelCase__ : int ) -> bool: '''simple docstring''' if curr_ind == len(UpperCamelCase__ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(UpperCamelCase__ ) ): if valid_connection(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # Insert current vertex into path as next transition _snake_case = next_ver # Validate created path if util_hamilton_cycle(UpperCamelCase__ , UpperCamelCase__ , curr_ind + 1 ): return True # Backtrack _snake_case = -1 return False def lowerCamelCase__ ( UpperCamelCase__ : list[list[int]] , UpperCamelCase__ : int = 0 ) -> list[int]: '''simple docstring''' _snake_case = [-1] * (len(UpperCamelCase__ ) + 1) # initialize start and end of path with starting index _snake_case = _snake_case = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(UpperCamelCase__ , UpperCamelCase__ , 1 ) else []
295
1
'''simple docstring''' import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_utils import GenerationTesterMixin 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 MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Any , lowercase : List[str] , lowercase : Union[str, Any]=None , lowercase : Any=None , lowercase : int=None , lowercase : List[str]=None , lowercase : List[str]=None , ) -> Union[str, Any]: if attention_mask is None: _a = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: _a = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: _a = torch.ones(config.encoder_layers , config.encoder_attention_heads , device=_a ) if decoder_head_mask is None: _a = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=_a ) if cross_attn_head_mask is None: _a = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=_a ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : int , __a : int=13 , __a : str=7 , __a : Any=True , __a : Union[str, Any]=False , __a : Optional[Any]=99 , __a : str=16 , __a : str=2 , __a : List[str]=4 , __a : Dict=4 , __a : List[str]="relu" , __a : Dict=0.1 , __a : str=0.1 , __a : Optional[int]=0.0 , __a : Optional[Any]=0.0 , __a : Any=20 , __a : Union[str, Any]=2 , __a : List[str]=1 , __a : List[str]=0 , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = encoder_layerdrop _a = decoder_layerdrop _a = max_position_embeddings _a = eos_token_id _a = pad_token_id _a = bos_token_id def UpperCamelCase__ ( self : List[str] ): _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = self.eos_token_id # Eos Token _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for M2M100 the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input _a = input_ids.clamp(self.pad_token_id + 1 ) _a = decoder_input_ids.clamp(self.pad_token_id + 1 ) _a = self.get_config() _a = prepare_mam_aaa_inputs_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return config, inputs_dict def UpperCamelCase__ ( self : str ): return MaMaaaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , encoder_layerdrop=self.encoder_layerdrop , decoder_layerdrop=self.decoder_layerdrop , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , ) def UpperCamelCase__ ( self : int ): _a = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase__ ( self : int , __a : Optional[Any] , __a : int ): _a = MaMaaaModel(config=_SCREAMING_SNAKE_CASE ).get_decoder().to(_SCREAMING_SNAKE_CASE ).eval() _a = inputs_dict['''input_ids'''] _a = inputs_dict['''attention_mask'''] _a = inputs_dict['''head_mask'''] # first forward pass _a = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , use_cache=_SCREAMING_SNAKE_CASE ) _a = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids _a = ids_tensor((self.batch_size, 3) , config.vocab_size ) _a = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and _a = torch.cat([input_ids, next_tokens] , dim=-1 ) _a = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) _a = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE )['''last_hidden_state'''] _a = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE )[ '''last_hidden_state''' ] # select random slice _a = ids_tensor((1,) , output_from_past.shape[-1] ).item() _a = output_from_no_past[:, -3:, random_slice_idx].detach() _a = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-2 ) ) def UpperCamelCase__ ( self : int , __a : List[Any] , __a : Optional[int] ): _a = MaMaaaModel(config=_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ).eval() _a = model(**_SCREAMING_SNAKE_CASE ) _a = outputs.encoder_last_hidden_state _a = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: _a = model.get_encoder() encoder.save_pretrained(_SCREAMING_SNAKE_CASE ) _a = MaMaaaEncoder.from_pretrained(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) _a = encoder(inputs_dict["input_ids"] , attention_mask=inputs_dict["attention_mask"] )[ 0 ] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) with tempfile.TemporaryDirectory() as tmpdirname: _a = model.get_decoder() decoder.save_pretrained(_SCREAMING_SNAKE_CASE ) _a = MaMaaaDecoder.from_pretrained(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) _a = decoder( input_ids=inputs_dict["decoder_input_ids"] , attention_mask=inputs_dict["decoder_attention_mask"] , encoder_hidden_states=_SCREAMING_SNAKE_CASE , encoder_attention_mask=inputs_dict["attention_mask"] , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class __SCREAMING_SNAKE_CASE (_lowercase , _lowercase , _lowercase , unittest.TestCase ): """simple docstring""" __a =( ( MaMaaaModel, MaMaaaForConditionalGeneration, ) if is_torch_available() else () ) __a =(MaMaaaForConditionalGeneration,) if is_torch_available() else () __a =( { '''conversational''': MaMaaaForConditionalGeneration, '''feature-extraction''': MaMaaaModel, '''summarization''': MaMaaaForConditionalGeneration, '''text2text-generation''': MaMaaaForConditionalGeneration, '''translation''': MaMaaaForConditionalGeneration, } if is_torch_available() else {} ) __a =True __a =True __a =False __a =False def UpperCamelCase__ ( self : Optional[int] , __a : List[str] , __a : List[str] , __a : str , __a : Dict , __a : List[Any] ): if pipeline_test_casse_name == "TranslationPipelineTests": # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`. # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer. return True return False def UpperCamelCase__ ( self : Optional[int] ): _a = MaMaaaModelTester(self ) _a = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( self : List[Any] ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self : int ): _a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: _a = model_class(_SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE ) _a = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE ) self.assertEqual(info["missing_keys"] , [] ) def UpperCamelCase__ ( self : str ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*_SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( self : Any ): _a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration): _a = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _a = copy.deepcopy(self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) if not self.is_encoder_decoder: _a = inputs['''input_ids'''] del inputs["input_ids"] else: _a = inputs['''input_ids'''] _a = inputs.get("decoder_input_ids" , _SCREAMING_SNAKE_CASE ) del inputs["input_ids"] inputs.pop("decoder_input_ids" , _SCREAMING_SNAKE_CASE ) _a = model.get_input_embeddings() if not self.is_encoder_decoder: _a = wte(_SCREAMING_SNAKE_CASE ) else: _a = wte(_SCREAMING_SNAKE_CASE ) _a = wte(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): model(**_SCREAMING_SNAKE_CASE )[0] def UpperCamelCase__ ( self : Optional[Any] ): _a = self.model_tester.prepare_config_and_inputs() _a = input_dict['''input_ids'''] _a = input_ids.ne(1 ).to(_SCREAMING_SNAKE_CASE ) _a = MaMaaaForConditionalGeneration(_SCREAMING_SNAKE_CASE ).eval().to(_SCREAMING_SNAKE_CASE ) if torch_device == "cuda": model.half() model.generate(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) model.generate(num_beams=4 , do_sample=_SCREAMING_SNAKE_CASE , early_stopping=_SCREAMING_SNAKE_CASE , num_return_sequences=3 ) def _lowerCamelCase ( lowercase : List[str] ) -> str: return torch.tensor(_a , dtype=torch.long , device=_a ) lowerCAmelCase_ : Optional[int] = 1e-4 @require_torch @require_sentencepiece @require_tokenizers @slow class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" @cached_property def UpperCamelCase__ ( self : int ): return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M" ) def UpperCamelCase__ ( self : Optional[int] ): _a = MaMaaaModel.from_pretrained("facebook/m2m100_418M" ).to(_SCREAMING_SNAKE_CASE ) _a = _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]] ) _a = _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]] ) _a = prepare_mam_aaa_inputs_dict(model.config , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with torch.no_grad(): _a = model(**_SCREAMING_SNAKE_CASE )[0] _a = torch.Size((1, 11, 10_24) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) # change to expected output here _a = torch.tensor( [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]] , device=_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(output[:, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) def UpperCamelCase__ ( self : Optional[Any] ): _a = MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M" ).to(_SCREAMING_SNAKE_CASE ) # change to intended input _a = _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]] ) _a = _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]] ) _a = prepare_mam_aaa_inputs_dict(model.config , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with torch.no_grad(): _a = model(**_SCREAMING_SNAKE_CASE )[0] _a = torch.Size((1, 11, model.config.vocab_size) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) # change to expected output here _a = torch.tensor( [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]] , device=_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(output[:, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) def UpperCamelCase__ ( self : Tuple ): _a = MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M" ).to(_SCREAMING_SNAKE_CASE ) _a = MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M" , src_lang="fr" , tgt_lang="en" ) _a = [ '''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''', '''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''', '''Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent''' ''' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de''' ''' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.''', ] # The below article tests that we don't add any hypotheses outside of the top n_beams _a = tokenizer(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="pt" ) _a = model.generate( input_ids=dct["input_ids"].to(_SCREAMING_SNAKE_CASE ) , attention_mask=dct["attention_mask"].to(_SCREAMING_SNAKE_CASE ) , num_beams=5 , forced_bos_token_id=tokenizer.get_lang_id("en" ) , ) _a = [ '''The NSA case highlights the total absence of intelligence debate''', '''I think there are two levels of response from the French government.''', '''When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.''' ''' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all''' ''' communications in France.''', ] _a = tokenizer.batch_decode( hypotheses_batch.tolist() , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) assert generated == expected_en
63
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase = logging.get_logger() @dataclass class _a : _a : nn.Module _a : List[nn.Module] = field(default_factory=_lowercase) _a : list = field(default_factory=_lowercase) def UpperCAmelCase__( self : Tuple , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Tensor , _SCREAMING_SNAKE_CASE : Tensor )-> Any: lowerCAmelCase__ : str = len(list(m.modules() ) ) == 1 or isinstance(_SCREAMING_SNAKE_CASE , nn.Convad ) or isinstance(_SCREAMING_SNAKE_CASE , nn.BatchNormad ) if has_not_submodules: self.traced.append(_SCREAMING_SNAKE_CASE ) def __call__( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : Tensor )-> str: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(_SCREAMING_SNAKE_CASE ) [x.remove() for x in self.handles] return self @property def UpperCAmelCase__( self : Any )-> Union[str, Any]: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda _SCREAMING_SNAKE_CASE : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class _a : _a : nn.Module _a : nn.Module _a : int = 1 _a : List = field(default_factory=_lowercase) _a : List = field(default_factory=_lowercase) _a : bool = True def __call__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : Tensor )-> str: lowerCAmelCase__ : List[Any] = Tracker(self.dest )(_SCREAMING_SNAKE_CASE ).parametrized lowerCAmelCase__ : str = Tracker(self.src )(_SCREAMING_SNAKE_CASE ).parametrized lowerCAmelCase__ : List[str] = list(filter(lambda _SCREAMING_SNAKE_CASE : type(_SCREAMING_SNAKE_CASE ) not in self.src_skip , _SCREAMING_SNAKE_CASE ) ) lowerCAmelCase__ : str = list(filter(lambda _SCREAMING_SNAKE_CASE : type(_SCREAMING_SNAKE_CASE ) not in self.dest_skip , _SCREAMING_SNAKE_CASE ) ) if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ) and self.raise_if_mismatch: raise Exception( F'Numbers of operations are different. Source module has {len(_SCREAMING_SNAKE_CASE )} operations while' F' destination module has {len(_SCREAMING_SNAKE_CASE )}.' ) for dest_m, src_m in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'Transfered from={src_m} to={dest_m}' ) class _a ( nn.Module): def __init__( self : List[Any] , _SCREAMING_SNAKE_CASE : nn.Module )-> Optional[int]: super().__init__() lowerCAmelCase__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('''conv1''', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('''block''' ), F'Unexpected layer name {k}' lowerCAmelCase__ : Optional[int] = len(_SCREAMING_SNAKE_CASE ) + 1 feature_blocks.append((F'res{block_index}', v) ) lowerCAmelCase__ : List[str] = nn.ModuleDict(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__( self : int , _SCREAMING_SNAKE_CASE : Tensor )-> List[str]: return get_trunk_forward_outputs( _SCREAMING_SNAKE_CASE , out_feat_keys=_SCREAMING_SNAKE_CASE , feature_blocks=self._feature_blocks , ) class _a ( _lowercase): def UpperCAmelCase__( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : str )-> str: lowerCAmelCase__ : int = x.split('''-''' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : str )-> Callable[[], Tuple[nn.Module, Dict]]: # default to timm! if x not in self: lowerCAmelCase__ : Optional[Any] = self.convert_name_to_timm(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : List[str] = partial(lambda: (timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ).eval(), None) ) else: lowerCAmelCase__ : Any = super().__getitem__(_SCREAMING_SNAKE_CASE ) return val class _a ( _lowercase): def __getitem__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : str )-> Callable[[], nn.Module]: if "seer" in x and "in1k" not in x: lowerCAmelCase__ : int = RegNetModel else: lowerCAmelCase__ : List[str] = RegNetForImageClassification return val def lowerCamelCase_ ( _a , _a , _a ): """simple docstring""" for from_key, to_key in keys: lowerCAmelCase__ : Optional[Any] = from_state_dict[from_key].clone() print(f'Copied key={from_key} to={to_key}' ) return to_state_dict def lowerCamelCase_ ( _a , _a , _a , _a , _a , _a = True , ): """simple docstring""" print(f'Converting {name}...' ) with torch.no_grad(): lowerCAmelCase__ , lowerCAmelCase__ : int = from_model_func() lowerCAmelCase__ : Optional[Any] = our_model_func(_a ).eval() lowerCAmelCase__ : int = ModuleTransfer(src=_a , dest=_a , raise_if_mismatch=_a ) lowerCAmelCase__ : str = torch.randn((1, 3, 224, 224) ) module_transfer(_a ) if from_state_dict is not None: lowerCAmelCase__ : Any = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: lowerCAmelCase__ : List[Any] = [('''0.clf.0.weight''', '''classifier.1.weight'''), ('''0.clf.0.bias''', '''classifier.1.bias''')] lowerCAmelCase__ : int = manually_copy_vissl_head(_a , our_model.state_dict() , _a ) our_model.load_state_dict(_a ) lowerCAmelCase__ : List[str] = our_model(_a , output_hidden_states=_a ) lowerCAmelCase__ : Dict = ( our_outputs.logits if isinstance(_a , _a ) else our_outputs.last_hidden_state ) lowerCAmelCase__ : Tuple = from_model(_a ) lowerCAmelCase__ : int = from_output[-1] if type(_a ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: lowerCAmelCase__ : Optional[int] = our_outputs.hidden_states[-1] assert torch.allclose(_a , _a ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='''Add model''' , use_temp_dir=_a , ) lowerCAmelCase__ : Optional[int] = 224 if '''seer''' not in name else 384 # we can use the convnext one lowerCAmelCase__ : int = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' , size=_a ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='''Add image processor''' , use_temp_dir=_a , ) print(f'Pushed {name}' ) def lowerCamelCase_ ( _a , _a = None , _a = True ): """simple docstring""" lowerCAmelCase__ : str = '''imagenet-1k-id2label.json''' lowerCAmelCase__ : Dict = 1_000 lowerCAmelCase__ : Optional[int] = (1, num_labels) lowerCAmelCase__ : Optional[int] = '''huggingface/label-files''' lowerCAmelCase__ : Tuple = num_labels lowerCAmelCase__ : List[Any] = json.load(open(cached_download(hf_hub_url(_a , _a , repo_type='''dataset''' ) ) , '''r''' ) ) lowerCAmelCase__ : Dict = {int(_a ): v for k, v in idalabel.items()} lowerCAmelCase__ : List[Any] = idalabel lowerCAmelCase__ : Union[str, Any] = {v: k for k, v in idalabel.items()} lowerCAmelCase__ : Dict = partial(_a , num_labels=_a , idalabel=_a , labelaid=_a ) lowerCAmelCase__ : Tuple = { '''regnet-x-002''': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type='''x''' ), '''regnet-x-004''': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type='''x''' ), '''regnet-x-006''': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type='''x''' ), '''regnet-x-008''': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type='''x''' ), '''regnet-x-016''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type='''x''' ), '''regnet-x-032''': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1_008] , groups_width=48 , layer_type='''x''' ), '''regnet-x-040''': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1_360] , groups_width=40 , layer_type='''x''' ), '''regnet-x-064''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1_624] , groups_width=56 , layer_type='''x''' ), '''regnet-x-080''': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1_920] , groups_width=120 , layer_type='''x''' ), '''regnet-x-120''': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2_240] , groups_width=112 , layer_type='''x''' ), '''regnet-x-160''': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2_048] , groups_width=128 , layer_type='''x''' ), '''regnet-x-320''': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1_344, 2_520] , groups_width=168 , layer_type='''x''' ), # y variant '''regnet-y-002''': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), '''regnet-y-004''': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), '''regnet-y-006''': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), '''regnet-y-008''': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), '''regnet-y-016''': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), '''regnet-y-032''': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1_512] , groups_width=24 ), '''regnet-y-040''': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1_088] , groups_width=64 ), '''regnet-y-064''': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1_296] , groups_width=72 ), '''regnet-y-080''': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2_016] , groups_width=56 ), '''regnet-y-120''': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2_240] , groups_width=112 ), '''regnet-y-160''': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1_232, 3_024] , groups_width=112 ), '''regnet-y-320''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 '''regnet-y-320-seer''': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), '''regnet-y-640-seer''': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1_968, 4_920] , groups_width=328 ), '''regnet-y-1280-seer''': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1_056, 2_904, 7_392] , groups_width=264 ), '''regnet-y-2560-seer''': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1_696, 2_544, 5_088] , groups_width=640 ), '''regnet-y-10b-seer''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2_020, 4_040, 11_110, 28_280] , groups_width=1_010 ), # finetuned on imagenet '''regnet-y-320-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1_392, 3_712] , groups_width=232 ), '''regnet-y-640-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1_968, 4_920] , groups_width=328 ), '''regnet-y-1280-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1_056, 2_904, 7_392] , groups_width=264 ), '''regnet-y-2560-seer-in1k''': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1_696, 2_544, 5_088] , groups_width=640 ), '''regnet-y-10b-seer-in1k''': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2_020, 4_040, 11_110, 28_280] , groups_width=1_010 ), } lowerCAmelCase__ : Optional[Any] = NameToOurModelFuncMap() lowerCAmelCase__ : Optional[Any] = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(_a , _a ) -> Tuple[nn.Module, Dict]: lowerCAmelCase__ : Tuple = torch.hub.load_state_dict_from_url(_a , model_dir=str(_a ) , map_location='''cpu''' ) lowerCAmelCase__ : int = model_func() # check if we have a head, if yes add it lowerCAmelCase__ : int = files['''classy_state_dict''']['''base_model''']['''model'''] lowerCAmelCase__ : Tuple = model_state_dict['''trunk'''] model.load_state_dict(_a ) return model.eval(), model_state_dict["heads"] # pretrained lowerCAmelCase__ : int = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ : Optional[int] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ : Optional[int] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) lowerCAmelCase__ : Tuple = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch''' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1_010 , w_a=1_744 , w_a=6_20.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned lowerCAmelCase__ : List[Any] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ : Optional[int] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ : Union[str, Any] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch''' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) lowerCAmelCase__ : Union[str, Any] = partial( _a , '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch''' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1_010 , w_a=1_744 , w_a=6_20.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( _a , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , _a , _a , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( _a , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , _a , _a , _a , ) return config, expected_shape if __name__ == "__main__": lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported regnet* architecture,''' ''' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) lowerCamelCase = parser.parse_args() lowerCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
131
0
'''simple docstring''' import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def SCREAMING_SNAKE_CASE__ ( __A ) -> Union[str, Any]: if isinstance(__A , collections.abc.Iterable ): return x return (x, x) @require_flax class __UpperCAmelCase : def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" pass def lowerCamelCase ( self ): """simple docstring""" pass def lowerCamelCase ( self ): """simple docstring""" pass def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = np.abs((a - b) ).max() self.assertLessEqual(lowerCAmelCase_ , lowerCAmelCase_ , F'Difference between torch and flax is {diff} (>= {tol}).' ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , **lowerCAmelCase_ ): """simple docstring""" _snake_case = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = FlaxVisionTextDualEncoderModel(lowerCAmelCase_ ) _snake_case = model(input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], config.projection_dim) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , **lowerCAmelCase_ ): """simple docstring""" _snake_case , _snake_case = self.get_vision_text_model(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = {'vision_model': vision_model, 'text_model': text_model} _snake_case = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase_ ) _snake_case = model(input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , **lowerCAmelCase_ ): """simple docstring""" _snake_case , _snake_case = self.get_vision_text_model(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = {'vision_model': vision_model, 'text_model': text_model} _snake_case = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase_ ) _snake_case = model(input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) _snake_case = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowerCAmelCase_ ) _snake_case = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase_ ) _snake_case = model(input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) _snake_case = after_output[0] _snake_case = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowerCAmelCase_ , 1E-3 ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , **lowerCAmelCase_ ): """simple docstring""" _snake_case , _snake_case = self.get_vision_text_model(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = {'vision_model': vision_model, 'text_model': text_model} _snake_case = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase_ ) _snake_case = model( input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , output_attentions=lowerCAmelCase_ ) _snake_case = output.vision_model_output.attentions self.assertEqual(len(lowerCAmelCase_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) _snake_case = to_atuple(vision_model.config.image_size ) _snake_case = to_atuple(vision_model.config.patch_size ) _snake_case = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) _snake_case = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) _snake_case = output.text_model_output.attentions self.assertEqual(len(lowerCAmelCase_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" pt_model.to(lowerCAmelCase_ ) pt_model.eval() # prepare inputs _snake_case = inputs_dict _snake_case = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): _snake_case = pt_model(**lowerCAmelCase_ ).to_tuple() _snake_case = fx_model(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(lowerCAmelCase_ , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(lowerCAmelCase_ ) _snake_case = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase_ , from_pt=lowerCAmelCase_ ) _snake_case = fx_model_loaded(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(lowerCAmelCase_ , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(lowerCAmelCase_ ) _snake_case = VisionTextDualEncoderModel.from_pretrained(lowerCAmelCase_ , from_flax=lowerCAmelCase_ ) pt_model_loaded.to(lowerCAmelCase_ ) pt_model_loaded.eval() with torch.no_grad(): _snake_case = pt_model_loaded(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(lowerCAmelCase_ , pt_output_loaded.numpy() , 4E-2 ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = VisionTextDualEncoderModel(lowerCAmelCase_ ) _snake_case = FlaxVisionTextDualEncoderModel(lowerCAmelCase_ ) _snake_case = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , lowerCAmelCase_ ) _snake_case = fx_state self.check_pt_flax_equivalence(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = VisionTextDualEncoderModel(lowerCAmelCase_ ) _snake_case = FlaxVisionTextDualEncoderModel(lowerCAmelCase_ ) _snake_case = load_flax_weights_in_pytorch_model(lowerCAmelCase_ , fx_model.params ) self.check_pt_flax_equivalence(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() self.check_save_load(**lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowerCAmelCase_ ) @is_pt_flax_cross_test def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() _snake_case = config_inputs_dict.pop('vision_config' ) _snake_case = config_inputs_dict.pop('text_config' ) _snake_case = config_inputs_dict self.check_equivalence_pt_to_flax(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) self.check_equivalence_flax_to_pt(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) @slow def lowerCamelCase ( self ): """simple docstring""" _snake_case , _snake_case = self.get_pretrained_model_and_inputs() _snake_case = model_a(**lowerCAmelCase_ ) _snake_case = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowerCAmelCase_ ) _snake_case = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase_ ) _snake_case = model_a(**lowerCAmelCase_ ) _snake_case = after_outputs[0] _snake_case = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowerCAmelCase_ , 1E-5 ) @require_flax class __UpperCAmelCase ( _lowerCamelCase , unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" _snake_case = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit' , 'hf-internal-testing/tiny-bert' , vision_from_pt=lowerCAmelCase_ , text_from_pt=lowerCAmelCase_ , ) _snake_case = 13 _snake_case = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) _snake_case = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) _snake_case = random_attention_mask([batch_size, 4] ) _snake_case = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = FlaxViTModel(lowerCAmelCase_ ) _snake_case = FlaxBertModel(lowerCAmelCase_ ) return vision_model, text_model def lowerCamelCase ( self ): """simple docstring""" _snake_case = FlaxViTModelTester(self ) _snake_case = FlaxBertModelTester(self ) _snake_case = vit_model_tester.prepare_config_and_inputs() _snake_case = bert_model_tester.prepare_config_and_inputs() _snake_case , _snake_case = vision_config_and_inputs _snake_case , _snake_case , _snake_case , _snake_case = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class __UpperCAmelCase ( _lowerCamelCase , unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" _snake_case = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-clip' , 'hf-internal-testing/tiny-bert' , vision_from_pt=lowerCAmelCase_ , text_from_pt=lowerCAmelCase_ , ) _snake_case = 13 _snake_case = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) _snake_case = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) _snake_case = random_attention_mask([batch_size, 4] ) _snake_case = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = FlaxCLIPVisionModel(lowerCAmelCase_ ) _snake_case = FlaxBertModel(lowerCAmelCase_ ) return vision_model, text_model def lowerCamelCase ( self ): """simple docstring""" _snake_case = FlaxCLIPVisionModelTester(self ) _snake_case = FlaxBertModelTester(self ) _snake_case = clip_model_tester.prepare_config_and_inputs() _snake_case = bert_model_tester.prepare_config_and_inputs() _snake_case , _snake_case = vision_config_and_inputs _snake_case , _snake_case , _snake_case , _snake_case = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class __UpperCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase ( self ): """simple docstring""" _snake_case = FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' , logit_scale_init_value=1.0 ) _snake_case = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' ) _snake_case = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) _snake_case = processor( text=['una foto di un gatto', 'una foto di un cane'] , images=lowerCAmelCase_ , padding=lowerCAmelCase_ , return_tensors='np' ) _snake_case = model(**lowerCAmelCase_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) _snake_case = np.array([[1.2284727, 0.3104122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , lowerCAmelCase_ , atol=1E-3 ) )
160
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging lowercase : Optional[Any] = logging.get_logger(__name__) lowercase : List[str] = { "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json", # See all Marian models at https://huggingface.co/models?filter=marian } class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = """marian""" __lowercase = ["""past_key_values"""] __lowercase = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCAmelCase_=5_81_01 , lowerCAmelCase_=None , lowerCAmelCase_=10_24 , lowerCAmelCase_=12 , lowerCAmelCase_=40_96 , lowerCAmelCase_=16 , lowerCAmelCase_=12 , lowerCAmelCase_=40_96 , lowerCAmelCase_=16 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.0 , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_="gelu" , lowerCAmelCase_=10_24 , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.02 , lowerCAmelCase_=5_81_00 , lowerCAmelCase_=False , lowerCAmelCase_=5_81_00 , lowerCAmelCase_=0 , lowerCAmelCase_=0 , lowerCAmelCase_=True , **lowerCAmelCase_ , ): """simple docstring""" _snake_case = vocab_size _snake_case = decoder_vocab_size or vocab_size _snake_case = max_position_embeddings _snake_case = d_model _snake_case = encoder_ffn_dim _snake_case = encoder_layers _snake_case = encoder_attention_heads _snake_case = decoder_ffn_dim _snake_case = decoder_layers _snake_case = decoder_attention_heads _snake_case = dropout _snake_case = attention_dropout _snake_case = activation_dropout _snake_case = activation_function _snake_case = init_std _snake_case = encoder_layerdrop _snake_case = decoder_layerdrop _snake_case = use_cache _snake_case = encoder_layers _snake_case = scale_embedding # scale factor will be sqrt(d_model) if True _snake_case = share_encoder_decoder_embeddings super().__init__( pad_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , is_encoder_decoder=lowerCAmelCase_ , decoder_start_token_id=lowerCAmelCase_ , forced_eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ , ) class __UpperCAmelCase ( _lowerCamelCase ): @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def lowerCamelCase ( self ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: _snake_case = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: _snake_case = {0: 'batch'} _snake_case = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: _snake_case = {0: 'batch', 1: 'decoder_sequence'} _snake_case = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase_ , direction='inputs' ) elif self.task == "causal-lm": # TODO: figure this case out. _snake_case = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: _snake_case , _snake_case = self.num_layers for i in range(lowerCAmelCase_ ): _snake_case = {0: 'batch', 2: 'past_sequence + sequence'} _snake_case = {0: 'batch', 2: 'past_sequence + sequence'} else: _snake_case = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}), ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}), ] ) return common_inputs @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs def lowerCamelCase ( self ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: _snake_case = super().outputs else: _snake_case = super(lowerCAmelCase_ , self ).outputs if self.use_past: _snake_case , _snake_case = self.num_layers for i in range(lowerCAmelCase_ ): _snake_case = {0: 'batch', 2: 'past_sequence + sequence'} _snake_case = {0: 'batch', 2: 'past_sequence + sequence'} return common_outputs def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = -1 , lowerCAmelCase_ = -1 , lowerCAmelCase_ = False , lowerCAmelCase_ = None , ): """simple docstring""" _snake_case = self._generate_dummy_inputs_for_encoder_and_decoder( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Generate decoder inputs _snake_case = seq_length if not self.use_past else 1 _snake_case = self._generate_dummy_inputs_for_encoder_and_decoder( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = {F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()} _snake_case = dict(**lowerCAmelCase_ , **lowerCAmelCase_ ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch _snake_case , _snake_case = common_inputs['input_ids'].shape _snake_case = common_inputs['decoder_input_ids'].shape[1] _snake_case , _snake_case = self.num_attention_heads _snake_case = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) _snake_case = decoder_seq_length + 3 _snake_case = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) _snake_case = torch.cat( [common_inputs['decoder_attention_mask'], torch.ones(lowerCAmelCase_ , lowerCAmelCase_ )] , dim=1 ) _snake_case = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered _snake_case , _snake_case = self.num_layers _snake_case = min(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = max(lowerCAmelCase_ , lowerCAmelCase_ ) - min_num_layers _snake_case = 'encoder' if num_encoder_layers > num_decoder_layers else 'decoder' for _ in range(lowerCAmelCase_ ): common_inputs["past_key_values"].append( ( torch.zeros(lowerCAmelCase_ ), torch.zeros(lowerCAmelCase_ ), torch.zeros(lowerCAmelCase_ ), torch.zeros(lowerCAmelCase_ ), ) ) # TODO: test this. _snake_case = encoder_shape if remaining_side_name == 'encoder' else decoder_shape for _ in range(lowerCAmelCase_ , lowerCAmelCase_ ): common_inputs["past_key_values"].append((torch.zeros(lowerCAmelCase_ ), torch.zeros(lowerCAmelCase_ )) ) return common_inputs def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = -1 , lowerCAmelCase_ = -1 , lowerCAmelCase_ = False , lowerCAmelCase_ = None , ): """simple docstring""" _snake_case = self._generate_dummy_inputs_for_encoder_and_decoder( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch _snake_case , _snake_case = common_inputs['input_ids'].shape # Not using the same length for past_key_values _snake_case = seqlen + 2 _snake_case , _snake_case = self.num_layers _snake_case , _snake_case = self.num_attention_heads _snake_case = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) _snake_case = common_inputs['attention_mask'].dtype _snake_case = torch.cat( [common_inputs['attention_mask'], torch.ones(lowerCAmelCase_ , lowerCAmelCase_ , dtype=lowerCAmelCase_ )] , dim=1 ) _snake_case = [ (torch.zeros(lowerCAmelCase_ ), torch.zeros(lowerCAmelCase_ )) for _ in range(lowerCAmelCase_ ) ] return common_inputs def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = -1 , lowerCAmelCase_ = -1 , lowerCAmelCase_ = False , lowerCAmelCase_ = None , ): """simple docstring""" _snake_case = compute_effective_axis_dimension( lowerCAmelCase_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX _snake_case = tokenizer.num_special_tokens_to_add(lowerCAmelCase_ ) _snake_case = compute_effective_axis_dimension( lowerCAmelCase_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCAmelCase_ ) # Generate dummy inputs according to compute batch and sequence _snake_case = [' '.join([tokenizer.unk_token] ) * seq_length] * batch_size _snake_case = dict(tokenizer(lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) ) return common_inputs def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = -1 , lowerCAmelCase_ = -1 , lowerCAmelCase_ = False , lowerCAmelCase_ = None , ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: _snake_case = self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowerCAmelCase_ , batch_size=lowerCAmelCase_ , seq_length=lowerCAmelCase_ , is_pair=lowerCAmelCase_ , framework=lowerCAmelCase_ ) else: _snake_case = self._generate_dummy_inputs_for_causal_lm( lowerCAmelCase_ , batch_size=lowerCAmelCase_ , seq_length=lowerCAmelCase_ , is_pair=lowerCAmelCase_ , framework=lowerCAmelCase_ ) return common_inputs def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: _snake_case = super()._flatten_past_key_values_(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) else: _snake_case = super(lowerCAmelCase_ , self )._flatten_past_key_values_( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) @property def lowerCamelCase ( self ): """simple docstring""" return 1E-4
160
1
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) a_ = 'hf-internal-testing/tiny-random-bert' a_ = os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert') a_ = '9b8c223d42b2188cb49d29af482996f9d0f3e5a6' class UpperCAmelCase_ ( unittest.TestCase ): def _lowerCamelCase ( self ) -> List[str]: __lowercase : int = cached_file(UpperCamelCase_ , UpperCamelCase_ ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(UpperCamelCase_ ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(UpperCamelCase_ , UpperCamelCase_ ) ) ) with open(os.path.join(UpperCamelCase_ , '''refs''' , '''main''' ) ) as f: __lowercase : Union[str, Any] = f.read() self.assertEqual(UpperCamelCase_ , os.path.join(UpperCamelCase_ , '''snapshots''' , UpperCamelCase_ , UpperCamelCase_ ) ) self.assertTrue(os.path.isfile(UpperCamelCase_ ) ) # File is cached at the same place the second time. __lowercase : Optional[int] = cached_file(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) # Using a specific revision to test the full commit hash. __lowercase : Union[str, Any] = cached_file(UpperCamelCase_ , UpperCamelCase_ , revision='''9b8c223''' ) self.assertEqual(UpperCamelCase_ , os.path.join(UpperCamelCase_ , '''snapshots''' , UpperCamelCase_ , UpperCamelCase_ ) ) def _lowerCamelCase ( self ) -> Dict: with self.assertRaisesRegex(UpperCamelCase_ , '''is not a valid model identifier''' ): __lowercase : List[str] = cached_file('''tiny-random-bert''' , UpperCamelCase_ ) with self.assertRaisesRegex(UpperCamelCase_ , '''is not a valid git identifier''' ): __lowercase : Any = cached_file(UpperCamelCase_ , UpperCamelCase_ , revision='''aaaa''' ) with self.assertRaisesRegex(UpperCamelCase_ , '''does not appear to have a file named''' ): __lowercase : Dict = cached_file(UpperCamelCase_ , '''conf''' ) def _lowerCamelCase ( self ) -> Optional[int]: with self.assertRaisesRegex(UpperCamelCase_ , '''does not appear to have a file named''' ): __lowercase : Optional[int] = cached_file(UpperCamelCase_ , '''conf''' ) with open(os.path.join(UpperCamelCase_ , '''refs''' , '''main''' ) ) as f: __lowercase : Any = f.read() self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase_ , '''.no_exist''' , UpperCamelCase_ , '''conf''' ) ) ) __lowercase : Tuple = cached_file(UpperCamelCase_ , '''conf''' , _raise_exceptions_for_missing_entries=UpperCamelCase_ ) self.assertIsNone(UpperCamelCase_ ) __lowercase : List[Any] = cached_file(UpperCamelCase_ , '''conf''' , local_files_only=UpperCamelCase_ , _raise_exceptions_for_missing_entries=UpperCamelCase_ ) self.assertIsNone(UpperCamelCase_ ) __lowercase : Union[str, Any] = mock.Mock() __lowercase : List[str] = 5_00 __lowercase : Optional[int] = {} __lowercase : Any = HTTPError __lowercase : Tuple = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=UpperCamelCase_ ) as mock_head: __lowercase : Optional[Any] = cached_file(UpperCamelCase_ , '''conf''' , _raise_exceptions_for_connection_errors=UpperCamelCase_ ) self.assertIsNone(UpperCamelCase_ ) # This check we did call the fake head request mock_head.assert_called() def _lowerCamelCase ( self ) -> List[Any]: self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , UpperCamelCase_ ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , UpperCamelCase_ ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , UpperCamelCase_ ) ) def _lowerCamelCase ( self ) -> Dict: # `get_file_from_repo` returns None if the file does not exist self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(UpperCamelCase_ , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , UpperCamelCase_ ) # The function raises if the revision does not exist. with self.assertRaisesRegex(UpperCamelCase_ , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , UpperCamelCase_ , revision='''ahaha''' ) __lowercase : str = get_file_from_repo('''bert-base-cased''' , UpperCamelCase_ ) # The name is the cached name which is not very easy to test, so instead we load the content. __lowercase : Dict = json.loads(open(UpperCamelCase_ , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_68 ) def _lowerCamelCase ( self ) -> Any: with tempfile.TemporaryDirectory() as tmp_dir: __lowercase : List[Any] = Path(UpperCamelCase_ ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(UpperCamelCase_ , '''a.txt''' ) , str(UpperCamelCase_ ) ) self.assertIsNone(get_file_from_repo(UpperCamelCase_ , '''b.txt''' ) )
249
"""simple docstring""" import math def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): if initial_intensity < 0: raise ValueError('''The value of intensity cannot be negative''' ) # handling of negative values of initial intensity if angle < 0 or angle > 3_60: raise ValueError('''In Malus Law, the angle is in the range 0-360 degrees''' ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(__UpperCamelCase ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='malus_law')
249
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase_ = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
355
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { '''shi-labs/dinat-mini-in1k-224''': '''https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json''', # See all Dinat models at https://huggingface.co/models?filter=dinat } class _snake_case ( __snake_case , __snake_case ): '''simple docstring''' A__ : Optional[Any] = "dinat" A__ : Any = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self: Any ,lowerCamelCase_: Any=4 ,lowerCamelCase_: Union[str, Any]=3 ,lowerCamelCase_: Union[str, Any]=64 ,lowerCamelCase_: Optional[int]=[3, 4, 6, 5] ,lowerCamelCase_: int=[2, 4, 8, 16] ,lowerCamelCase_: Optional[int]=7 ,lowerCamelCase_: Dict=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] ,lowerCamelCase_: Tuple=3.0 ,lowerCamelCase_: Any=True ,lowerCamelCase_: int=0.0 ,lowerCamelCase_: Optional[Any]=0.0 ,lowerCamelCase_: Optional[int]=0.1 ,lowerCamelCase_: Optional[int]="gelu" ,lowerCamelCase_: Optional[Any]=0.0_2 ,lowerCamelCase_: List[Any]=1e-5 ,lowerCamelCase_: int=0.0 ,lowerCamelCase_: int=None ,lowerCamelCase_: str=None ,**lowerCamelCase_: Dict ,) -> Union[str, Any]: super().__init__(**lowerCamelCase_ ) UpperCAmelCase_ : List[str] = patch_size UpperCAmelCase_ : Tuple = num_channels UpperCAmelCase_ : Union[str, Any] = embed_dim UpperCAmelCase_ : int = depths UpperCAmelCase_ : List[Any] = len(lowerCamelCase_ ) UpperCAmelCase_ : Union[str, Any] = num_heads UpperCAmelCase_ : Tuple = kernel_size UpperCAmelCase_ : int = dilations UpperCAmelCase_ : Optional[Any] = mlp_ratio UpperCAmelCase_ : Optional[Any] = qkv_bias UpperCAmelCase_ : List[Any] = hidden_dropout_prob UpperCAmelCase_ : List[str] = attention_probs_dropout_prob UpperCAmelCase_ : Tuple = drop_path_rate UpperCAmelCase_ : List[str] = hidden_act UpperCAmelCase_ : Any = layer_norm_eps UpperCAmelCase_ : List[str] = initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model UpperCAmelCase_ : List[Any] = int(embed_dim * 2 ** (len(lowerCamelCase_ ) - 1) ) UpperCAmelCase_ : Optional[int] = layer_scale_init_value UpperCAmelCase_ : List[Any] = ["""stem"""] + [F'''stage{idx}''' for idx in range(1 ,len(lowerCamelCase_ ) + 1 )] UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = get_aligned_output_features_output_indices( out_features=lowerCamelCase_ ,out_indices=lowerCamelCase_ ,stage_names=self.stage_names )
59
0
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=a ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :str = field(default="""question-answering-extractive""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) __magic_name__ :ClassVar[Features] = Features({"""question""": Value("""string""" ), """context""": Value("""string""" )} ) __magic_name__ :ClassVar[Features] = Features( { """answers""": Sequence( { """text""": Value("""string""" ), """answer_start""": Value("""int32""" ), } ) } ) __magic_name__ :str = "question" __magic_name__ :str = "context" __magic_name__ :str = "answers" @property def snake_case ( self ): '''simple docstring''' return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
293
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __A = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __A = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __A = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
293
1
'''simple docstring''' from manim import * class UpperCAmelCase__ ( UpperCAmelCase_): def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = Rectangle(height=0.5 , width=0.5 ) __UpperCamelCase = Rectangle(height=0.25 , width=0.25 ) __UpperCamelCase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __UpperCamelCase = [mem.copy() for i in range(6 )] __UpperCamelCase = [mem.copy() for i in range(6 )] __UpperCamelCase = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = VGroup(lowercase , lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = Text("""CPU""" , font_size=2_4 ) __UpperCamelCase = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowercase ) __UpperCamelCase = [mem.copy() for i in range(4 )] __UpperCamelCase = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = Text("""GPU""" , font_size=2_4 ) __UpperCamelCase = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) gpu.move_to([-1, -1, 0] ) self.add(lowercase ) __UpperCamelCase = [mem.copy() for i in range(6 )] __UpperCamelCase = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = Text("""Model""" , font_size=2_4 ) __UpperCamelCase = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) model.move_to([3, -1.0, 0] ) self.add(lowercase ) __UpperCamelCase = [] __UpperCamelCase = [] __UpperCamelCase = [] for i, rect in enumerate(lowercase ): rect.set_stroke(lowercase ) __UpperCamelCase = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(lowercase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=lowercase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=lowercase , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=lowercase , buff=0.0 ) self.add(lowercase ) model_cpu_arr.append(lowercase ) self.add(*lowercase , *lowercase , *lowercase ) __UpperCamelCase = [mem.copy() for i in range(6 )] __UpperCamelCase = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = Text("""Loaded Checkpoint""" , font_size=2_4 ) __UpperCamelCase = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) checkpoint.move_to([3, 0.5, 0] ) self.add(lowercase ) __UpperCamelCase = [] __UpperCamelCase = [] for i, rect in enumerate(lowercase ): __UpperCamelCase = fill.copy().set_fill(lowercase , opacity=0.7 ) target.move_to(lowercase ) ckpt_arr.append(lowercase ) __UpperCamelCase = 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(lowercase ) self.add(*lowercase , *lowercase ) __UpperCamelCase = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __UpperCamelCase = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=1_8 , ) key_text.move_to([-5, 2.4, 0] ) self.add(lowercase , lowercase ) __UpperCamelCase = MarkupText( f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=1_8 , ) blue_text.next_to(lowercase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(lowercase ) __UpperCamelCase = 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=2_4 , ) step_a.move_to([2, 2, 0] ) __UpperCamelCase = [meta_mem.copy() for i in range(6 )] __UpperCamelCase = [meta_mem.copy() for i in range(6 )] __UpperCamelCase = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = VGroup(lowercase , lowercase ).arrange(lowercase , buff=0 ) __UpperCamelCase = Text("""Disk""" , font_size=2_4 ) __UpperCamelCase = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(lowercase , run_time=3 ) , Write(lowercase , run_time=1 ) , Create(lowercase , run_time=1 ) ) __UpperCamelCase = [] for i, rect in enumerate(lowercase ): __UpperCamelCase = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(lowercase , run_time=1.5 ) ) self.play(*lowercase ) self.play(FadeOut(lowercase ) ) __UpperCamelCase = MarkupText(f"Then, the checkpoint is removed from memory\nthrough garbage collection." , font_size=2_4 ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase , run_time=3 ) ) self.play( FadeOut(lowercase , lowercase , *lowercase , *lowercase ) , ) self.wait()
353
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _lowercase ( *__A ): '''simple docstring''' if not isinstance(__A ,__A ): __UpperCamelCase = list(__A ) for i in range(len(__A ) ): __UpperCamelCase = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = [ """CUDA out of memory.""", # CUDA OOM """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""", # CUDNN SNAFU """DefaultCPUAllocator: can't allocate memory""", # CPU OOM ] if isinstance(__A ,__A ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def _lowercase ( __A = None ,__A = 128 ): '''simple docstring''' if function is None: return functools.partial(__A ,starting_batch_size=__A ) __UpperCamelCase = starting_batch_size def decorator(*__A ,**__A ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() __UpperCamelCase = list(inspect.signature(__A ).parameters.keys() ) # Guard against user error if len(__A ) < (len(__A ) + 1): __UpperCamelCase = """, """.join([f"{arg}={value}" for arg, value in zip(params[1:] ,args[1:] )] ) raise TypeError( f"Batch size was passed into `{function.__name__}` as the first argument when called." f"Remove this as the decorator already does so: `{function.__name__}({arg_str})`" ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(__A ,*__A ,**__A ) except Exception as e: if should_reduce_batch_size(__A ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
243
0
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError("iterations must be defined as integers" ) if not isinstance(_UpperCamelCase , _UpperCamelCase ) or not number >= 1: raise ValueError( "starting number must be\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) __lowerCAmelCase = "" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(_UpperCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
57
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path UpperCamelCase : str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) UpperCamelCase : list[int] = [ord(letter) for letter in string.ascii_lowercase] UpperCamelCase : set[int] = {ord(char) for char in VALID_CHARS} UpperCamelCase : list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"] def A ( snake_case :list[int] , snake_case :tuple[int, ...] ) -> str | None: __UpperCamelCase = "" __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = 42 for keychar, cipherchar in zip(cycle(snake_case ) , snake_case ): __UpperCamelCase = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(snake_case ) return decoded def A ( snake_case :list[int] ) -> list[str]: __UpperCamelCase = [] for key in product(snake_case , repeat=3 ): __UpperCamelCase = try_key(snake_case , snake_case ) if encoded is not None: possibles.append(snake_case ) return possibles def A ( snake_case :list[str] , snake_case :str ) -> list[str]: return [possible for possible in possibles if common_word in possible.lower()] def A ( snake_case :str = "p059_cipher.txt" ) -> int: __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = Path(snake_case ).parent.joinpath(snake_case ).read_text(encoding='utf-8' ) __UpperCamelCase = [int(snake_case ) for number in data.strip().split(',' )] __UpperCamelCase = filter_valid_chars(snake_case ) for common_word in COMMON_WORDS: __UpperCamelCase = filter_common_word(snake_case , snake_case ) if len(snake_case ) == 1: break __UpperCamelCase = possibles[0] return sum(ord(snake_case ) for char in decoded_text ) if __name__ == "__main__": print(f'''{solution() = }''')
316
0
import math from datetime import datetime, timedelta def lowerCAmelCase__ ( lowerCamelCase_ : int): '''simple docstring''' lowerCAmelCase__ : Any = year % 19 lowerCAmelCase__ : List[str] = year % 4 lowerCAmelCase__ : int = year % 7 lowerCAmelCase__ : Tuple = math.floor(year / 100) lowerCAmelCase__ : Optional[Any] = math.floor((13 + 8 * leap_day_inhibits) / 25) lowerCAmelCase__ : List[str] = leap_day_inhibits / 4 lowerCAmelCase__ : Dict = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 lowerCAmelCase__ : List[str] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 lowerCAmelCase__ : Optional[Any] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon lowerCAmelCase__ : List[Any] = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ ,4 ,19) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(lowerCamelCase_ ,4 ,18) else: return datetime(lowerCamelCase_ ,3 ,22) + timedelta( days=int(days_to_add + days_from_phm_to_sunday)) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): __snake_case : Optional[int] ='will be' if year > datetime.now().year else 'was' print(f"""Easter in {year} {tense} {gauss_easter(year)}""")
371
def lowerCAmelCase__ ( lowerCamelCase_ : str = "The quick brown fox jumps over the lazy dog" ,): '''simple docstring''' lowerCAmelCase__ : Any = set() # Replace all the whitespace in our sentence lowerCAmelCase__ : List[Any] = input_str.replace(''' ''' ,'''''') for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(lowerCamelCase_) == 26 def lowerCAmelCase__ ( lowerCamelCase_ : str = "The quick brown fox jumps over the lazy dog" ,): '''simple docstring''' lowerCAmelCase__ : List[str] = [False] * 26 for char in input_str: if char.islower(): lowerCAmelCase__ : Union[str, Any] = True elif char.isupper(): lowerCAmelCase__ : str = True return all(lowerCamelCase_) def lowerCAmelCase__ ( lowerCamelCase_ : str = "The quick brown fox jumps over the lazy dog" ,): '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()}) == 26 def lowerCAmelCase__ ( ): '''simple docstring''' from timeit import timeit lowerCAmelCase__ : Optional[Any] = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' ,setup=lowerCamelCase_)) print(timeit('''is_pangram_faster()''' ,setup=lowerCamelCase_)) print(timeit('''is_pangram_fastest()''' ,setup=lowerCamelCase_)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
94
0
"""simple docstring""" import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Any: lowerCAmelCase_ :Union[str, Any] = torch.nn.Linear(10 , 10 ) lowerCAmelCase_ :List[Any] = torch.optim.SGD(model.parameters() , 0.1 ) lowerCAmelCase_ :Tuple = Accelerator() lowerCAmelCase_ :Any = accelerator.prepare(__A ) try: pickle.loads(pickle.dumps(__A ) ) except Exception as e: self.fail(f"""Accelerated optimizer pickling failed with {e}""" ) AcceleratorState._reset_state()
84
"""simple docstring""" def _snake_case ( lowercase__ : int = 1_0 ) -> str: '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or n < 0: raise ValueError("""Invalid input""" ) lowerCAmelCase_ :List[str] = 1_0**n lowerCAmelCase_ :int = 2_8_4_3_3 * (pow(2 , 7_8_3_0_4_5_7 , lowercase__ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(10) = }""")
84
1
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class lowerCAmelCase ( lowercase_ ): __lowerCamelCase = 'autoformer' __lowerCamelCase = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self :str , _lowercase :Optional[int] = None , _lowercase :Optional[int] = None , _lowercase :str = "student_t" , _lowercase :str = "nll" , _lowercase :int = 1 , _lowercase :List[int] = [1, 2, 3, 4, 5, 6, 7] , _lowercase :bool = True , _lowercase :int = 0 , _lowercase :int = 0 , _lowercase :int = 0 , _lowercase :int = 0 , _lowercase :Optional[List[int]] = None , _lowercase :Optional[List[int]] = None , _lowercase :int = 64 , _lowercase :int = 2 , _lowercase :int = 2 , _lowercase :int = 2 , _lowercase :int = 2 , _lowercase :int = 32 , _lowercase :int = 32 , _lowercase :str = "gelu" , _lowercase :float = 0.1 , _lowercase :float = 0.1 , _lowercase :float = 0.1 , _lowercase :float = 0.1 , _lowercase :float = 0.1 , _lowercase :int = 1_00 , _lowercase :float = 0.02 , _lowercase :bool = True , _lowercase :Tuple=True , _lowercase :int = 10 , _lowercase :int = 25 , _lowercase :int = 3 , **_lowercase :Tuple , ): '''simple docstring''' lowercase__ = prediction_length lowercase__ = context_length if context_length is not None else prediction_length lowercase__ = distribution_output lowercase__ = loss lowercase__ = input_size lowercase__ = num_time_features lowercase__ = lags_sequence lowercase__ = scaling lowercase__ = num_dynamic_real_features lowercase__ = num_static_real_features lowercase__ = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(_lowercase ) != num_static_categorical_features: raise ValueError( "The cardinality should be a list of the same length as `num_static_categorical_features`" ) lowercase__ = cardinality else: lowercase__ = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(_lowercase ) != num_static_categorical_features: raise ValueError( "The embedding dimension should be a list of the same length as `num_static_categorical_features`" ) lowercase__ = embedding_dimension else: lowercase__ = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] lowercase__ = num_parallel_samples # Transformer architecture configuration lowercase__ = input_size * len(self.lags_sequence ) + self._number_of_features lowercase__ = d_model lowercase__ = encoder_attention_heads lowercase__ = decoder_attention_heads lowercase__ = encoder_ffn_dim lowercase__ = decoder_ffn_dim lowercase__ = encoder_layers lowercase__ = decoder_layers lowercase__ = dropout lowercase__ = attention_dropout lowercase__ = activation_dropout lowercase__ = encoder_layerdrop lowercase__ = decoder_layerdrop lowercase__ = activation_function lowercase__ = init_std lowercase__ = use_cache # Autoformer lowercase__ = label_length lowercase__ = moving_average lowercase__ = autocorrelation_factor super().__init__(is_encoder_decoder=_lowercase , **_lowercase ) @property def UpperCAmelCase ( self :Optional[int] ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
201
from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class lowerCAmelCase ( yaml.SafeLoader ): def UpperCAmelCase ( self :Optional[Any] , _lowercase :Any ): '''simple docstring''' lowercase__ = [self.constructed_objects[key_node] for key_node, _ in node.value] lowercase__ = [tuple(_lowercase ) if isinstance(_lowercase , _lowercase ) else key for key in keys] lowercase__ = Counter(_lowercase ) lowercase__ = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def UpperCAmelCase ( self :Any , _lowercase :str , _lowercase :Dict=False ): '''simple docstring''' lowercase__ = super().construct_mapping(_lowercase , deep=_lowercase ) self._check_no_duplicates_on_constructed_node(_lowercase ) return mapping def _A ( __magic_name__ ): lowercase__ = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowercase__ = full_content[1:].index("---" ) + 1 lowercase__ = "\n".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(__magic_name__ ) class lowerCAmelCase ( lowercase_ ): # class attributes __lowerCamelCase = {'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def UpperCAmelCase ( cls :Dict , _lowercase :Path ): '''simple docstring''' with open(_lowercase , encoding="utf-8" ) as readme_file: lowercase__ , lowercase__ = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(_lowercase ) else: return cls() def UpperCAmelCase ( self :Any , _lowercase :Path ): '''simple docstring''' if path.exists(): with open(_lowercase , encoding="utf-8" ) as readme_file: lowercase__ = readme_file.read() else: lowercase__ = None lowercase__ = self._to_readme(_lowercase ) with open(_lowercase , "w" , encoding="utf-8" ) as readme_file: readme_file.write(_lowercase ) def UpperCAmelCase ( self :List[str] , _lowercase :Optional[str] = None ): '''simple docstring''' if readme_content is not None: lowercase__ , lowercase__ = _split_yaml_from_readme(_lowercase ) lowercase__ = "---\n" + self.to_yaml_string() + "---\n" + content else: lowercase__ = "---\n" + self.to_yaml_string() + "---\n" return full_content @classmethod def UpperCAmelCase ( cls :Any , _lowercase :str ): '''simple docstring''' lowercase__ = yaml.load(_lowercase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowercase__ = { (key.replace("-" , "_" ) if key.replace("-" , "_" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**_lowercase ) def UpperCAmelCase ( self :Union[str, Any] ): '''simple docstring''' return yaml.safe_dump( { (key.replace("_" , "-" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=_lowercase , allow_unicode=_lowercase , encoding="utf-8" , ).decode("utf-8" ) _snake_case = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser _snake_case = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") _snake_case = ap.parse_args() _snake_case = Path(args.readme_filepath) _snake_case = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
201
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) A ={ 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =[ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =[ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A =['LayoutLMv3FeatureExtractor'] A =['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys A =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
34
'''simple docstring''' import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() A =logging.get_logger(__name__) A ={ 'b0': efficientnet.EfficientNetBa, 'b1': efficientnet.EfficientNetBa, 'b2': efficientnet.EfficientNetBa, 'b3': efficientnet.EfficientNetBa, 'b4': efficientnet.EfficientNetBa, 'b5': efficientnet.EfficientNetBa, 'b6': efficientnet.EfficientNetBa, 'b7': efficientnet.EfficientNetBa, } A ={ 'b0': { 'hidden_dim': 12_80, 'width_coef': 1.0, 'depth_coef': 1.0, 'image_size': 2_24, 'dropout_rate': 0.2, 'dw_padding': [], }, 'b1': { 'hidden_dim': 12_80, 'width_coef': 1.0, 'depth_coef': 1.1, 'image_size': 2_40, 'dropout_rate': 0.2, 'dw_padding': [16], }, 'b2': { 'hidden_dim': 14_08, 'width_coef': 1.1, 'depth_coef': 1.2, 'image_size': 2_60, 'dropout_rate': 0.3, 'dw_padding': [5, 8, 16], }, 'b3': { 'hidden_dim': 15_36, 'width_coef': 1.2, 'depth_coef': 1.4, 'image_size': 3_00, 'dropout_rate': 0.3, 'dw_padding': [5, 18], }, 'b4': { 'hidden_dim': 17_92, 'width_coef': 1.4, 'depth_coef': 1.8, 'image_size': 3_80, 'dropout_rate': 0.4, 'dw_padding': [6], }, 'b5': { 'hidden_dim': 20_48, 'width_coef': 1.6, 'depth_coef': 2.2, 'image_size': 4_56, 'dropout_rate': 0.4, 'dw_padding': [13, 27], }, 'b6': { 'hidden_dim': 23_04, 'width_coef': 1.8, 'depth_coef': 2.6, 'image_size': 5_28, 'dropout_rate': 0.5, 'dw_padding': [31], }, 'b7': { 'hidden_dim': 25_60, 'width_coef': 2.0, 'depth_coef': 3.1, 'image_size': 6_00, 'dropout_rate': 0.5, 'dw_padding': [18], }, } def snake_case_ (_a : List[str] ): UpperCAmelCase = EfficientNetConfig() UpperCAmelCase = CONFIG_MAP[model_name]['''hidden_dim'''] UpperCAmelCase = CONFIG_MAP[model_name]['''width_coef'''] UpperCAmelCase = CONFIG_MAP[model_name]['''depth_coef'''] UpperCAmelCase = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase = CONFIG_MAP[model_name]['''dropout_rate'''] UpperCAmelCase = CONFIG_MAP[model_name]['''dw_padding'''] UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = '''imagenet-1k-id2label.json''' UpperCAmelCase = 1_0_0_0 UpperCAmelCase = json.load(open(hf_hub_download(_a , _a , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase = {int(_a ): v for k, v in idalabel.items()} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def snake_case_ (): UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase = Image.open(requests.get(_a , stream=_a ).raw ) return im def snake_case_ (_a : str ): UpperCAmelCase = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase = EfficientNetImageProcessor( size={'''height''': size, '''width''': size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.4785_3944, 0.473_2864, 0.4743_4163] , do_center_crop=_a , ) return preprocessor def snake_case_ (_a : Optional[Any] ): UpperCAmelCase = [v.split('''_''' )[0].split('''block''' )[1] for v in original_param_names if v.startswith('''block''' )] UpperCAmelCase = sorted(set(_a ) ) UpperCAmelCase = len(_a ) UpperCAmelCase = {b: str(_a ) for b, i in zip(_a , range(_a ) )} UpperCAmelCase = [] rename_keys.append(('''stem_conv/kernel:0''', '''embeddings.convolution.weight''') ) rename_keys.append(('''stem_bn/gamma:0''', '''embeddings.batchnorm.weight''') ) rename_keys.append(('''stem_bn/beta:0''', '''embeddings.batchnorm.bias''') ) rename_keys.append(('''stem_bn/moving_mean:0''', '''embeddings.batchnorm.running_mean''') ) rename_keys.append(('''stem_bn/moving_variance:0''', '''embeddings.batchnorm.running_var''') ) for b in block_names: UpperCAmelCase = block_name_mapping[b] rename_keys.append((F"block{b}_expand_conv/kernel:0", F"encoder.blocks.{hf_b}.expansion.expand_conv.weight") ) rename_keys.append((F"block{b}_expand_bn/gamma:0", F"encoder.blocks.{hf_b}.expansion.expand_bn.weight") ) rename_keys.append((F"block{b}_expand_bn/beta:0", F"encoder.blocks.{hf_b}.expansion.expand_bn.bias") ) rename_keys.append( (F"block{b}_expand_bn/moving_mean:0", F"encoder.blocks.{hf_b}.expansion.expand_bn.running_mean") ) rename_keys.append( (F"block{b}_expand_bn/moving_variance:0", F"encoder.blocks.{hf_b}.expansion.expand_bn.running_var") ) rename_keys.append( (F"block{b}_dwconv/depthwise_kernel:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight") ) rename_keys.append((F"block{b}_bn/gamma:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight") ) rename_keys.append((F"block{b}_bn/beta:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias") ) rename_keys.append( (F"block{b}_bn/moving_mean:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean") ) rename_keys.append( (F"block{b}_bn/moving_variance:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var") ) rename_keys.append((F"block{b}_se_reduce/kernel:0", F"encoder.blocks.{hf_b}.squeeze_excite.reduce.weight") ) rename_keys.append((F"block{b}_se_reduce/bias:0", F"encoder.blocks.{hf_b}.squeeze_excite.reduce.bias") ) rename_keys.append((F"block{b}_se_expand/kernel:0", F"encoder.blocks.{hf_b}.squeeze_excite.expand.weight") ) rename_keys.append((F"block{b}_se_expand/bias:0", F"encoder.blocks.{hf_b}.squeeze_excite.expand.bias") ) rename_keys.append( (F"block{b}_project_conv/kernel:0", F"encoder.blocks.{hf_b}.projection.project_conv.weight") ) rename_keys.append((F"block{b}_project_bn/gamma:0", F"encoder.blocks.{hf_b}.projection.project_bn.weight") ) rename_keys.append((F"block{b}_project_bn/beta:0", F"encoder.blocks.{hf_b}.projection.project_bn.bias") ) rename_keys.append( (F"block{b}_project_bn/moving_mean:0", F"encoder.blocks.{hf_b}.projection.project_bn.running_mean") ) rename_keys.append( (F"block{b}_project_bn/moving_variance:0", F"encoder.blocks.{hf_b}.projection.project_bn.running_var") ) rename_keys.append(('''top_conv/kernel:0''', '''encoder.top_conv.weight''') ) rename_keys.append(('''top_bn/gamma:0''', '''encoder.top_bn.weight''') ) rename_keys.append(('''top_bn/beta:0''', '''encoder.top_bn.bias''') ) rename_keys.append(('''top_bn/moving_mean:0''', '''encoder.top_bn.running_mean''') ) rename_keys.append(('''top_bn/moving_variance:0''', '''encoder.top_bn.running_var''') ) UpperCAmelCase = {} for item in rename_keys: if item[0] in original_param_names: UpperCAmelCase = '''efficientnet.''' + item[1] UpperCAmelCase = '''classifier.weight''' UpperCAmelCase = '''classifier.bias''' return key_mapping def snake_case_ (_a : Dict , _a : List[str] , _a : Dict ): for key, value in tf_params.items(): if "normalization" in key: continue UpperCAmelCase = key_mapping[key] if "_conv" in key and "kernel" in key: UpperCAmelCase = torch.from_numpy(_a ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: UpperCAmelCase = torch.from_numpy(_a ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: UpperCAmelCase = torch.from_numpy(np.transpose(_a ) ) else: UpperCAmelCase = torch.from_numpy(_a ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(_a ) @torch.no_grad() def snake_case_ (_a : Optional[Any] , _a : List[str] , _a : Optional[int] , _a : Dict ): UpperCAmelCase = model_classes[model_name]( include_top=_a , weights='''imagenet''' , input_tensor=_a , input_shape=_a , pooling=_a , classes=1_0_0_0 , classifier_activation='''softmax''' , ) UpperCAmelCase = original_model.trainable_variables UpperCAmelCase = original_model.non_trainable_variables UpperCAmelCase = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: UpperCAmelCase = param.numpy() UpperCAmelCase = list(tf_params.keys() ) # Load HuggingFace model UpperCAmelCase = get_efficientnet_config(_a ) UpperCAmelCase = EfficientNetForImageClassification(_a ).eval() UpperCAmelCase = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print('''Converting parameters...''' ) UpperCAmelCase = rename_keys(_a ) replace_params(_a , _a , _a ) # Initialize preprocessor and preprocess input image UpperCAmelCase = convert_image_processor(_a ) UpperCAmelCase = preprocessor(images=prepare_img() , return_tensors='''pt''' ) # HF model inference hf_model.eval() with torch.no_grad(): UpperCAmelCase = hf_model(**_a ) UpperCAmelCase = outputs.logits.detach().numpy() # Original model inference UpperCAmelCase = False UpperCAmelCase = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) UpperCAmelCase = image.img_to_array(_a ) UpperCAmelCase = np.expand_dims(_a , axis=0 ) UpperCAmelCase = original_model.predict(_a ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(_a , _a , atol=1E-3 ), "The predicted logits are not the same." print('''Model outputs match!''' ) if save_model: # Create folder to save model if not os.path.isdir(_a ): os.mkdir(_a ) # Save converted model and image processor hf_model.save_pretrained(_a ) preprocessor.save_pretrained(_a ) if push_to_hub: # Push model and image processor to hub print(F"Pushing converted {model_name} to the hub..." ) UpperCAmelCase = F"efficientnet-{model_name}" preprocessor.push_to_hub(_a ) hf_model.push_to_hub(_a ) if __name__ == "__main__": A =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='b0', type=str, help='Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].', ) parser.add_argument( '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--save_model', action='store_true', help='Save model to local') parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') A =parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
34
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _lowerCAmelCase ( unittest.TestCase ): @property def _a (self ): torch.manual_seed(0 ) A_ : List[str] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def _a (self ): A_ : Tuple = self.dummy_uncond_unet A_ : Any = PNDMScheduler() A_ : List[str] = PNDMPipeline(unet=lowercase , scheduler=lowercase ) pndm.to(lowercase ) pndm.set_progress_bar_config(disable=lowercase ) A_ : List[Any] = torch.manual_seed(0 ) A_ : int = pndm(generator=lowercase , num_inference_steps=20 , output_type="""numpy""" ).images A_ : Tuple = torch.manual_seed(0 ) A_ : Any = pndm(generator=lowercase , num_inference_steps=20 , output_type="""numpy""" , return_dict=lowercase )[0] A_ : Optional[int] = image[0, -3:, -3:, -1] A_ : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A_ : List[str] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class _lowerCAmelCase ( unittest.TestCase ): def _a (self ): A_ : Union[str, Any] = """google/ddpm-cifar10-32""" A_ : List[Any] = UNetaDModel.from_pretrained(lowercase ) A_ : Union[str, Any] = PNDMScheduler() A_ : Union[str, Any] = PNDMPipeline(unet=lowercase , scheduler=lowercase ) pndm.to(lowercase ) pndm.set_progress_bar_config(disable=lowercase ) A_ : List[str] = torch.manual_seed(0 ) A_ : List[str] = pndm(generator=lowercase , output_type="""numpy""" ).images A_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A_ : List[str] = np.array([0.15_64, 0.1_46_45, 0.14_06, 0.1_47_15, 0.1_24_25, 0.1_40_45, 0.1_31_15, 0.1_21_75, 0.1_25] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
357
'''simple docstring''' lowerCamelCase :Any = { '''A''': '''.-''', '''B''': '''-...''', '''C''': '''-.-.''', '''D''': '''-..''', '''E''': '''.''', '''F''': '''..-.''', '''G''': '''--.''', '''H''': '''....''', '''I''': '''..''', '''J''': '''.---''', '''K''': '''-.-''', '''L''': '''.-..''', '''M''': '''--''', '''N''': '''-.''', '''O''': '''---''', '''P''': '''.--.''', '''Q''': '''--.-''', '''R''': '''.-.''', '''S''': '''...''', '''T''': '''-''', '''U''': '''..-''', '''V''': '''...-''', '''W''': '''.--''', '''X''': '''-..-''', '''Y''': '''-.--''', '''Z''': '''--..''', '''1''': '''.----''', '''2''': '''..---''', '''3''': '''...--''', '''4''': '''....-''', '''5''': '''.....''', '''6''': '''-....''', '''7''': '''--...''', '''8''': '''---..''', '''9''': '''----.''', '''0''': '''-----''', '''&''': '''.-...''', '''@''': '''.--.-.''', ''':''': '''---...''', ''',''': '''--..--''', '''.''': '''.-.-.-''', '''\'''': '''.----.''', '''"''': '''.-..-.''', '''?''': '''..--..''', '''/''': '''-..-.''', '''=''': '''-...-''', '''+''': '''.-.-.''', '''-''': '''-....-''', '''(''': '''-.--.''', ''')''': '''-.--.-''', '''!''': '''-.-.--''', ''' ''': '''/''' } # Exclamation mark is not in ITU-R recommendation # fmt: on lowerCamelCase :Any = {value: key for key, value in MORSE_CODE_DICT.items()} def a ( lowerCamelCase__ ): '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def a ( lowerCamelCase__ ): '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def a ( ): '''simple docstring''' A_ : List[str] = """Morse code here!""" print(lowerCamelCase__ ) A_ : str = encrypt(lowerCamelCase__ ) print(lowerCamelCase__ ) A_ : Dict = decrypt(lowerCamelCase__ ) print(lowerCamelCase__ ) if __name__ == "__main__": main()
135
0
"""simple docstring""" from __future__ import annotations snake_case_ = list[tuple[int, int]] snake_case_ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] snake_case_ = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A_ : """simple docstring""" def __init__( self :Optional[int] , lowercase_ :int , lowercase_ :int , lowercase_ :int , lowercase_ :int , lowercase_ :float , lowercase_ :Node | None , ) -> Dict: UpperCAmelCase = pos_x UpperCAmelCase = pos_y UpperCAmelCase = (pos_y, pos_x) UpperCAmelCase = goal_x UpperCAmelCase = goal_y UpperCAmelCase = g_cost UpperCAmelCase = parent UpperCAmelCase = self.calculate_heuristic() def UpperCAmelCase__ ( self :str ) -> float: UpperCAmelCase = abs(self.pos_x - self.goal_x ) UpperCAmelCase = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self :Optional[int] , lowercase_ :Any ) -> bool: return self.f_cost < other.f_cost class A_ : """simple docstring""" def __init__( self :Optional[int] , lowercase_ :tuple[int, int] , lowercase_ :tuple[int, int] ) -> str: UpperCAmelCase = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , __snake_case ) UpperCAmelCase = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , __snake_case ) UpperCAmelCase = [self.start] UpperCAmelCase = [] UpperCAmelCase = False def UpperCAmelCase__ ( self :Optional[Any] ) -> Path | None: while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() UpperCAmelCase = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: UpperCAmelCase = True return self.retrace_path(__snake_case ) self.closed_nodes.append(__snake_case ) UpperCAmelCase = self.get_successors(__snake_case ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(__snake_case ) else: # retrieve the best current path UpperCAmelCase = self.open_nodes.pop(self.open_nodes.index(__snake_case ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(__snake_case ) else: self.open_nodes.append(__snake_case ) if not self.reached: return [self.start.pos] return None def UpperCAmelCase__ ( self :Optional[int] , lowercase_ :Node ) -> list[Node]: UpperCAmelCase = [] for action in delta: UpperCAmelCase = parent.pos_x + action[1] UpperCAmelCase = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__snake_case ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( __snake_case , __snake_case , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , __snake_case , ) ) return successors def UpperCAmelCase__ ( self :int , lowercase_ :Node | None ) -> Path: UpperCAmelCase = node UpperCAmelCase = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) UpperCAmelCase = current_node.parent path.reverse() return path if __name__ == "__main__": snake_case_ = (0, 0) snake_case_ = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("""------""") snake_case_ = GreedyBestFirst(init, goal) snake_case_ = greedy_bf.search() if path: for pos_x, pos_y in path: snake_case_ = 2 for elem in grid: print(elem)
78
'''simple docstring''' # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position A__ : Dict ='''2.13.1''' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse('''3.7'''): raise ImportWarning( '''To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.''' ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( '''To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n''' '''If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.''' ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip A__ : Tuple =concatenate_datasets A__ : Dict =DownloadConfig A__ : int =DownloadManager A__ : Union[str, Any] =DownloadMode A__ : Tuple =DownloadConfig A__ : Optional[Any] =DownloadMode A__ : str =DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
70
0
"""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 SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { "google/mobilenet_v1_1.0_224": "https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json", "google/mobilenet_v1_0.75_192": "https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCAmelCase_ ( A_ ): lowercase__ = '''mobilenet_v1''' def __init__( self : int , snake_case_ : Union[str, Any]=3 , snake_case_ : Tuple=224 , snake_case_ : Optional[int]=1.0 , snake_case_ : Optional[int]=8 , snake_case_ : List[Any]="relu6" , snake_case_ : Optional[Any]=True , snake_case_ : str=0.999 , snake_case_ : Tuple=0.02 , snake_case_ : Optional[int]=0.001 , **snake_case_ : Optional[Any] , ) -> Any: '''simple docstring''' super().__init__(**snake_case_ ) if depth_multiplier <= 0: raise ValueError("depth_multiplier must be greater than zero." ) A__ = num_channels A__ = image_size A__ = depth_multiplier A__ = min_depth A__ = hidden_act A__ = tf_padding A__ = classifier_dropout_prob A__ = initializer_range A__ = layer_norm_eps class UpperCAmelCase_ ( A_ ): lowercase__ = version.parse('''1.11''' ) @property def __magic_name__ ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict([("pixel_values", {0: "batch"})] ) @property def __magic_name__ ( self : Any ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "image-classification": return OrderedDict([("logits", {0: "batch"})] ) else: return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] ) @property def __magic_name__ ( self : List[str] ) -> float: '''simple docstring''' return 1e-4
367
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCAmelCase_ ( A_ ): lowercase__ = ['''image_processor''', '''tokenizer'''] lowercase__ = '''AutoImageProcessor''' lowercase__ = '''AutoTokenizer''' def __init__( self : str , snake_case_ : Dict , snake_case_ : List[str] ) -> str: '''simple docstring''' super().__init__(snake_case_ , snake_case_ ) A__ = self.image_processor def __call__( self : int , snake_case_ : Any=None , snake_case_ : Any=None , snake_case_ : Union[str, Any]=None , **snake_case_ : Optional[int] ) -> Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: A__ = self.tokenizer(snake_case_ , return_tensors=snake_case_ , **snake_case_ ) if images is not None: A__ = self.image_processor(snake_case_ , return_tensors=snake_case_ , **snake_case_ ) if text is not None and images is not None: A__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**snake_case_ ) , tensor_type=snake_case_ ) def __magic_name__ ( self : Optional[int] , *snake_case_ : Union[str, Any] , **snake_case_ : List[Any] ) -> int: '''simple docstring''' return self.tokenizer.batch_decode(*snake_case_ , **snake_case_ ) def __magic_name__ ( self : List[str] , *snake_case_ : List[str] , **snake_case_ : Optional[int] ) -> Tuple: '''simple docstring''' return self.tokenizer.decode(*snake_case_ , **snake_case_ ) @property def __magic_name__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' return ["input_ids", "attention_mask", "pixel_values"]
230
0
"""simple docstring""" # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import sys import transformers a__ : Dict = '''3''' print('''Python version:''', sys.version) print('''transformers version:''', transformers.__version__) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) print('''NCCL version:''', torch.cuda.nccl.version()) except ImportError: print('''Torch version:''', None) try: import deepspeed print('''DeepSpeed version:''', deepspeed.__version__) except ImportError: print('''DeepSpeed version:''', None) try: import tensorflow as tf print('''TensorFlow version:''', tf.__version__) print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU'''))) print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU'''))) except ImportError: print('''TensorFlow version:''', None)
54
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a__ : Tuple = False class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" pass @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images __SCREAMING_SNAKE_CASE = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
54
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class __SCREAMING_SNAKE_CASE (metaclass=lowerCamelCase_ ): """simple docstring""" __a =['onnx'] def __init__( self : List[str] , *__a : Tuple , **__a : Optional[Any] ): requires_backends(self , ["onnx"] ) @classmethod def UpperCamelCase__ ( cls : str , *__a : Tuple , **__a : Union[str, Any] ): requires_backends(cls , ["onnx"] ) @classmethod def UpperCamelCase__ ( cls : Optional[Any] , *__a : Optional[int] , **__a : int ): requires_backends(cls , ["onnx"] )
354
'''simple docstring''' import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase_ : Tuple = WebClient(token=os.environ['CI_SLACK_BOT_TOKEN']) def _lowerCamelCase ( lowercase : List[Any] ) -> Optional[int]: _a = test_results.split(" " ) _a = 0 _a = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. _a = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def _lowerCamelCase ( lowercase : str ) -> Optional[Any]: _a = {} _a = None _a = False for line in failures_short_lines.split("\n" ): if re.search(r"_ \[doctest\]" , lowercase ): _a = True _a = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): _a = line _a = False return failures class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Tuple , __a : str , __a : Dict ): _a = title _a = doc_test_results["time_spent"].split("," )[0] _a = doc_test_results["success"] _a = doc_test_results["failures"] _a = self.n_success + self.n_failures # Failures and success of the modeling tests _a = doc_test_results @property def UpperCamelCase__ ( self : int ): _a = [self._time_spent] _a = 0 for time in time_spent: _a = time.split(":" ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(__a ) == 1: _a = [0, 0, time_parts[0]] _a , _a , _a = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds _a , _a , _a = total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(__a )}h{int(__a )}m{int(__a )}s' @property def UpperCamelCase__ ( self : Optional[Any] ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def UpperCamelCase__ ( self : Optional[Any] ): return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : List[str] ): return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def UpperCamelCase__ ( self : str ): _a = 40 _a = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(__a , __a )} _a = "" for category, failures in category_failures.items(): if len(__a ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(__a ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def UpperCamelCase__ ( self : List[str] ): _a = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(__a ) @staticmethod def UpperCamelCase__ ( ): _a = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(__a )} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=__a , ) def UpperCamelCase__ ( self : Tuple ): print("Sending the following payload" ) print(json.dumps({"blocks": json.loads(self.payload )} ) ) _a = f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else "All tests passed." _a = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=__a , ) def UpperCamelCase__ ( self : Dict , __a : List[str] , __a : List[Any] , __a : Tuple , __a : int ): _a = "" for key, value in failures.items(): _a = value[:2_00] + " [Truncated]" if len(__a ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' _a = job_name _a = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: _a = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def UpperCamelCase__ ( self : str ): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made." ) _a = self.doc_test_results.pop("job_link" ) self.doc_test_results.pop("failures" ) self.doc_test_results.pop("success" ) self.doc_test_results.pop("time_spent" ) _a = sorted(self.doc_test_results.items() , key=lambda __a : t[0] ) for job, job_result in sorted_dict: if len(job_result["failures"] ): _a = f'*Num failures* :{len(job_result["failed"] )} \n' _a = job_result["failures"] _a = self.get_reply_blocks(__a , __a , __a , text=__a ) print("Sending the following reply" ) print(json.dumps({"blocks": blocks} ) ) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=f'Results for {job}' , blocks=__a , thread_ts=self.thread_ts["ts"] , ) time.sleep(1 ) def _lowerCamelCase ( ) -> Any: _a = os.environ["GITHUB_RUN_ID"] _a = F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' _a = requests.get(lowercase ).json() _a = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) _a = math.ceil((result["total_count"] - 100) / 100 ) for i in range(lowercase ): _a = requests.get(url + F'&page={i + 2}' ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , lowercase ) return {} def _lowerCamelCase ( lowercase : str ) -> Dict: _a = {} if os.path.exists(lowercase ): _a = os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase , lowercase ) , encoding="utf-8" ) as f: _a = f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase , lowercase )}.' ) from e return _artifact def _lowerCamelCase ( ) -> str: class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __a : str ): _a = name _a = [] def __str__( self : List[str] ): return self.name def UpperCamelCase__ ( self : str , __a : str ): self.paths.append({"name": self.name, "path": path} ) _a = {} _a = filter(os.path.isdir , os.listdir() ) for directory in directories: _a = directory if artifact_name not in _available_artifacts: _a = Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase_ : List[Any] = get_job_links() lowerCAmelCase_ : Any = retrieve_available_artifacts() lowerCAmelCase_ : List[str] = collections.OrderedDict( [ ('*.py', 'API Examples'), ('*.md', 'MD Examples'), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase_ : Optional[Any] = { v: { 'failed': [], 'failures': {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase_ : int = github_actions_job_links.get('run_doctests') lowerCAmelCase_ : Union[str, Any] = available_artifacts['doc_tests_gpu_test_reports'].paths[0] lowerCAmelCase_ : List[str] = retrieve_artifact(artifact_path['name']) if "stats" in artifact: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = handle_test_results(artifact['stats']) lowerCAmelCase_ : List[str] = failed lowerCAmelCase_ : Optional[Any] = success lowerCAmelCase_ : Tuple = time_spent[1:-1] + ', ' lowerCAmelCase_ : List[Any] = extract_first_line_failure(artifact['failures_short']) for line in artifact["summary_short"].split('\n'): if re.search('FAILED', line): lowerCAmelCase_ : int = line.replace('FAILED ', '') lowerCAmelCase_ : Optional[int] = line.split()[0].replace('\n', '') if "::" in line: lowerCAmelCase_ , lowerCAmelCase_ : str = line.split('::') else: lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase_ : Union[str, Any] = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase_ : List[str] = all_failures[test] if test in all_failures else 'N/A' lowerCAmelCase_ : Optional[Any] = failure break lowerCAmelCase_ : Tuple = Message('🤗 Results of the doc tests.', doc_test_results) message.post() message.post_reply()
346
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase__ = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
65
'''simple docstring''' from __future__ import annotations from collections.abc import MutableSequence class lowercase__ : def __init__( self : List[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : MutableSequence[float] ): '''simple docstring''' if len(lowerCamelCase__ ) != degree + 1: raise ValueError( 'The number of coefficients should be equal to the degree + 1.' ) _UpperCamelCase : list[float] = list(lowerCamelCase__ ) _UpperCamelCase : Tuple = degree def __add__( self : Optional[int] ,lowerCamelCase__ : Polynomial ): '''simple docstring''' if self.degree > polynomial_a.degree: _UpperCamelCase : str = self.coefficients[:] for i in range(polynomial_a.degree + 1 ): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree ,lowerCamelCase__ ) else: _UpperCamelCase : str = polynomial_a.coefficients[:] for i in range(self.degree + 1 ): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree ,lowerCamelCase__ ) def __sub__( self : Dict ,lowerCamelCase__ : Polynomial ): '''simple docstring''' return self + polynomial_a * Polynomial(0 ,[-1] ) def __neg__( self : Dict ): '''simple docstring''' return Polynomial(self.degree ,[-c for c in self.coefficients] ) def __mul__( self : Union[str, Any] ,lowerCamelCase__ : Polynomial ): '''simple docstring''' _UpperCamelCase : list[float] = [0] * (self.degree + polynomial_a.degree + 1) for i in range(self.degree + 1 ): for j in range(polynomial_a.degree + 1 ): coefficients[i + j] += ( self.coefficients[i] * polynomial_a.coefficients[j] ) return Polynomial(self.degree + polynomial_a.degree ,lowerCamelCase__ ) def UpperCamelCase_ ( self : Dict ,lowerCamelCase__ : int | float ): '''simple docstring''' _UpperCamelCase : int | float = 0 for i in range(self.degree + 1 ): result += self.coefficients[i] * (substitution**i) return result def __str__( self : Union[str, Any] ): '''simple docstring''' _UpperCamelCase : Dict = '' for i in range(self.degree ,-1 ,-1 ): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i] ) ) elif i == 1: polynomial += str(abs(self.coefficients[i] ) ) + "x" else: polynomial += str(abs(self.coefficients[i] ) ) + "x^" + str(lowerCamelCase__ ) return polynomial def __repr__( self : List[str] ): '''simple docstring''' return self.__str__() def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' _UpperCamelCase : list[float] = [0] * self.degree for i in range(self.degree ): _UpperCamelCase : Optional[int] = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 ,lowerCamelCase__ ) def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : int | float = 0 ): '''simple docstring''' _UpperCamelCase : list[float] = [0] * (self.degree + 2) _UpperCamelCase : Any = constant for i in range(self.degree + 1 ): _UpperCamelCase : Optional[Any] = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 ,lowerCamelCase__ ) def __eq__( self : str ,lowerCamelCase__ : object ): '''simple docstring''' if not isinstance(lowerCamelCase__ ,lowerCamelCase__ ): return False if self.degree != polynomial_a.degree: return False for i in range(self.degree + 1 ): if self.coefficients[i] != polynomial_a.coefficients[i]: return False return True def __ne__( self : List[str] ,lowerCamelCase__ : object ): '''simple docstring''' return not self.__eq__(lowerCamelCase__ )
83
0
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version __snake_case : Optional[int] = { '<': operator.lt, '<=': operator.le, '==': operator.eq, '!=': operator.ne, '>=': operator.ge, '>': operator.gt, } def _lowercase ( __snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> int: if got_ver is None or want_ver is None: raise ValueError( F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider""" F""" reinstalling {pkg}.""" ) if not ops[op](version.parse(__snake_case ) ,version.parse(__snake_case ) ): raise ImportError( F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" ) def _lowercase ( __snake_case ,__snake_case = None ) -> None: __lowerCAmelCase : List[Any] = F"""\n{hint}""" if hint is not None else "" # non-versioned check if re.match(r"^[\w_\-\d]+$" ,__snake_case ): __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : int = requirement, None, None else: __lowerCAmelCase : Any = re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2}.+)" ,__snake_case ) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but" F""" got {requirement}""" ) __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = match[0] __lowerCAmelCase : int = want_full.split("," ) # there could be multiple requirements __lowerCAmelCase : Optional[Any] = {} for w in want_range: __lowerCAmelCase : int = re.findall(r"^([\s!=<>]{1,2})(.+)" ,__snake_case ) if not match: raise ValueError( "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23," F""" but got {requirement}""" ) __lowerCAmelCase , __lowerCAmelCase : Optional[int] = match[0] __lowerCAmelCase : str = want_ver if op not in ops: raise ValueError(F"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" ) # special case if pkg == "python": __lowerCAmelCase : Optional[Any] = ".".join([str(__snake_case ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) return # check if any version is installed try: __lowerCAmelCase : Dict = importlib.metadata.version(__snake_case ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F"""The '{requirement}' distribution was not found and is required by this application. {hint}""" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) def _lowercase ( __snake_case ) -> Optional[Any]: __lowerCAmelCase : Union[str, Any] = "Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main" return require_version(__snake_case ,__snake_case )
58
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VivitImageProcessor class A__ ( unittest.TestCase ): '''simple docstring''' def __init__( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: List[Any]=7 , _SCREAMING_SNAKE_CASE: Optional[Any]=3 , _SCREAMING_SNAKE_CASE: int=10 , _SCREAMING_SNAKE_CASE: Tuple=18 , _SCREAMING_SNAKE_CASE: Union[str, Any]=30 , _SCREAMING_SNAKE_CASE: Any=400 , _SCREAMING_SNAKE_CASE: List[str]=True , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: str=True , _SCREAMING_SNAKE_CASE: Union[str, Any]=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE: Any=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE: Dict=None , ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = size if size is not None else {"shortest_edge": 18} __lowerCAmelCase : int = crop_size if crop_size is not None else {"height": 18, "width": 18} __lowerCAmelCase : Tuple = parent __lowerCAmelCase : List[Any] = batch_size __lowerCAmelCase : List[str] = num_channels __lowerCAmelCase : int = num_frames __lowerCAmelCase : Union[str, Any] = image_size __lowerCAmelCase : Tuple = min_resolution __lowerCAmelCase : Tuple = max_resolution __lowerCAmelCase : str = do_resize __lowerCAmelCase : Optional[int] = size __lowerCAmelCase : Optional[int] = do_normalize __lowerCAmelCase : Dict = image_mean __lowerCAmelCase : List[Any] = image_std __lowerCAmelCase : List[Any] = crop_size def _SCREAMING_SNAKE_CASE ( self: int) -> Union[str, Any]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class A__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = VivitImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self: int) -> Tuple: """simple docstring""" __lowerCAmelCase : Optional[int] = VivitImageProcessingTester(self) @property def _SCREAMING_SNAKE_CASE ( self: int) -> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> Optional[int]: """simple docstring""" __lowerCAmelCase : int = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "image_mean")) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "image_std")) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "do_normalize")) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "do_resize")) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "do_center_crop")) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "size")) def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {"shortest_edge": 18}) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18}) __lowerCAmelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84) self.assertEqual(image_processor.size , {"shortest_edge": 42}) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84}) def _SCREAMING_SNAKE_CASE ( self: int) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : List[str] = self.image_processing_class(**self.image_processor_dict) # create random PIL videos __lowerCAmelCase : Dict = prepare_video_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE) for video in video_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) self.assertIsInstance(video[0] , Image.Image) # Test not batched input __lowerCAmelCase : Any = image_processing(video_inputs[0] , return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __lowerCAmelCase : str = image_processing(_SCREAMING_SNAKE_CASE , return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def _SCREAMING_SNAKE_CASE ( self: List[str]) -> int: """simple docstring""" __lowerCAmelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __lowerCAmelCase : Optional[int] = prepare_video_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , numpify=_SCREAMING_SNAKE_CASE) for video in video_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) self.assertIsInstance(video[0] , np.ndarray) # Test not batched input __lowerCAmelCase : Any = image_processing(video_inputs[0] , return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __lowerCAmelCase : List[str] = image_processing(_SCREAMING_SNAKE_CASE , return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def _SCREAMING_SNAKE_CASE ( self: Dict) -> int: """simple docstring""" __lowerCAmelCase : str = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __lowerCAmelCase : Optional[int] = prepare_video_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE) for video in video_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) self.assertIsInstance(video[0] , torch.Tensor) # Test not batched input __lowerCAmelCase : List[str] = image_processing(video_inputs[0] , return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __lowerCAmelCase : Any = image_processing(_SCREAMING_SNAKE_CASE , return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
58
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import 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 from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case_( a__ , a__ , a__ , unittest.TestCase ): __UpperCamelCase = AltDiffusionPipeline __UpperCamelCase = TEXT_TO_IMAGE_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase__ ( self : Union[str, Any] ): torch.manual_seed(0 ) lowerCAmelCase : List[str] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , ) lowerCAmelCase : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=UpperCamelCase_ , set_alpha_to_one=UpperCamelCase_ , ) torch.manual_seed(0 ) lowerCAmelCase : int = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0 ) lowerCAmelCase : List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_0_0_2 , ) lowerCAmelCase : str = CLIPTextModel(UpperCamelCase_ ) lowerCAmelCase : Any = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) lowerCAmelCase : Union[str, Any] = 7_7 lowerCAmelCase : Optional[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def lowerCamelCase__ ( self : int , UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any]=0 ): if str(UpperCamelCase_ ).startswith('''mps''' ): lowerCAmelCase : Optional[int] = torch.manual_seed(UpperCamelCase_ ) else: lowerCAmelCase : List[Any] = torch.Generator(device=UpperCamelCase_ ).manual_seed(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = { '''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 : Any ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def lowerCamelCase__ ( self : Optional[int] ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def lowerCamelCase__ ( self : str ): lowerCAmelCase : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase : Union[str, Any] = self.get_dummy_components() torch.manual_seed(0 ) lowerCAmelCase : List[Any] = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_0_0_2 , ) # TODO: remove after fixing the non-deterministic text encoder lowerCAmelCase : Optional[Any] = RobertaSeriesModelWithTransformation(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = text_encoder lowerCAmelCase : int = AltDiffusionPipeline(**UpperCamelCase_ ) lowerCAmelCase : Any = alt_pipe.to(UpperCamelCase_ ) alt_pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : str = self.get_dummy_inputs(UpperCamelCase_ ) lowerCAmelCase : List[str] = '''A photo of an astronaut''' lowerCAmelCase : Optional[Any] = alt_pipe(**UpperCamelCase_ ) lowerCAmelCase : Any = output.images lowerCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowerCAmelCase : Any = np.array( [0.5_748_162, 0.60_447_145, 0.48_821_217, 0.50_100_636, 0.5_431_185, 0.45_763_683, 0.49_657_696, 0.48_132_733, 0.47_573_093] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase : Dict = self.get_dummy_components() lowerCAmelCase : int = PNDMScheduler(skip_prk_steps=UpperCamelCase_ ) torch.manual_seed(0 ) lowerCAmelCase : List[Any] = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_0_0_2 , ) # TODO: remove after fixing the non-deterministic text encoder lowerCAmelCase : str = RobertaSeriesModelWithTransformation(UpperCamelCase_ ) lowerCAmelCase : List[str] = text_encoder lowerCAmelCase : Optional[int] = AltDiffusionPipeline(**UpperCamelCase_ ) lowerCAmelCase : int = alt_pipe.to(UpperCamelCase_ ) alt_pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : int = self.get_dummy_inputs(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = alt_pipe(**UpperCamelCase_ ) lowerCAmelCase : str = output.images lowerCAmelCase : int = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowerCAmelCase : Any = np.array( [0.51_605_093, 0.5_707_241, 0.47_365_507, 0.50_578_886, 0.5_633_877, 0.4_642_503, 0.5_182_081, 0.48_763_484, 0.49_084_237] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self : List[Any] ): # make sure here that pndm scheduler skips prk lowerCAmelCase : str = AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion''' , safety_checker=UpperCamelCase_ ) lowerCAmelCase : Any = alt_pipe.to(UpperCamelCase_ ) alt_pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : Tuple = '''A painting of a squirrel eating a burger''' lowerCAmelCase : Dict = torch.manual_seed(0 ) lowerCAmelCase : Optional[Any] = alt_pipe([prompt] , generator=UpperCamelCase_ , guidance_scale=6.0 , num_inference_steps=2_0 , output_type='''np''' ) lowerCAmelCase : int = output.images lowerCAmelCase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase : List[str] = np.array([0.1_010, 0.0_800, 0.0_794, 0.0_885, 0.0_843, 0.0_762, 0.0_769, 0.0_729, 0.0_586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Union[str, Any] = DDIMScheduler.from_pretrained('''BAAI/AltDiffusion''' , subfolder='''scheduler''' ) lowerCAmelCase : Union[str, Any] = AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion''' , scheduler=UpperCamelCase_ , safety_checker=UpperCamelCase_ ) lowerCAmelCase : str = alt_pipe.to(UpperCamelCase_ ) alt_pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : Dict = '''A painting of a squirrel eating a burger''' lowerCAmelCase : str = torch.manual_seed(0 ) lowerCAmelCase : List[str] = alt_pipe([prompt] , generator=UpperCamelCase_ , num_inference_steps=2 , output_type='''numpy''' ) lowerCAmelCase : str = output.images lowerCAmelCase : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase : Dict = np.array([0.4_019, 0.4_052, 0.3_810, 0.4_119, 0.3_916, 0.3_982, 0.4_651, 0.4_195, 0.5_323] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
60
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: snake_case__ : str = None snake_case__ : Optional[Any] = logging.get_logger(__name__) snake_case__ : Optional[int] = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} snake_case__ : Dict = { '''vocab_file''': { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/spiece.model''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/spiece.model''', }, '''tokenizer_file''': { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json''', }, } snake_case__ : Any = { '''google/fnet-base''': 512, '''google/fnet-large''': 512, } snake_case__ : Dict = '''▁''' class snake_case_( a__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ['''input_ids''', '''token_type_ids'''] __UpperCamelCase = FNetTokenizer def __init__( self : Union[str, Any] , UpperCamelCase_ : Union[str, Any]=None , UpperCamelCase_ : Union[str, Any]=None , UpperCamelCase_ : Any=False , UpperCamelCase_ : Any=True , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Tuple="<unk>" , UpperCamelCase_ : List[str]="[SEP]" , UpperCamelCase_ : List[Any]="<pad>" , UpperCamelCase_ : Union[str, Any]="[CLS]" , UpperCamelCase_ : int="[MASK]" , **UpperCamelCase_ : Optional[Any] , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. lowerCAmelCase : int = ( AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ , normalized=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token ) super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , remove_space=UpperCamelCase_ , keep_accents=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , **UpperCamelCase_ , ) lowerCAmelCase : Optional[int] = do_lower_case lowerCAmelCase : str = remove_space lowerCAmelCase : Any = keep_accents lowerCAmelCase : int = vocab_file lowerCAmelCase : List[str] = False if not self.vocab_file else True def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : Optional[int] = [self.sep_token_id] lowerCAmelCase : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : List[str] = [self.sep_token_id] lowerCAmelCase : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ): if not os.path.isdir(UpperCamelCase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCAmelCase : str = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ): copyfile(self.vocab_file , UpperCamelCase_ ) return (out_vocab_file,)
60
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 __A = logging.get_logger(__name__) __A = { """google/mobilenet_v2_1.4_224""": """https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json""", """google/mobilenet_v2_1.0_224""": """https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json""", """google/mobilenet_v2_0.75_160""": """https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json""", """google/mobilenet_v2_0.35_96""": """https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json""", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class _lowerCAmelCase ( __lowercase ): """simple docstring""" __magic_name__ :List[Any] = """mobilenet_v2""" def __init__( self , __UpperCAmelCase=3 , __UpperCAmelCase=2_2_4 , __UpperCAmelCase=1.0 , __UpperCAmelCase=8 , __UpperCAmelCase=8 , __UpperCAmelCase=6 , __UpperCAmelCase=3_2 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase="relu6" , __UpperCAmelCase=True , __UpperCAmelCase=0.8 , __UpperCAmelCase=0.02 , __UpperCAmelCase=0.0_01 , __UpperCAmelCase=2_5_5 , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**_a ) if depth_multiplier <= 0: raise ValueError('depth_multiplier must be greater than zero.' ) lowerCAmelCase__ :str = num_channels lowerCAmelCase__ :List[Any] = image_size lowerCAmelCase__ :Any = depth_multiplier lowerCAmelCase__ :Dict = depth_divisible_by lowerCAmelCase__ :Dict = min_depth lowerCAmelCase__ :int = expand_ratio lowerCAmelCase__ :str = output_stride lowerCAmelCase__ :Any = first_layer_is_expansion lowerCAmelCase__ :Any = finegrained_output lowerCAmelCase__ :str = hidden_act lowerCAmelCase__ :Any = tf_padding lowerCAmelCase__ :Optional[Any] = classifier_dropout_prob lowerCAmelCase__ :int = initializer_range lowerCAmelCase__ :Any = layer_norm_eps lowerCAmelCase__ :Tuple = semantic_loss_ignore_index class _lowerCAmelCase ( __lowercase ): """simple docstring""" __magic_name__ :Optional[int] = version.parse("""1.11""" ) @property def snake_case ( self ): '''simple docstring''' return OrderedDict([('pixel_values', {0: 'batch'})] ) @property def snake_case ( self ): '''simple docstring''' if self.task == "image-classification": return OrderedDict([('logits', {0: 'batch'})] ) else: return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})] ) @property def snake_case ( self ): '''simple docstring''' return 1E-4
350
"""simple docstring""" from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) ->str: """simple docstring""" if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path lowerCAmelCase__ :Optional[int] = quote(_SCREAMING_SNAKE_CASE ) return hfh.hf_hub_url(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' , revision=_SCREAMING_SNAKE_CASE )
254
0
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __a ( __UpperCamelCase ): __lowercase : Any = ['vqvae'] def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , mel=lowerCAmelCase__ , vqvae=lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' return 50 if isinstance(self.scheduler , lowerCAmelCase__ ) else 1_000 @torch.no_grad() def __call__( self , lowerCAmelCase__ = 1 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = 0 , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = 0 , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: '''simple docstring''' lowercase__: Union[str, Any] = steps or self.get_default_steps() self.scheduler.set_timesteps(lowerCAmelCase__ ) lowercase__: Optional[int] = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: lowercase__: Optional[int] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: lowercase__: List[str] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=lowerCAmelCase__ , device=self.device , ) lowercase__: List[Any] = noise lowercase__: int = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(lowerCAmelCase__ , lowerCAmelCase__ ) lowercase__: int = self.mel.audio_slice_to_image(lowerCAmelCase__ ) lowercase__: int = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape( (input_image.height, input_image.width) ) lowercase__: str = (input_image / 255) * 2 - 1 lowercase__: Union[str, Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: lowercase__: Optional[int] = self.vqvae.encode(torch.unsqueeze(lowerCAmelCase__ , 0 ) ).latent_dist.sample( generator=lowerCAmelCase__ )[0] lowercase__: Dict = self.vqvae.config.scaling_factor * input_images if start_step > 0: lowercase__: List[Any] = self.scheduler.add_noise(lowerCAmelCase__ , lowerCAmelCase__ , self.scheduler.timesteps[start_step - 1] ) lowercase__: str = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) lowercase__: Dict = int(mask_start_secs * pixels_per_second ) lowercase__: Tuple = int(mask_end_secs * pixels_per_second ) lowercase__: List[Any] = self.scheduler.add_noise(lowerCAmelCase__ , lowerCAmelCase__ , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , lowerCAmelCase__ ): lowercase__: Union[str, Any] = self.unet(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )['sample'] else: lowercase__: Optional[Any] = self.unet(lowerCAmelCase__ , lowerCAmelCase__ )['sample'] if isinstance(self.scheduler , lowerCAmelCase__ ): lowercase__: List[str] = self.scheduler.step( model_output=lowerCAmelCase__ , timestep=lowerCAmelCase__ , sample=lowerCAmelCase__ , eta=lowerCAmelCase__ , generator=lowerCAmelCase__ , )['prev_sample'] else: lowercase__: int = self.scheduler.step( model_output=lowerCAmelCase__ , timestep=lowerCAmelCase__ , sample=lowerCAmelCase__ , generator=lowerCAmelCase__ , )['prev_sample'] if mask is not None: if mask_start > 0: lowercase__: List[Any] = mask[:, step, :, :mask_start] if mask_end > 0: lowercase__: Optional[int] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance lowercase__: Union[str, Any] = 1 / self.vqvae.config.scaling_factor * images lowercase__: Optional[Any] = self.vqvae.decode(lowerCAmelCase__ )['sample'] lowercase__: Dict = (images / 2 + 0.5).clamp(0 , 1 ) lowercase__: List[Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() lowercase__: int = (images * 255).round().astype('uint8' ) lowercase__: Optional[Any] = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(lowerCAmelCase__ , mode='RGB' ).convert('L' ) for _ in images) ) lowercase__: Dict = [self.mel.image_to_audio(lowerCAmelCase__ ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(lowerCAmelCase__ )[:, np.newaxis, :] ) , **ImagePipelineOutput(lowerCAmelCase__ ) ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = 50 ) -> np.ndarray: '''simple docstring''' assert isinstance(self.scheduler , lowerCAmelCase__ ) self.scheduler.set_timesteps(lowerCAmelCase__ ) lowercase__: List[str] = np.array( [np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) lowercase__: str = (sample / 255) * 2 - 1 lowercase__: str = torch.Tensor(lowerCAmelCase__ ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): lowercase__: Union[str, Any] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps lowercase__: Optional[Any] = self.scheduler.alphas_cumprod[t] lowercase__: str = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) lowercase__: str = 1 - alpha_prod_t lowercase__: int = self.unet(lowerCAmelCase__ , lowerCAmelCase__ )['sample'] lowercase__: int = (1 - alpha_prod_t_prev) ** 0.5 * model_output lowercase__: Optional[int] = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) lowercase__: Any = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> torch.Tensor: '''simple docstring''' lowercase__: Any = acos(torch.dot(torch.flatten(lowerCAmelCase__ ) , torch.flatten(lowerCAmelCase__ ) ) / torch.norm(lowerCAmelCase__ ) / torch.norm(lowerCAmelCase__ ) ) return sin((1 - alpha) * theta ) * xa / sin(lowerCAmelCase__ ) + sin(alpha * theta ) * xa / sin(lowerCAmelCase__ )
196
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig __lowerCAmelCase = logging.get_logger(__name__) # General docstring __lowerCAmelCase = '''RegNetConfig''' # Base docstring __lowerCAmelCase = '''facebook/regnet-y-040''' __lowerCAmelCase = [1, 10_88, 7, 7] # Image classification docstring __lowerCAmelCase = '''facebook/regnet-y-040''' __lowerCAmelCase = '''tabby, tabby cat''' __lowerCAmelCase = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class __a ( nn.Module ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 3 , lowerCAmelCase__ = 1 , lowerCAmelCase__ = 1 , lowerCAmelCase__ = "relu" , ) -> Optional[Any]: '''simple docstring''' super().__init__() lowercase__: Any = nn.Convad( lowerCAmelCase__ , lowerCAmelCase__ , kernel_size=lowerCAmelCase__ , stride=lowerCAmelCase__ , padding=kernel_size // 2 , groups=lowerCAmelCase__ , bias=lowerCAmelCase__ , ) lowercase__: str = nn.BatchNormad(lowerCAmelCase__ ) lowercase__: Union[str, Any] = ACTaFN[activation] if activation is not None else nn.Identity() def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Dict: '''simple docstring''' lowercase__: List[str] = self.convolution(lowerCAmelCase__ ) lowercase__: Optional[Any] = self.normalization(lowerCAmelCase__ ) lowercase__: Union[str, Any] = self.activation(lowerCAmelCase__ ) return hidden_state class __a ( nn.Module ): def __init__( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' super().__init__() lowercase__: Dict = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) lowercase__: Dict = config.num_channels def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> int: '''simple docstring''' lowercase__: Tuple = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.' ) lowercase__: Optional[int] = self.embedder(lowerCAmelCase__ ) return hidden_state class __a ( nn.Module ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 2 ) -> Optional[Any]: '''simple docstring''' super().__init__() lowercase__: Optional[Any] = nn.Convad(lowerCAmelCase__ , lowerCAmelCase__ , kernel_size=1 , stride=lowerCAmelCase__ , bias=lowerCAmelCase__ ) lowercase__: Union[str, Any] = nn.BatchNormad(lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Tensor: '''simple docstring''' lowercase__: Any = self.convolution(lowerCAmelCase__ ) lowercase__: str = self.normalization(lowerCAmelCase__ ) return hidden_state class __a ( nn.Module ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' super().__init__() lowercase__: Any = nn.AdaptiveAvgPoolad((1, 1) ) lowercase__: str = nn.Sequential( nn.Convad(lowerCAmelCase__ , lowerCAmelCase__ , kernel_size=1 ) , nn.ReLU() , nn.Convad(lowerCAmelCase__ , lowerCAmelCase__ , kernel_size=1 ) , nn.Sigmoid() , ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' # b c h w -> b c 1 1 lowercase__: str = self.pooler(lowerCAmelCase__ ) lowercase__: List[str] = self.attention(lowerCAmelCase__ ) lowercase__: List[Any] = hidden_state * attention return hidden_state class __a ( nn.Module ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 1 ) -> Dict: '''simple docstring''' super().__init__() lowercase__: str = in_channels != out_channels or stride != 1 lowercase__: Optional[int] = max(1 , out_channels // config.groups_width ) lowercase__: Union[str, Any] = ( RegNetShortCut(lowerCAmelCase__ , lowerCAmelCase__ , stride=lowerCAmelCase__ ) if should_apply_shortcut else nn.Identity() ) lowercase__: Dict = nn.Sequential( RegNetConvLayer(lowerCAmelCase__ , lowerCAmelCase__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(lowerCAmelCase__ , lowerCAmelCase__ , stride=lowerCAmelCase__ , groups=lowerCAmelCase__ , activation=config.hidden_act ) , RegNetConvLayer(lowerCAmelCase__ , lowerCAmelCase__ , kernel_size=1 , activation=lowerCAmelCase__ ) , ) lowercase__: Tuple = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> int: '''simple docstring''' lowercase__: Dict = hidden_state lowercase__: Union[str, Any] = self.layer(lowerCAmelCase__ ) lowercase__: int = self.shortcut(lowerCAmelCase__ ) hidden_state += residual lowercase__: Optional[int] = self.activation(lowerCAmelCase__ ) return hidden_state class __a ( nn.Module ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 1 ) -> Dict: '''simple docstring''' super().__init__() lowercase__: Optional[int] = in_channels != out_channels or stride != 1 lowercase__: List[str] = max(1 , out_channels // config.groups_width ) lowercase__: Any = ( RegNetShortCut(lowerCAmelCase__ , lowerCAmelCase__ , stride=lowerCAmelCase__ ) if should_apply_shortcut else nn.Identity() ) lowercase__: str = nn.Sequential( RegNetConvLayer(lowerCAmelCase__ , lowerCAmelCase__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(lowerCAmelCase__ , lowerCAmelCase__ , stride=lowerCAmelCase__ , groups=lowerCAmelCase__ , activation=config.hidden_act ) , RegNetSELayer(lowerCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(lowerCAmelCase__ , lowerCAmelCase__ , kernel_size=1 , activation=lowerCAmelCase__ ) , ) lowercase__: Union[str, Any] = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' lowercase__: Optional[Any] = hidden_state lowercase__: Optional[int] = self.layer(lowerCAmelCase__ ) lowercase__: str = self.shortcut(lowerCAmelCase__ ) hidden_state += residual lowercase__: Optional[int] = self.activation(lowerCAmelCase__ ) return hidden_state class __a ( nn.Module ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 2 , lowerCAmelCase__ = 2 , ) -> Tuple: '''simple docstring''' super().__init__() lowercase__: Optional[int] = RegNetXLayer if config.layer_type == 'x' else RegNetYLayer lowercase__: str = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , stride=lowerCAmelCase__ , ) , *[layer(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for _ in range(depth - 1 )] , ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' lowercase__: str = self.layers(lowerCAmelCase__ ) return hidden_state class __a ( nn.Module ): def __init__( self , lowerCAmelCase__ ) -> Dict: '''simple docstring''' super().__init__() lowercase__: int = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( lowerCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) lowercase__: int = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(lowerCAmelCase__ , config.depths[1:] ): self.stages.append(RegNetStage(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , depth=lowerCAmelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = True ) -> BaseModelOutputWithNoAttention: '''simple docstring''' lowercase__: List[str] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowercase__: Optional[Any] = hidden_states + (hidden_state,) lowercase__: List[Any] = stage_module(lowerCAmelCase__ ) if output_hidden_states: lowercase__: Optional[Any] = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=lowerCAmelCase__ , hidden_states=lowerCAmelCase__ ) class __a ( __UpperCamelCase ): __lowercase : Dict = RegNetConfig __lowercase : Dict = 'regnet' __lowercase : str = 'pixel_values' __lowercase : List[str] = True def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' if isinstance(lowerCAmelCase__ , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode='fan_out' , nonlinearity='relu' ) elif isinstance(lowerCAmelCase__ , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__=False ) -> Optional[Any]: '''simple docstring''' if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): lowercase__: Any = value __lowerCAmelCase = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' __lowerCAmelCase = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , __UpperCamelCase , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class __a ( __UpperCamelCase ): def __init__( self , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' super().__init__(lowerCAmelCase__ ) lowercase__: Tuple = config lowercase__: List[str] = RegNetEmbeddings(lowerCAmelCase__ ) lowercase__: Optional[int] = RegNetEncoder(lowerCAmelCase__ ) lowercase__: Optional[Any] = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowerCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=lowerCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None ) -> BaseModelOutputWithPoolingAndNoAttention: '''simple docstring''' lowercase__: List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowercase__: Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict lowercase__: Any = self.embedder(lowerCAmelCase__ ) lowercase__: List[Any] = self.encoder( lowerCAmelCase__ , output_hidden_states=lowerCAmelCase__ , return_dict=lowerCAmelCase__ ) lowercase__: Optional[Any] = encoder_outputs[0] lowercase__: Optional[int] = self.pooler(lowerCAmelCase__ ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=lowerCAmelCase__ , pooler_output=lowerCAmelCase__ , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , __UpperCamelCase , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class __a ( __UpperCamelCase ): def __init__( self , lowerCAmelCase__ ) -> str: '''simple docstring''' super().__init__(lowerCAmelCase__ ) lowercase__: Dict = config.num_labels lowercase__: Dict = RegNetModel(lowerCAmelCase__ ) # classification head lowercase__: str = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowerCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=lowerCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , ) -> ImageClassifierOutputWithNoAttention: '''simple docstring''' lowercase__: str = return_dict if return_dict is not None else self.config.use_return_dict lowercase__: Optional[int] = self.regnet(lowerCAmelCase__ , output_hidden_states=lowerCAmelCase__ , return_dict=lowerCAmelCase__ ) lowercase__: Dict = outputs.pooler_output if return_dict else outputs[1] lowercase__: List[str] = self.classifier(lowerCAmelCase__ ) lowercase__: Optional[Any] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowercase__: Dict = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowercase__: Optional[int] = 'single_label_classification' else: lowercase__: Tuple = 'multi_label_classification' if self.config.problem_type == "regression": lowercase__: List[Any] = MSELoss() if self.num_labels == 1: lowercase__: Optional[int] = loss_fct(logits.squeeze() , labels.squeeze() ) else: lowercase__: int = loss_fct(lowerCAmelCase__ , lowerCAmelCase__ ) elif self.config.problem_type == "single_label_classification": lowercase__: Dict = CrossEntropyLoss() lowercase__: Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowercase__: List[Any] = BCEWithLogitsLoss() lowercase__: Any = loss_fct(lowerCAmelCase__ , lowerCAmelCase__ ) if not return_dict: lowercase__: int = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=lowerCAmelCase__ , logits=lowerCAmelCase__ , hidden_states=outputs.hidden_states )
196
1
def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) __snake_case : Tuple = str(bin(__SCREAMING_SNAKE_CASE ) )[2:] # remove the leading "0b" __snake_case : Any = str(bin(__SCREAMING_SNAKE_CASE ) )[2:] # remove the leading "0b" __snake_case : str = max(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) return "0b" + "".join( str(int(char_a == """1""" and char_b == """1""" ) ) for char_a, char_b in zip(a_binary.zfill(__SCREAMING_SNAKE_CASE ) , b_binary.zfill(__SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
20
from __future__ import annotations import math def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : float ): '''simple docstring''' if depth < 0: raise ValueError("""Depth cannot be less than 0""" ) if len(__SCREAMING_SNAKE_CASE ) == 0: raise ValueError("""Scores cannot be empty""" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , minimax(depth + 1 , node_index * 2 + 1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , ) return min( minimax(depth + 1 , node_index * 2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , minimax(depth + 1 , node_index * 2 + 1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , ) def __lowerCAmelCase ( ): '''simple docstring''' __snake_case : str = [9_0, 2_3, 6, 3_3, 2_1, 6_5, 1_2_3, 3_4_4_2_3] __snake_case : Optional[Any] = math.log(len(__SCREAMING_SNAKE_CASE ) , 2 ) print("""Optimal value : """ , end="""""" ) print(minimax(0 , 0 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
20
1
def UpperCAmelCase__ ( _A : Optional[int] , _A : Optional[Any] ): '''simple docstring''' if digit_amount > 0: return round(number - int(__a ) , __a ) return number - int(__a ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
188
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class lowercase ( A__ ): """simple docstring""" _a = 'camembert' def __init__( self , UpperCamelCase_=30522 , UpperCamelCase_=768 , UpperCamelCase_=12 , UpperCamelCase_=12 , UpperCamelCase_=3072 , UpperCamelCase_="gelu" , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=512 , UpperCamelCase_=2 , UpperCamelCase_=0.02 , UpperCamelCase_=1e-12 , UpperCamelCase_=1 , UpperCamelCase_=0 , UpperCamelCase_=2 , UpperCamelCase_="absolute" , UpperCamelCase_=True , UpperCamelCase_=None , **UpperCamelCase_ , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase_ , bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase__ :int = vocab_size UpperCamelCase__ :Optional[int] = hidden_size UpperCamelCase__ :Optional[int] = num_hidden_layers UpperCamelCase__ :List[Any] = num_attention_heads UpperCamelCase__ :Union[str, Any] = hidden_act UpperCamelCase__ :List[Any] = intermediate_size UpperCamelCase__ :int = hidden_dropout_prob UpperCamelCase__ :Tuple = attention_probs_dropout_prob UpperCamelCase__ :Union[str, Any] = max_position_embeddings UpperCamelCase__ :Tuple = type_vocab_size UpperCamelCase__ :int = initializer_range UpperCamelCase__ :List[str] = layer_norm_eps UpperCamelCase__ :int = position_embedding_type UpperCamelCase__ :Any = use_cache UpperCamelCase__ :Any = classifier_dropout class lowercase ( A__ ): """simple docstring""" @property def lowerCAmelCase__ ( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase__ :List[str] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCamelCase__ :Tuple = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
97
0
"""simple docstring""" def snake_case_ ( A_ : int, A_ : list[int], A_ : int ): '''simple docstring''' def count_of_possible_combinations(A_ : int ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(A_ ) def snake_case_ ( A_ : int, A_ : list[int], A_ : int ): '''simple docstring''' def count_of_possible_combinations_with_dp_array( A_ : int, A_ : list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] _lowerCamelCase : List[Any] = sum( count_of_possible_combinations_with_dp_array(target - item, A_ ) for item in array ) _lowerCamelCase : Optional[Any] = answer return answer _lowerCamelCase : Optional[Any] = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(A_, A_ ) def snake_case_ ( A_ : int, A_ : list[int], A_ : int ): '''simple docstring''' _lowerCamelCase : List[str] = [0] * (target + 1) _lowerCamelCase : Any = 1 for i in range(1, target + 1 ): for j in range(A_ ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase__ = 3 lowerCAmelCase__ = 5 lowerCAmelCase__ = [1, 2, 5] print(combination_sum_iv(n, array, target))
175
"""simple docstring""" def snake_case_ ( A_ : int ): '''simple docstring''' return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def snake_case_ ( A_ : int ): '''simple docstring''' _lowerCamelCase : str = 0 _lowerCamelCase : Any = number while duplicate > 0: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = divmod(A_, 10 ) fact_sum += factorial(A_ ) return fact_sum == number if __name__ == "__main__": print('''Program to check whether a number is a Krisnamurthy Number or not.''') lowerCAmelCase__ = int(input('''Enter number: ''').strip()) print( F"""{number} is {"" if krishnamurthy(number) else "not "}a Krishnamurthy Number.""" )
175
1
"""simple docstring""" import os def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Tuple ): '''simple docstring''' lowerCAmelCase = len(grid[0] ) lowerCAmelCase = len(SCREAMING_SNAKE_CASE ) lowerCAmelCase = 0 lowerCAmelCase = 0 lowerCAmelCase = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(SCREAMING_SNAKE_CASE ): for j in range(n_rows - 3 ): lowerCAmelCase = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] lowerCAmelCase = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: lowerCAmelCase = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: lowerCAmelCase = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) lowerCAmelCase = max( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if max_product > largest: lowerCAmelCase = max_product return largest def UpperCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase = [] with open(os.path.dirname(SCREAMING_SNAKE_CASE ) + """/grid.txt""" ) as file: for line in file: grid.append(line.strip("""\n""" ).split(""" """ ) ) lowerCAmelCase = [[int(SCREAMING_SNAKE_CASE ) for i in grid[j]] for j in range(len(SCREAMING_SNAKE_CASE ) )] return largest_product(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(solution())
46
"""simple docstring""" from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets SCREAMING_SNAKE_CASE__ = "\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n" SCREAMING_SNAKE_CASE__ = "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n" SCREAMING_SNAKE_CASE__ = "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"pearson\": Pearson Correlation\n \"spearmanr\": Spearman Correlation\n \"matthews_correlation\": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'stsb')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n {'pearson': 1.0, 'spearmanr': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'cola')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : List[Any] ): '''simple docstring''' return float((preds == labels).mean() ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' lowerCAmelCase = simple_accuracy(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowerCAmelCase = float(fa_score(y_true=SCREAMING_SNAKE_CASE , y_pred=SCREAMING_SNAKE_CASE ) ) return { "accuracy": acc, "f1": fa, } def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Tuple ): '''simple docstring''' lowerCAmelCase = float(pearsonr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )[0] ) lowerCAmelCase = float(spearmanr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase ( datasets.Metric ): def _snake_case ( self ) -> List[str]: if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """ """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def _snake_case ( self , lowercase , lowercase ) -> Any: if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(lowercase , lowercase )} elif self.config_name == "stsb": return pearson_and_spearman(lowercase , lowercase ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(lowercase , lowercase ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(lowercase , lowercase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """ """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )
46
1
from typing import List from .keymap import KEYMAP, get_character def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" def decorator(a_ ): __A = getattr(a_ , "handle_key" , [] ) handle += [key] setattr(a_ , "handle_key" , a_ ) return func return decorator def UpperCAmelCase ( *a_ ) -> List[str]: """simple docstring""" def decorator(a_ ): __A = getattr(a_ , "handle_key" , [] ) handle += keys setattr(a_ , "handle_key" , a_ ) return func return decorator class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __new__( cls : Optional[int] ,A : Dict ,A : Union[str, Any] ,A : int ): __A = super().__new__(cls ,A ,A ,A ) if not hasattr(A ,"key_handler" ): setattr(A ,"key_handler" ,{} ) setattr(A ,"handle_input" ,KeyHandler.handle_input ) for value in attrs.values(): __A = getattr(A ,"handle_key" ,[] ) for key in handled_keys: __A = value return new_cls @staticmethod def UpperCamelCase_ ( cls : List[Any] ): __A = get_character() if char != KEYMAP["undefined"]: __A = ord(A ) __A = cls.key_handler.get(A ) if handler: __A = char return handler(cls ) else: return None def UpperCAmelCase ( cls ) -> int: """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
124
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) snake_case_ = Features({"text": Value("string" )} ) snake_case_ = Features({"labels": ClassLabel} ) snake_case_ = "text" snake_case_ = "labels" def UpperCamelCase_ ( self : Optional[Any] ,A : Dict ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __A = copy.deepcopy(self ) __A = self.label_schema.copy() __A = features[self.label_column] __A = label_schema return task_template @property def UpperCamelCase_ ( self : Dict ): return { self.text_column: "text", self.label_column: "labels", }
124
1
"""simple docstring""" import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.esm.modeling_esmfold import EsmForProteinFolding class __lowerCamelCase : '''simple docstring''' def __init__( self : str , a_ : Union[str, Any] , a_ : str=13 , a_ : int=7 , a_ : Optional[Any]=False , a_ : Dict=True , a_ : int=False , a_ : List[str]=False , a_ : List[Any]=19 , a_ : Optional[Any]=32 , a_ : Union[str, Any]=5 , a_ : List[Any]=4 , a_ : Any=37 , a_ : List[Any]="gelu" , a_ : Tuple=0.1 , a_ : Dict=0.1 , a_ : Dict=5_12 , a_ : str=16 , a_ : str=2 , a_ : List[Any]=0.02 , a_ : Any=3 , a_ : List[str]=4 , a_ : Optional[Any]=None , ): lowerCAmelCase_ : int = parent lowerCAmelCase_ : str = batch_size lowerCAmelCase_ : List[str] = seq_length lowerCAmelCase_ : int = is_training lowerCAmelCase_ : Dict = use_input_mask lowerCAmelCase_ : Optional[Any] = use_token_type_ids lowerCAmelCase_ : int = use_labels lowerCAmelCase_ : str = vocab_size lowerCAmelCase_ : Dict = hidden_size lowerCAmelCase_ : str = num_hidden_layers lowerCAmelCase_ : Any = num_attention_heads lowerCAmelCase_ : List[str] = intermediate_size lowerCAmelCase_ : Optional[int] = hidden_act lowerCAmelCase_ : List[str] = hidden_dropout_prob lowerCAmelCase_ : Tuple = attention_probs_dropout_prob lowerCAmelCase_ : int = max_position_embeddings lowerCAmelCase_ : str = type_vocab_size lowerCAmelCase_ : str = type_sequence_label_size lowerCAmelCase_ : int = initializer_range lowerCAmelCase_ : Tuple = num_labels lowerCAmelCase_ : Optional[Any] = num_choices lowerCAmelCase_ : str = scope def lowerCamelCase ( self : Union[str, Any] ): lowerCAmelCase_ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase_ : str = None if self.use_input_mask: lowerCAmelCase_ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase_ : Optional[int] = None lowerCAmelCase_ : Union[str, Any] = None lowerCAmelCase_ : Dict = None if self.use_labels: lowerCAmelCase_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase_ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase_ : List[Any] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase ( self : List[Any] ): lowerCAmelCase_ : Tuple = EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , 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 , is_folding_model=a_ , esmfold_config={"trunk": {"num_blocks": 2}, "fp16_esm": False} , ) return config def lowerCamelCase ( self : List[str] , a_ : Optional[Any] , a_ : str , a_ : str , a_ : int , a_ : List[str] , a_ : List[str] ): lowerCAmelCase_ : Union[str, Any] = EsmForProteinFolding(config=a_ ).float() model.to(a_ ) model.eval() lowerCAmelCase_ : Union[str, Any] = model(a_ , attention_mask=a_ ) lowerCAmelCase_ : int = model(a_ ) lowerCAmelCase_ : Optional[int] = model(a_ ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def lowerCamelCase ( self : Dict ): lowerCAmelCase_ : Any = self.prepare_config_and_inputs() ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) : str = config_and_inputs lowerCAmelCase_ : int = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __lowerCamelCase ( A__ , A__ , unittest.TestCase ): '''simple docstring''' a_ : Optional[int] = False a_ : Union[str, Any] = (EsmForProteinFolding,) if is_torch_available() else () a_ : int = () a_ : Union[str, Any] = {} if is_torch_available() else {} a_ : Union[str, Any] = False def lowerCamelCase ( self : List[str] ): lowerCAmelCase_ : Optional[int] = EsmFoldModelTester(self ) lowerCAmelCase_ : Optional[int] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def lowerCamelCase ( self : str ): self.config_tester.run_common_tests() def lowerCamelCase ( self : Union[str, Any] ): lowerCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) @unittest.skip("Does not support attention outputs" ) def lowerCamelCase ( self : Any ): pass @unittest.skip def lowerCamelCase ( self : Tuple ): pass @unittest.skip("Esm does not support embedding resizing" ) def lowerCamelCase ( self : Union[str, Any] ): pass @unittest.skip("Esm does not support embedding resizing" ) def lowerCamelCase ( self : List[str] ): pass @unittest.skip("ESMFold does not support passing input embeds!" ) def lowerCamelCase ( self : Tuple ): pass @unittest.skip("ESMFold does not support head pruning." ) def lowerCamelCase ( self : List[str] ): pass @unittest.skip("ESMFold does not support head pruning." ) def lowerCamelCase ( self : Optional[Any] ): pass @unittest.skip("ESMFold does not support head pruning." ) def lowerCamelCase ( self : Optional[int] ): pass @unittest.skip("ESMFold does not support head pruning." ) def lowerCamelCase ( self : Any ): pass @unittest.skip("ESMFold does not support head pruning." ) def lowerCamelCase ( self : Any ): pass @unittest.skip("ESMFold does not output hidden states in the normal way." ) def lowerCamelCase ( self : Optional[Any] ): pass @unittest.skip("ESMfold does not output hidden states in the normal way." ) def lowerCamelCase ( self : List[Any] ): pass @unittest.skip("ESMFold only has one output format." ) def lowerCamelCase ( self : Dict ): pass @unittest.skip("This test doesn't work for ESMFold and doesn't test core functionality" ) def lowerCamelCase ( self : Any ): pass @unittest.skip("ESMFold does not support input chunking." ) def lowerCamelCase ( self : Any ): pass @unittest.skip("ESMFold doesn't respect you and it certainly doesn't respect your initialization arguments." ) def lowerCamelCase ( self : Dict ): pass @unittest.skip("ESMFold doesn't support torchscript compilation." ) def lowerCamelCase ( self : int ): pass @unittest.skip("ESMFold doesn't support torchscript compilation." ) def lowerCamelCase ( self : Union[str, Any] ): pass @unittest.skip("ESMFold doesn't support torchscript compilation." ) def lowerCamelCase ( self : Any ): pass @unittest.skip("ESMFold doesn't support data parallel." ) def lowerCamelCase ( self : Tuple ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def lowerCamelCase ( self : Optional[int] ): pass @require_torch class __lowerCamelCase ( A__ ): '''simple docstring''' @slow def lowerCamelCase ( self : Tuple ): lowerCAmelCase_ : List[Any] = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1" ).float() model.eval() lowerCAmelCase_ : List[str] = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) lowerCAmelCase_ : str = model(a_ )["positions"] lowerCAmelCase_ : int = torch.tensor([2.5828, 0.7993, -10.9334] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , a_ , atol=1e-4 ) )
241
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCamelCase ( self : Optional[Any] ): lowerCAmelCase_ : Optional[int] = 1 lowerCAmelCase_ : int = 3 lowerCAmelCase_ : Dict = (32, 32) lowerCAmelCase_ : List[Any] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(a_ ) return image @property def lowerCamelCase ( self : List[Any] ): torch.manual_seed(0 ) lowerCAmelCase_ : Union[str, Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def lowerCamelCase ( self : Tuple ): torch.manual_seed(0 ) lowerCAmelCase_ : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def lowerCamelCase ( self : List[str] ): torch.manual_seed(0 ) lowerCAmelCase_ : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModel(a_ ) @property def lowerCamelCase ( self : Union[str, Any] ): def extract(*a_ : Tuple , **a_ : Tuple ): class __lowerCamelCase : '''simple docstring''' def __init__( self : Union[str, Any] ): lowerCAmelCase_ : List[str] = torch.ones([0] ) def lowerCamelCase ( self : str , a_ : Optional[int] ): self.pixel_values.to(a_ ) return self return Out() return extract def lowerCamelCase ( self : List[str] ): lowerCAmelCase_ : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase_ : List[Any] = self.dummy_cond_unet lowerCAmelCase_ : List[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , ) lowerCAmelCase_ : List[Any] = self.dummy_vae lowerCAmelCase_ : List[str] = self.dummy_text_encoder lowerCAmelCase_ : List[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk lowerCAmelCase_ : Optional[Any] = StableDiffusionPipeline( unet=a_ , scheduler=a_ , vae=a_ , text_encoder=a_ , tokenizer=a_ , safety_checker=a_ , feature_extractor=self.dummy_extractor , ) lowerCAmelCase_ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) lowerCAmelCase_ : str = "A painting of a squirrel eating a burger" lowerCAmelCase_ : Any = torch.Generator(device=a_ ).manual_seed(0 ) lowerCAmelCase_ : Union[str, Any] = sd_pipe([prompt] , generator=a_ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) lowerCAmelCase_ : str = output.images lowerCAmelCase_ : Dict = torch.Generator(device=a_ ).manual_seed(0 ) lowerCAmelCase_ : str = sd_pipe( [prompt] , generator=a_ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=a_ , )[0] lowerCAmelCase_ : str = image[0, -3:, -3:, -1] lowerCAmelCase_ : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCAmelCase_ : Any = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864] ) 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 : List[Any] ): lowerCAmelCase_ : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase_ : Union[str, Any] = self.dummy_cond_unet lowerCAmelCase_ : Any = PNDMScheduler(skip_prk_steps=a_ ) lowerCAmelCase_ : List[Any] = self.dummy_vae lowerCAmelCase_ : List[str] = self.dummy_text_encoder lowerCAmelCase_ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk lowerCAmelCase_ : List[str] = StableDiffusionPipeline( unet=a_ , scheduler=a_ , vae=a_ , text_encoder=a_ , tokenizer=a_ , safety_checker=a_ , feature_extractor=self.dummy_extractor , ) lowerCAmelCase_ : Optional[Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) lowerCAmelCase_ : Optional[Any] = "A painting of a squirrel eating a burger" lowerCAmelCase_ : List[Any] = torch.Generator(device=a_ ).manual_seed(0 ) lowerCAmelCase_ : Any = sd_pipe([prompt] , generator=a_ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) lowerCAmelCase_ : Union[str, Any] = output.images lowerCAmelCase_ : List[str] = torch.Generator(device=a_ ).manual_seed(0 ) lowerCAmelCase_ : Optional[int] = sd_pipe( [prompt] , generator=a_ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=a_ , )[0] lowerCAmelCase_ : Dict = image[0, -3:, -3:, -1] lowerCAmelCase_ : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCAmelCase_ : str = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993] ) 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 : Tuple ): lowerCAmelCase_ : Tuple = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=a_ ) assert isinstance(a_ , a_ ) assert isinstance(pipe.scheduler , a_ ) assert pipe.safety_checker is None lowerCAmelCase_ : str = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(a_ ) lowerCAmelCase_ : List[str] = StableDiffusionPipeline.from_pretrained(a_ ) # sanity check that the pipeline still works assert pipe.safety_checker is None lowerCAmelCase_ : Any = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def lowerCamelCase ( self : Tuple ): lowerCAmelCase_ : str = self.dummy_cond_unet lowerCAmelCase_ : str = PNDMScheduler(skip_prk_steps=a_ ) lowerCAmelCase_ : Tuple = self.dummy_vae lowerCAmelCase_ : Dict = self.dummy_text_encoder lowerCAmelCase_ : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 lowerCAmelCase_ : int = unet.half() lowerCAmelCase_ : Dict = vae.half() lowerCAmelCase_ : List[Any] = bert.half() # make sure here that pndm scheduler skips prk lowerCAmelCase_ : Optional[int] = StableDiffusionPipeline( unet=a_ , scheduler=a_ , vae=a_ , text_encoder=a_ , tokenizer=a_ , safety_checker=a_ , feature_extractor=self.dummy_extractor , ) lowerCAmelCase_ : Optional[Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) lowerCAmelCase_ : List[str] = "A painting of a squirrel eating a burger" lowerCAmelCase_ : Optional[Any] = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self : List[str] ): lowerCAmelCase_ : Union[str, Any] = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=a_ ) lowerCAmelCase_ : Any = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) lowerCAmelCase_ : str = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) lowerCAmelCase_ : List[str] = ( "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle" " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with" " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and" " children from bahnhof zoo, detailed " ) lowerCAmelCase_ : Optional[int] = 40_03_66_03_46 lowerCAmelCase_ : List[Any] = 7 # without safety guidance (sld_guidance_scale = 0) lowerCAmelCase_ : Union[str, Any] = torch.manual_seed(a_ ) lowerCAmelCase_ : Union[str, Any] = sd_pipe( [prompt] , generator=a_ , guidance_scale=a_ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) lowerCAmelCase_ : Union[str, Any] = output.images lowerCAmelCase_ : Optional[Any] = image[0, -3:, -3:, -1] lowerCAmelCase_ : Union[str, Any] = [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) lowerCAmelCase_ : List[str] = torch.manual_seed(a_ ) lowerCAmelCase_ : Any = sd_pipe( [prompt] , generator=a_ , guidance_scale=a_ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) lowerCAmelCase_ : Optional[Any] = output.images lowerCAmelCase_ : Optional[int] = image[0, -3:, -3:, -1] lowerCAmelCase_ : Optional[Any] = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCamelCase ( self : str ): lowerCAmelCase_ : Any = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=a_ ) lowerCAmelCase_ : Union[str, Any] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) lowerCAmelCase_ : Optional[Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) lowerCAmelCase_ : Union[str, Any] = "padme amidala taking a bath artwork, safe for work, no nudity" lowerCAmelCase_ : Union[str, Any] = 27_34_97_17_55 lowerCAmelCase_ : Union[str, Any] = 7 lowerCAmelCase_ : str = torch.manual_seed(a_ ) lowerCAmelCase_ : Dict = sd_pipe( [prompt] , generator=a_ , guidance_scale=a_ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) lowerCAmelCase_ : Any = output.images lowerCAmelCase_ : int = image[0, -3:, -3:, -1] lowerCAmelCase_ : int = [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 lowerCAmelCase_ : Optional[int] = torch.manual_seed(a_ ) lowerCAmelCase_ : Union[str, Any] = sd_pipe( [prompt] , generator=a_ , guidance_scale=a_ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) lowerCAmelCase_ : Any = output.images lowerCAmelCase_ : Optional[int] = image[0, -3:, -3:, -1] lowerCAmelCase_ : Tuple = [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCamelCase ( self : Union[str, Any] ): lowerCAmelCase_ : Dict = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) lowerCAmelCase_ : Any = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) lowerCAmelCase_ : Tuple = ( "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c." " leyendecker" ) lowerCAmelCase_ : List[Any] = 10_44_35_52_34 lowerCAmelCase_ : Dict = 12 lowerCAmelCase_ : int = torch.manual_seed(a_ ) lowerCAmelCase_ : List[str] = sd_pipe( [prompt] , generator=a_ , guidance_scale=a_ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) lowerCAmelCase_ : int = output.images lowerCAmelCase_ : int = image[0, -3:, -3:, -1] lowerCAmelCase_ : int = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 lowerCAmelCase_ : int = torch.manual_seed(a_ ) lowerCAmelCase_ : Any = sd_pipe( [prompt] , generator=a_ , guidance_scale=a_ , num_inference_steps=50 , output_type="np" , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) lowerCAmelCase_ : Optional[Any] = output.images lowerCAmelCase_ : Optional[Any] = image[0, -3:, -3:, -1] lowerCAmelCase_ : str = np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
241
1
"""simple docstring""" from math import pi, sqrt def lowerCamelCase_ ( _lowerCamelCase ): if num <= 0: raise ValueError('math domain error' ) if num > 171.5: raise OverflowError('math range error' ) elif num - int(_lowerCamelCase ) not in (0, 0.5): raise NotImplementedError('num must be an integer or a half-integer' ) elif num == 0.5: return sqrt(_lowerCamelCase ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def lowerCamelCase_ ( ): assert gamma(0.5 ) == sqrt(_lowerCamelCase ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() A_ : Any = 1.0 while num: A_ : Tuple = float(input("Gamma of: ")) print(f"gamma({num}) = {gamma(num)}") print("\nEnter 0 to exit...")
365
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class a_ ( snake_case_ ): '''simple docstring''' @staticmethod @abstractmethod def a__ (lowerCamelCase_ ): '''simple docstring''' raise NotImplementedError() @abstractmethod def a__ (self ): '''simple docstring''' raise NotImplementedError()
316
0
"""simple docstring""" from collections.abc import Sequence def _A ( lowercase , lowercase = False ): """simple docstring""" if not arr: return 0 a =0 if allow_empty_subarrays else float('''-inf''' ) a =0.0 for num in arr: a =max(0 if allow_empty_subarrays else num , curr_sum + num ) a =max(lowercase , lowercase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowerCamelCase_ : List[str] = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F'{max_subarray_sum(nums) = }')
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
1
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): @register_to_config def __init__( self, lowerCAmelCase__ = 768, ) -> Optional[Any]: super().__init__() snake_case_ = nn.Parameter(torch.zeros(1, lowerCAmelCase__)) snake_case_ = nn.Parameter(torch.ones(1, lowerCAmelCase__)) def a_ ( self, lowerCAmelCase__ = None, lowerCAmelCase__ = None, ) -> Optional[int]: snake_case_ = nn.Parameter(self.mean.to(lowerCAmelCase__).to(lowerCAmelCase__)) snake_case_ = nn.Parameter(self.std.to(lowerCAmelCase__).to(lowerCAmelCase__)) return self def a_ ( self, lowerCAmelCase__) -> List[str]: snake_case_ = (embeds - self.mean) * 1.0 / self.std return embeds def a_ ( self, lowerCAmelCase__) -> Tuple: snake_case_ = (embeds * self.std) + self.mean return embeds
312
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase = {'''configuration_mmbt''': ['''MMBTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase = ['''MMBTForClassification''', '''MMBTModel''', '''ModalEmbeddings'''] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
312
1
def UpperCAmelCase_ ( __snake_case = 4000000 ) -> int: """simple docstring""" _lowercase =[] _lowercase , _lowercase =0, 1 while b <= n: if b % 2 == 0: even_fibs.append(__snake_case ) _lowercase , _lowercase =b, a + b return sum(__snake_case ) if __name__ == "__main__": print(f'''{solution() = }''')
5
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase__ : '''simple docstring''' def __init__( self :List[Any] , a :Dict , a :Any=3 , a :Any=3_2 , a :Optional[Any]=3 , a :str=1_0 , a :Union[str, Any]=[1_0, 2_0, 3_0, 4_0] , a :Optional[Any]=[1, 1, 2, 1] , a :Optional[Any]=True , a :Dict=True , a :Tuple="relu" , a :List[str]=3 , a :Tuple=None , ) -> Tuple: __UpperCamelCase : Optional[Any] = parent __UpperCamelCase : Dict = batch_size __UpperCamelCase : int = image_size __UpperCamelCase : Dict = num_channels __UpperCamelCase : Optional[int] = embeddings_size __UpperCamelCase : List[Any] = hidden_sizes __UpperCamelCase : Optional[Any] = depths __UpperCamelCase : Optional[int] = is_training __UpperCamelCase : Union[str, Any] = use_labels __UpperCamelCase : Optional[int] = hidden_act __UpperCamelCase : Tuple = num_labels __UpperCamelCase : Tuple = scope __UpperCamelCase : Dict = len(a ) def _lowerCamelCase ( self :Optional[int] ) -> Any: __UpperCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCamelCase : List[str] = None if self.use_labels: __UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_labels ) __UpperCamelCase : List[Any] = self.get_config() return config, pixel_values, labels def _lowerCamelCase ( self :Union[str, Any] ) -> int: return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _lowerCamelCase ( self :List[Any] , a :Dict , a :int , a :Optional[Any] ) -> Tuple: __UpperCamelCase : str = TFResNetModel(config=a ) __UpperCamelCase : Union[str, Any] = model(a ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def _lowerCamelCase ( self :Union[str, Any] , a :Optional[int] , a :List[str] , a :Optional[Any] ) -> Any: __UpperCamelCase : str = self.num_labels __UpperCamelCase : Optional[int] = TFResNetForImageClassification(a ) __UpperCamelCase : List[str] = model(a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowerCamelCase ( self :Optional[int] ) -> List[str]: __UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Union[str, Any] = config_and_inputs __UpperCamelCase : List[str] = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class lowerCamelCase__ ( __lowercase , __lowercase , unittest.TestCase): '''simple docstring''' _A = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _A = ( {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification} if is_tf_available() else {} ) _A = False _A = False _A = False _A = False _A = False def _lowerCamelCase ( self :int ) -> List[str]: __UpperCamelCase : Union[str, Any] = TFResNetModelTester(self ) __UpperCamelCase : List[Any] = ConfigTester(self , config_class=a , has_text_modality=a ) def _lowerCamelCase ( self :int ) -> Dict: 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 :str ) -> Optional[Any]: return @unittest.skip(reason="ResNet does not use inputs_embeds" ) def _lowerCamelCase ( self :Tuple ) -> Tuple: pass @unittest.skip(reason="ResNet does not support input and output embeddings" ) def _lowerCamelCase ( self :List[Any] ) -> List[str]: pass def _lowerCamelCase ( self :Optional[int] ) -> Tuple: __UpperCamelCase , __UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase : Dict = model_class(a ) __UpperCamelCase : Union[str, Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase : Dict = [*signature.parameters.keys()] __UpperCamelCase : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , a ) def _lowerCamelCase ( self :List[str] ) -> List[str]: __UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _lowerCamelCase ( self :Optional[Any] ) -> Tuple: def check_hidden_states_output(a :Optional[Any] , a :Optional[int] , a :List[str] ): __UpperCamelCase : int = model_class(a ) __UpperCamelCase : int = model(**self._prepare_for_class(a , a ) ) __UpperCamelCase : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __UpperCamelCase : Optional[int] = self.model_tester.num_stages self.assertEqual(len(a ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __UpperCamelCase , __UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase : str = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: __UpperCamelCase : int = layer_type __UpperCamelCase : int = True check_hidden_states_output(a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCamelCase : int = True check_hidden_states_output(a , a , a ) def _lowerCamelCase ( self :Union[str, Any] ) -> Dict: __UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a ) @slow def _lowerCamelCase ( self :Dict ) -> Dict: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Optional[Any] = TFResNetModel.from_pretrained(a ) self.assertIsNotNone(a ) def _SCREAMING_SNAKE_CASE ( ) -> int: '''simple docstring''' __UpperCamelCase : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_tf @require_vision class lowerCamelCase__ ( unittest.TestCase): '''simple docstring''' @cached_property def _lowerCamelCase ( self :Optional[Any] ) -> Tuple: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _lowerCamelCase ( self :Optional[int] ) -> Optional[int]: __UpperCamelCase : int = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __UpperCamelCase : List[Any] = self.default_image_processor __UpperCamelCase : List[str] = prepare_img() __UpperCamelCase : List[str] = image_processor(images=a , return_tensors="tf" ) # forward pass __UpperCamelCase : Dict = model(**a ) # verify the logits __UpperCamelCase : Dict = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , a ) __UpperCamelCase : Union[str, Any] = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4 ) )
232
0
'''simple docstring''' import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class a_ ( _lowerCAmelCase , unittest.TestCase ): __A = CTRLTokenizer __A = False __A = False def lowercase__ ( self : List[str] ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowercase_ :Optional[int] = ["adapt", "re@@", "a@@", "apt", "c@@", "t", "<unk>"] lowercase_ :Optional[Any] = dict(zip(lowercase , range(len(lowercase ) ) ) ) lowercase_ :Optional[int] = ["#version: 0.2", "a p", "ap t</w>", "r e", "a d", "ad apt</w>", ""] lowercase_ :Tuple = {"unk_token": "<unk>"} lowercase_ :List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowercase_ :Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowercase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowercase ) ) def lowercase__ ( self : int , **lowercase : str ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **lowercase ) def lowercase__ ( self : List[str] , lowercase : Dict ): """simple docstring""" lowercase_ :Union[str, Any] = "adapt react readapt apt" lowercase_ :List[Any] = "adapt react readapt apt" return input_text, output_text def lowercase__ ( self : Dict ): """simple docstring""" lowercase_ :Dict = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowercase_ :List[Any] = "adapt react readapt apt" lowercase_ :str = "adapt re@@ a@@ c@@ t re@@ adapt apt".split() lowercase_ :List[str] = tokenizer.tokenize(lowercase ) self.assertListEqual(lowercase , lowercase ) lowercase_ :str = tokens + [tokenizer.unk_token] lowercase_ :List[str] = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase ) , lowercase )
367
'''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 a_ ( _lowerCAmelCase ): def __init__( self : Any , lowercase : int , lowercase : Union[str, Any]=13 , lowercase : List[str]=7 , lowercase : List[str]=True , lowercase : int=True , lowercase : Tuple=True , lowercase : int=True , lowercase : List[Any]=99 , lowercase : Optional[int]=32 , lowercase : Dict=5 , lowercase : Optional[int]=4 , lowercase : List[str]=37 , lowercase : Tuple="gelu" , lowercase : List[Any]=0.1 , lowercase : Tuple=0.1 , lowercase : List[str]=512 , lowercase : str=16 , lowercase : Tuple=2 , lowercase : List[Any]=0.02 , lowercase : Dict=False , lowercase : Dict=True , lowercase : int="None" , lowercase : Optional[Any]=3 , lowercase : Dict=4 , lowercase : List[Any]=None , ): """simple docstring""" lowercase_ :int = parent lowercase_ :str = batch_size lowercase_ :Tuple = seq_length lowercase_ :Union[str, Any] = is_training lowercase_ :Dict = use_input_mask lowercase_ :Any = use_token_type_ids lowercase_ :Tuple = use_labels lowercase_ :Dict = vocab_size lowercase_ :Tuple = hidden_size lowercase_ :Union[str, Any] = num_hidden_layers lowercase_ :int = num_attention_heads lowercase_ :List[Any] = intermediate_size lowercase_ :Tuple = hidden_act lowercase_ :str = hidden_dropout_prob lowercase_ :Any = attention_probs_dropout_prob lowercase_ :List[Any] = max_position_embeddings lowercase_ :Union[str, Any] = type_vocab_size lowercase_ :Union[str, Any] = type_sequence_label_size lowercase_ :Any = initializer_range lowercase_ :List[Any] = num_labels lowercase_ :str = num_choices lowercase_ :Optional[Any] = relative_attention lowercase_ :Tuple = position_biased_input lowercase_ :Union[str, Any] = pos_att_type lowercase_ :Tuple = scope def lowercase__ ( self : Dict ): """simple docstring""" lowercase_ :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase_ :Union[str, Any] = None if self.use_input_mask: lowercase_ :int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) lowercase_ :List[Any] = None if self.use_token_type_ids: lowercase_ :Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase_ :str = None lowercase_ :Union[str, Any] = None lowercase_ :List[str] = None if self.use_labels: lowercase_ :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase_ :Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase_ :str = ids_tensor([self.batch_size] , self.num_choices ) lowercase_ :Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase__ ( self : Optional[Any] ): """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 lowercase__ ( self : Optional[int] ): """simple docstring""" lowercase_ :Dict = self.get_config() lowercase_ :Optional[Any] = 300 return config def lowercase__ ( self : Optional[Any] , lowercase : Dict ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def lowercase__ ( self : Optional[Any] , lowercase : Union[str, Any] , lowercase : List[Any] , lowercase : List[Any] , lowercase : Tuple , lowercase : str , lowercase : Optional[Any] , lowercase : Optional[int] ): """simple docstring""" lowercase_ :str = DebertaModel(config=lowercase ) model.to(lowercase ) model.eval() lowercase_ :Optional[int] = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase )[0] lowercase_ :Union[str, Any] = model(lowercase , token_type_ids=lowercase )[0] lowercase_ :Dict = model(lowercase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def lowercase__ ( self : Dict , lowercase : Union[str, Any] , lowercase : Optional[int] , lowercase : Tuple , lowercase : Dict , lowercase : Dict , lowercase : str , lowercase : Tuple ): """simple docstring""" lowercase_ :Dict = DebertaForMaskedLM(config=lowercase ) model.to(lowercase ) model.eval() lowercase_ :Optional[Any] = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase__ ( self : Optional[int] , lowercase : Union[str, Any] , lowercase : Union[str, Any] , lowercase : Union[str, Any] , lowercase : Dict , lowercase : List[Any] , lowercase : int , lowercase : Dict ): """simple docstring""" lowercase_ :Dict = self.num_labels lowercase_ :int = DebertaForSequenceClassification(lowercase ) model.to(lowercase ) model.eval() lowercase_ :Union[str, Any] = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(lowercase ) def lowercase__ ( self : List[Any] , lowercase : List[str] , lowercase : Tuple , lowercase : Optional[Any] , lowercase : Optional[int] , lowercase : Union[str, Any] , lowercase : Dict , lowercase : int ): """simple docstring""" lowercase_ :List[str] = self.num_labels lowercase_ :Optional[int] = DebertaForTokenClassification(config=lowercase ) model.to(lowercase ) model.eval() lowercase_ :Dict = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase__ ( self : Union[str, Any] , lowercase : Tuple , lowercase : Any , lowercase : List[Any] , lowercase : List[Any] , lowercase : Union[str, Any] , lowercase : Optional[int] , lowercase : List[Any] ): """simple docstring""" lowercase_ :Any = DebertaForQuestionAnswering(config=lowercase ) model.to(lowercase ) model.eval() lowercase_ :List[Any] = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , start_positions=lowercase , end_positions=lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowercase__ ( self : Any ): """simple docstring""" lowercase_ :Optional[int] = self.prepare_config_and_inputs() ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) :List[str] = config_and_inputs lowercase_ :Tuple = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class a_ ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): __A = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) __A = ( { "feature-extraction": DebertaModel, "fill-mask": DebertaForMaskedLM, "question-answering": DebertaForQuestionAnswering, "text-classification": DebertaForSequenceClassification, "token-classification": DebertaForTokenClassification, "zero-shot": DebertaForSequenceClassification, } if is_torch_available() else {} ) __A = True __A = False __A = False __A = False __A = False def lowercase__ ( self : Optional[int] ): """simple docstring""" lowercase_ :List[Any] = DebertaModelTester(self ) lowercase_ :str = ConfigTester(self , config_class=lowercase , hidden_size=37 ) def lowercase__ ( self : Union[str, Any] ): """simple docstring""" self.config_tester.run_common_tests() def lowercase__ ( self : Union[str, Any] ): """simple docstring""" lowercase_ :str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*lowercase ) def lowercase__ ( self : Union[str, Any] ): """simple docstring""" lowercase_ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*lowercase ) def lowercase__ ( self : Union[str, Any] ): """simple docstring""" lowercase_ :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*lowercase ) def lowercase__ ( self : int ): """simple docstring""" lowercase_ :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*lowercase ) def lowercase__ ( self : Tuple ): """simple docstring""" lowercase_ :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*lowercase ) @slow def lowercase__ ( self : Optional[int] ): """simple docstring""" for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase_ :Tuple = DebertaModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_torch @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): @unittest.skip(reason="Model not available yet" ) def lowercase__ ( self : Dict ): """simple docstring""" pass @slow def lowercase__ ( self : List[Any] ): """simple docstring""" lowercase_ :Optional[Any] = DebertaModel.from_pretrained("microsoft/deberta-base" ) lowercase_ :Dict = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) lowercase_ :Optional[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): lowercase_ :Optional[int] = model(lowercase , attention_mask=lowercase )[0] # compare the actual values for a slice. lowercase_ :List[Any] = torch.tensor( [[[-0.59_86, -0.80_55, -0.84_62], [1.44_84, -0.93_48, -0.80_59], [0.31_23, 0.00_32, -1.41_31]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowercase , atol=1e-4 ) , F'{output[:, 1:4, 1:4]}' )
147
0
"""simple docstring""" def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' if not isinstance(A_, A_ ): raise ValueError('''iterations must be defined as integers''' ) if not isinstance(A_, A_ ) or not number >= 1: raise ValueError( '''starting number must be and integer and be more than 0''' ) if not iterations >= 1: raise ValueError('''Iterations must be done more than 0 times to play FizzBuzz''' ) _lowerCamelCase : Optional[int] = '''''' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(A_ ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
72
"""simple docstring""" def snake_case_ ( A_ : list[list] ): '''simple docstring''' _lowerCamelCase : Optional[int] = current_set.copy() for row_index, row in enumerate(A_ ): _lowerCamelCase : Tuple = row[0] for column_index, column in enumerate(A_ ): if magnitude == 0: _lowerCamelCase : List[Any] = column continue _lowerCamelCase : List[Any] = column / magnitude # Subtract to cancel term _lowerCamelCase : Union[str, Any] = current_set[0] _lowerCamelCase : Dict = [first_row] _lowerCamelCase : str = current_set[1::] for row in current_set: _lowerCamelCase : Union[str, Any] = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(A_ ) continue for column_index in range(len(A_ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(A_ ) # Create next recursion iteration set if len(final_set[0] ) != 3: _lowerCamelCase : Any = final_set[0] _lowerCamelCase : Any = [] _lowerCamelCase : Optional[int] = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) _lowerCamelCase : Dict = simplify(A_ ) for i in range(len(A_ ) ): resultant[i].insert(0, current_first_column[i] ) resultant.insert(0, A_ ) _lowerCamelCase : Tuple = resultant return final_set def snake_case_ ( A_ : list[list] ): '''simple docstring''' if len(A_ ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) _lowerCamelCase : Dict = len(A_ ) + 1 if any(len(A_ ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(A_, (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(A_ ) == 1: return [equations[0][-1] / equations[0][0]] _lowerCamelCase : Optional[Any] = equations.copy() if any(0 in row for row in data_set ): _lowerCamelCase : str = data_set.copy() _lowerCamelCase : List[Any] = [] for row_index, row in enumerate(A_ ): if 0 not in row: _lowerCamelCase : Union[str, Any] = data_set.pop(A_ ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0, A_ ) _lowerCamelCase : List[str] = data_set.copy() _lowerCamelCase : int = simplify(A_ ) _lowerCamelCase : int = simplified[::-1] _lowerCamelCase : list = [] for row in simplified: _lowerCamelCase : Tuple = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue _lowerCamelCase : Optional[Any] = row.copy()[: len(A_ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(A_ ) == 0: solutions.append(0 ) continue _lowerCamelCase : Tuple = temp_row[1::] _lowerCamelCase : Tuple = temp_row[::-1] for column_index, column in enumerate(A_ ): current_solution -= column * solutions[column_index] solutions.append(A_ ) _lowerCamelCase : Optional[int] = [] for item in solutions: final.append(float(round(A_, 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase__ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
72
1
import os from distutils.util import strtobool def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[str] ) -> List[Any]: for e in env_keys: __lowerCAmelCase : str = int(os.environ.get(SCREAMING_SNAKE_CASE , -1 ) ) if val >= 0: return val return default def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any]=False ) -> List[str]: __lowerCAmelCase : Optional[Any] = os.environ.get(SCREAMING_SNAKE_CASE , str(SCREAMING_SNAKE_CASE ) ) return strtobool(SCREAMING_SNAKE_CASE ) == 1 # As its name indicates `strtobool` actually returns an int... def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any]="no" ) -> Optional[Any]: __lowerCAmelCase : List[str] = os.environ.get(SCREAMING_SNAKE_CASE , str(SCREAMING_SNAKE_CASE ) ) return value
350
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'microsoft/unispeech-sat-base-100h-libri-ft': ( 'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json' ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class snake_case_ ( __lowercase ): A_ = 'unispeech-sat' def __init__( self : str , _snake_case : List[Any]=32 , _snake_case : Union[str, Any]=768 , _snake_case : Tuple=12 , _snake_case : Optional[int]=12 , _snake_case : Optional[Any]=3072 , _snake_case : Tuple="gelu" , _snake_case : int=0.1 , _snake_case : List[Any]=0.1 , _snake_case : Union[str, Any]=0.1 , _snake_case : str=0.0 , _snake_case : List[str]=0.0 , _snake_case : int=0.1 , _snake_case : Optional[Any]=0.1 , _snake_case : Optional[Any]=0.02 , _snake_case : int=1E-5 , _snake_case : Dict="group" , _snake_case : Optional[Any]="gelu" , _snake_case : Optional[Any]=(512, 512, 512, 512, 512, 512, 512) , _snake_case : int=(5, 2, 2, 2, 2, 2, 2) , _snake_case : int=(10, 3, 3, 3, 3, 2, 2) , _snake_case : Any=False , _snake_case : Optional[Any]=128 , _snake_case : Tuple=16 , _snake_case : str=False , _snake_case : Dict=True , _snake_case : Tuple=0.05 , _snake_case : str=10 , _snake_case : Tuple=2 , _snake_case : List[Any]=0.0 , _snake_case : str=10 , _snake_case : Any=0 , _snake_case : List[Any]=320 , _snake_case : Union[str, Any]=2 , _snake_case : Dict=0.1 , _snake_case : Dict=100 , _snake_case : Union[str, Any]=256 , _snake_case : int=256 , _snake_case : Union[str, Any]=0.1 , _snake_case : Optional[Any]="mean" , _snake_case : int=False , _snake_case : str=False , _snake_case : str=256 , _snake_case : List[Any]=(512, 512, 512, 512, 1500) , _snake_case : Optional[int]=(5, 3, 3, 1, 1) , _snake_case : Tuple=(1, 2, 3, 1, 1) , _snake_case : Dict=512 , _snake_case : Union[str, Any]=0 , _snake_case : List[str]=1 , _snake_case : Optional[Any]=2 , _snake_case : Optional[int]=504 , **_snake_case : Optional[int] , )->Union[str, Any]: '''simple docstring''' super().__init__(**_snake_case , pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case ) __lowerCAmelCase : Dict = hidden_size __lowerCAmelCase : List[Any] = feat_extract_norm __lowerCAmelCase : int = feat_extract_activation __lowerCAmelCase : Union[str, Any] = list(_snake_case ) __lowerCAmelCase : str = list(_snake_case ) __lowerCAmelCase : Optional[Any] = list(_snake_case ) __lowerCAmelCase : Optional[int] = conv_bias __lowerCAmelCase : Dict = num_conv_pos_embeddings __lowerCAmelCase : List[Any] = num_conv_pos_embedding_groups __lowerCAmelCase : Tuple = len(self.conv_dim ) __lowerCAmelCase : int = num_hidden_layers __lowerCAmelCase : str = intermediate_size __lowerCAmelCase : str = hidden_act __lowerCAmelCase : Any = num_attention_heads __lowerCAmelCase : Optional[int] = hidden_dropout __lowerCAmelCase : str = attention_dropout __lowerCAmelCase : int = activation_dropout __lowerCAmelCase : Union[str, Any] = feat_proj_dropout __lowerCAmelCase : List[str] = final_dropout __lowerCAmelCase : Dict = layerdrop __lowerCAmelCase : Tuple = layer_norm_eps __lowerCAmelCase : Optional[Any] = initializer_range __lowerCAmelCase : str = vocab_size __lowerCAmelCase : Optional[int] = num_clusters __lowerCAmelCase : List[Any] = do_stable_layer_norm __lowerCAmelCase : Tuple = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __lowerCAmelCase : Dict = apply_spec_augment __lowerCAmelCase : List[Any] = mask_time_prob __lowerCAmelCase : List[str] = mask_time_length __lowerCAmelCase : Dict = mask_time_min_masks __lowerCAmelCase : Tuple = mask_feature_prob __lowerCAmelCase : List[str] = mask_feature_length __lowerCAmelCase : str = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __lowerCAmelCase : Optional[int] = num_codevectors_per_group __lowerCAmelCase : List[Any] = num_codevector_groups __lowerCAmelCase : int = contrastive_logits_temperature __lowerCAmelCase : str = feat_quantizer_dropout __lowerCAmelCase : int = num_negatives __lowerCAmelCase : str = codevector_dim __lowerCAmelCase : Any = proj_codevector_dim __lowerCAmelCase : Any = diversity_loss_weight # ctc loss __lowerCAmelCase : Tuple = ctc_loss_reduction __lowerCAmelCase : Any = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. __lowerCAmelCase : Any = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __lowerCAmelCase : List[str] = list(_snake_case ) __lowerCAmelCase : List[str] = list(_snake_case ) __lowerCAmelCase : Optional[int] = list(_snake_case ) __lowerCAmelCase : Optional[int] = xvector_output_dim @property def UpperCAmelCase__ ( self : Optional[Any] )->Any: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
232
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : 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: UpperCAmelCase : Union[str, Any] = [ '''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: UpperCAmelCase : Optional[Any] = [ '''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 UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor __A =logging.get_logger(__name__) class _snake_case ( a__ ): def __init__( self , *_lowerCamelCase , **_lowerCamelCase): warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , _lowerCamelCase , ) super().__init__(*_lowerCamelCase , **_lowerCamelCase)
283
'''simple docstring''' def _UpperCamelCase ( UpperCamelCase__ = 4_0_0_0_0_0_0 ): UpperCAmelCase__ : List[str] = [0, 1] UpperCAmelCase__ : Any = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 UpperCAmelCase__ : str = 0 for j in range(len(UpperCamelCase__ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"""{solution() = }""")
283
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A : Optional[Any] = { 'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'], 'tokenization_canine': ['CanineTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[Any] = [ 'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST', 'CanineForMultipleChoice', 'CanineForQuestionAnswering', 'CanineForSequenceClassification', 'CanineForTokenClassification', 'CanineLayer', 'CanineModel', 'CaninePreTrainedModel', 'load_tf_weights_in_canine', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys A : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def a ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): '''simple docstring''' lowercase__ = ('''dense.weight''', '''attention.self.query''', '''attention.self.key''', '''attention.self.value''') lowercase__ = ( ('''layer.''', '''layer_'''), ('''word_embeddings.weight''', '''word_embeddings'''), ('''position_embeddings.weight''', '''position_embeddings'''), ('''token_type_embeddings.weight''', '''token_type_embeddings'''), ('''.''', '''/'''), ('''LayerNorm/weight''', '''LayerNorm/gamma'''), ('''LayerNorm/bias''', '''LayerNorm/beta'''), ('''weight''', '''kernel'''), ) if not os.path.isdir(lowerCamelCase_ ): os.makedirs(lowerCamelCase_ ) lowercase__ = model.state_dict() def to_tf_var_name(lowerCamelCase_ ): for patt, repl in iter(lowerCamelCase_ ): lowercase__ = name.replace(lowerCamelCase_ , lowerCamelCase_ ) return F"""bert/{name}""" def create_tf_var(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): lowercase__ = tf.dtypes.as_dtype(tensor.dtype ) lowercase__ = tf.get_variable(dtype=lowerCamelCase_ , shape=tensor.shape , name=lowerCamelCase_ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(lowerCamelCase_ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: lowercase__ = to_tf_var_name(lowerCamelCase_ ) lowercase__ = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): lowercase__ = torch_tensor.T lowercase__ = create_tf_var(tensor=lowerCamelCase_ , name=lowerCamelCase_ , session=lowerCamelCase_ ) tf.keras.backend.set_value(lowerCamelCase_ , lowerCamelCase_ ) lowercase__ = session.run(lowerCamelCase_ ) print(F"""Successfully created {tf_name}: {np.allclose(lowerCamelCase_ , lowerCamelCase_ )}""" ) lowercase__ = tf.train.Saver(tf.trainable_variables() ) saver.save(lowerCamelCase_ , os.path.join(lowerCamelCase_ , model_name.replace('''-''' , '''_''' ) + '''.ckpt''' ) ) def a ( lowerCamelCase_=None ): '''simple docstring''' lowercase__ = argparse.ArgumentParser() parser.add_argument('''--model_name''' , type=lowerCamelCase_ , required=lowerCamelCase_ , help='''model name e.g. bert-base-uncased''' ) parser.add_argument( '''--cache_dir''' , type=lowerCamelCase_ , default=lowerCamelCase_ , required=lowerCamelCase_ , help='''Directory containing pytorch model''' ) parser.add_argument('''--pytorch_model_path''' , type=lowerCamelCase_ , required=lowerCamelCase_ , help='''/path/to/<pytorch-model-name>.bin''' ) parser.add_argument('''--tf_cache_dir''' , type=lowerCamelCase_ , required=lowerCamelCase_ , help='''Directory in which to save tensorflow model''' ) lowercase__ = parser.parse_args(lowerCamelCase_ ) lowercase__ = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=lowerCamelCase_ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
207
0
def _lowercase ( _UpperCAmelCase = 4_00_00_00 ) -> int: lowerCamelCase =[0, 1] lowerCamelCase =0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 lowerCamelCase =0 for j in range(len(_UpperCAmelCase ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(F"{solution() = }")
262
import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class __A ( unittest.TestCase ): def _snake_case ( self ): lowerCamelCase =Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) lowerCamelCase =Vector() def _snake_case ( self ): lowerCamelCase =Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(UpperCAmelCase_ ) , """(0,0,0,0,0,1)""" ) def _snake_case ( self ): lowerCamelCase =Vector([1, 2, 3, 4] ) self.assertEqual(len(UpperCAmelCase_ ) , 4 ) def _snake_case ( self ): lowerCamelCase =Vector([1, 2] ) lowerCamelCase =Vector([1, 2, 3, 4, 5] ) lowerCamelCase =Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) lowerCamelCase =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 _snake_case ( self ): lowerCamelCase =Vector([1, 2, 3] ) lowerCamelCase =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 _snake_case ( self ): lowerCamelCase =Vector([1, 2, 3] ) lowerCamelCase =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 _snake_case ( self ): lowerCamelCase =Vector([1, 2, 3] ) lowerCamelCase =Vector([2, -1, 4] ) # for test of dot product lowerCamelCase =Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , """(3.0,6.0,9.0)""" ) self.assertEqual((a * b) , 0 ) def _snake_case ( self ): self.assertEqual(str(zero_vector(10 ) ).count("""0""" ) , 10 ) def _snake_case ( self ): self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , """(0,1,0)""" ) def _snake_case ( self ): lowerCamelCase =Vector([1, 2, 3] ) lowerCamelCase =Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , UpperCAmelCase_ , UpperCAmelCase_ ) ) , """(3,4,7)""" ) def _snake_case ( self ): lowerCamelCase =Vector([1, 0, 0, 0, 0, 0] ) lowerCamelCase =x.copy() self.assertEqual(str(UpperCAmelCase_ ) , str(UpperCAmelCase_ ) ) def _snake_case ( self ): lowerCamelCase =Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(UpperCAmelCase_ ) , """(0,1,0)""" ) def _snake_case ( self ): lowerCamelCase =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(UpperCAmelCase_ ) ) def _snake_case ( self ): lowerCamelCase =Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) lowerCamelCase =[[-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(UpperCAmelCase_ , UpperCAmelCase_ ) ) def _snake_case ( self ): lowerCamelCase =Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) lowerCamelCase =[[-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(UpperCAmelCase_ , UpperCAmelCase_ ) ) def _snake_case ( self ): lowerCamelCase =Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def _snake_case ( self ): lowerCamelCase =Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) lowerCamelCase =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 _snake_case ( self ): lowerCamelCase =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(UpperCAmelCase_ ) ) def _snake_case ( self ): lowerCamelCase =Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.0_1 ) def _snake_case ( self ): lowerCamelCase =Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) lowerCamelCase =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 _snake_case ( self ): lowerCamelCase =Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) lowerCamelCase =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 _snake_case ( self ): 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()
262
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[str] = { '''kssteven/ibert-roberta-base''': '''https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json''', '''kssteven/ibert-roberta-large''': '''https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json''', '''kssteven/ibert-roberta-large-mnli''': ( '''https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json''' ), } class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = 'ibert' def __init__( self , _lowerCamelCase=3_0522 , _lowerCamelCase=768 , _lowerCamelCase=12 , _lowerCamelCase=12 , _lowerCamelCase=3072 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=512 , _lowerCamelCase=2 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-12 , _lowerCamelCase=1 , _lowerCamelCase=0 , _lowerCamelCase=2 , _lowerCamelCase="absolute" , _lowerCamelCase=False , _lowerCamelCase="none" , **_lowerCamelCase , ) ->Any: super().__init__(pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps SCREAMING_SNAKE_CASE : str = position_embedding_type SCREAMING_SNAKE_CASE : Optional[int] = quant_mode SCREAMING_SNAKE_CASE : Dict = force_dequant class a_ ( a__ ): """simple docstring""" @property def __lowerCAmelCase ( self ) ->Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Dict = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : List[Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
313
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_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = filter(lambda a__ : p.requires_grad , model.parameters() ) SCREAMING_SNAKE_CASE : List[Any] = sum([np.prod(p.size() ) for p in model_parameters] ) return params a__ : Any = logging.getLogger(__name__) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if metric == "rouge2": SCREAMING_SNAKE_CASE : str = '''{val_avg_rouge2:.4f}-{step_count}''' elif metric == "bleu": SCREAMING_SNAKE_CASE : List[Any] = '''{val_avg_bleu:.4f}-{step_count}''' elif metric == "em": SCREAMING_SNAKE_CASE : int = '''{val_avg_em:.4f}-{step_count}''' elif metric == "loss": SCREAMING_SNAKE_CASE : int = '''{val_avg_loss:.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.''' ) SCREAMING_SNAKE_CASE : Dict = ModelCheckpoint( dirpath=a__ , filename=a__ , monitor=F"""val_{metric}""" , mode='''max''' , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def UpperCAmelCase_( a__ , a__ ): """simple docstring""" return EarlyStopping( monitor=F"""val_{metric}""" , mode='''min''' if '''loss''' in metric else '''max''' , patience=a__ , verbose=a__ , ) class a_ ( pl.Callback ): """simple docstring""" def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Dict: SCREAMING_SNAKE_CASE : List[str] = {F"""lr_group_{i}""": param['''lr'''] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_lowerCamelCase ) @rank_zero_only def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=True ) ->None: logger.info(F"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) SCREAMING_SNAKE_CASE : Optional[int] = 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 SCREAMING_SNAKE_CASE : List[str] = Path(pl_module.hparams.output_dir ) if type_path == "test": SCREAMING_SNAKE_CASE : Any = od / '''test_results.txt''' SCREAMING_SNAKE_CASE : Optional[int] = 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. SCREAMING_SNAKE_CASE : str = od / F"""{type_path}_results/{trainer.global_step:05d}.txt""" SCREAMING_SNAKE_CASE : Tuple = od / F"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=_lowerCamelCase ) generations_file.parent.mkdir(exist_ok=_lowerCamelCase ) with open(_lowerCamelCase , '''a+''' ) as writer: for key in sorted(_lowerCamelCase ): if key in ["log", "progress_bar", "preds"]: continue SCREAMING_SNAKE_CASE : Tuple = metrics[key] if isinstance(_lowerCamelCase , torch.Tensor ): SCREAMING_SNAKE_CASE : List[Any] = val.item() SCREAMING_SNAKE_CASE : Tuple = F"""{key}: {val:.6f}\n""" writer.write(_lowerCamelCase ) if not save_generations: return if "preds" in metrics: SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(metrics['''preds'''] ) generations_file.open('''w+''' ).write(_lowerCamelCase ) @rank_zero_only def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Dict: try: SCREAMING_SNAKE_CASE : Any = pl_module.model.model.num_parameters() except AttributeError: SCREAMING_SNAKE_CASE : Optional[int] = pl_module.model.num_parameters() SCREAMING_SNAKE_CASE : int = count_trainable_parameters(_lowerCamelCase ) # 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 , _lowerCamelCase , _lowerCamelCase ) ->List[Any]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_lowerCamelCase , _lowerCamelCase , '''test''' ) @rank_zero_only def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Tuple: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
313
1
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowerCAmelCase : Optional[Any] = (720, 1280) # Height, Width _lowerCAmelCase : int = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowerCAmelCase : Any = 1 / 100 _lowerCAmelCase : Optional[int] = '''''' _lowerCAmelCase : List[str] = '''''' _lowerCAmelCase : Optional[Any] = '''''' _lowerCAmelCase : Optional[Any] = 250 def lowerCamelCase_( ) -> None: '''simple docstring''' _lowerCamelCase, _lowerCamelCase : int = get_dataset(_lowerCamelCase , _lowerCamelCase ) for index in range(_lowerCamelCase ): _lowerCamelCase : Tuple = random.sample(range(len(_lowerCamelCase ) ) , 4 ) _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Optional[int] = update_image_and_anno( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , filter_scale=_lowerCamelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' _lowerCamelCase : Optional[int] = random_chars(32 ) _lowerCamelCase : str = path.split(os.sep )[-1].rsplit("." , 1 )[0] _lowerCamelCase : int = F"""{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}""" cva.imwrite(F"""{file_root}.jpg""" , _lowerCamelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}""" ) _lowerCamelCase : Optional[int] = [] for anno in new_annos: _lowerCamelCase : Dict = anno[3] - anno[1] _lowerCamelCase : List[str] = anno[4] - anno[2] _lowerCamelCase : List[Any] = anno[1] + width / 2 _lowerCamelCase : Any = anno[2] + height / 2 _lowerCamelCase : Dict = F"""{anno[0]} {x_center} {y_center} {width} {height}""" annos_list.append(_lowerCamelCase ) with open(F"""{file_root}.txt""" , "w" ) as outfile: outfile.write("\n".join(line for line in annos_list ) ) def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> tuple[list, list]: '''simple docstring''' _lowerCamelCase : Union[str, Any] = [] _lowerCamelCase : Any = [] for label_file in glob.glob(os.path.join(_lowerCamelCase , "*.txt" ) ): _lowerCamelCase : Optional[Any] = label_file.split(os.sep )[-1].rsplit("." , 1 )[0] with open(_lowerCamelCase ) as in_file: _lowerCamelCase : List[str] = in_file.readlines() _lowerCamelCase : List[Any] = os.path.join(_lowerCamelCase , F"""{label_name}.jpg""" ) _lowerCamelCase : Optional[Any] = [] for obj_list in obj_lists: _lowerCamelCase : str = obj_list.rstrip("\n" ).split(" " ) _lowerCamelCase : Optional[Any] = float(obj[1] ) - float(obj[3] ) / 2 _lowerCamelCase : Any = float(obj[2] ) - float(obj[4] ) / 2 _lowerCamelCase : str = float(obj[1] ) + float(obj[3] ) / 2 _lowerCamelCase : List[str] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(_lowerCamelCase ) labels.append(_lowerCamelCase ) return img_paths, labels def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 0.0 , ) -> tuple[list, list, str]: '''simple docstring''' _lowerCamelCase : str = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) _lowerCamelCase : List[str] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) _lowerCamelCase : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) _lowerCamelCase : Optional[int] = int(scale_x * output_size[1] ) _lowerCamelCase : Tuple = int(scale_y * output_size[0] ) _lowerCamelCase : List[Any] = [] _lowerCamelCase : Any = [] for i, index in enumerate(_lowerCamelCase ): _lowerCamelCase : Optional[int] = all_img_list[index] path_list.append(_lowerCamelCase ) _lowerCamelCase : Union[str, Any] = all_annos[index] _lowerCamelCase : Tuple = cva.imread(_lowerCamelCase ) if i == 0: # top-left _lowerCamelCase : Any = cva.resize(_lowerCamelCase , (divid_point_x, divid_point_y) ) _lowerCamelCase : Any = img for bbox in img_annos: _lowerCamelCase : List[Any] = bbox[1] * scale_x _lowerCamelCase : str = bbox[2] * scale_y _lowerCamelCase : Union[str, Any] = bbox[3] * scale_x _lowerCamelCase : List[Any] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right _lowerCamelCase : List[Any] = cva.resize(_lowerCamelCase , (output_size[1] - divid_point_x, divid_point_y) ) _lowerCamelCase : Optional[Any] = img for bbox in img_annos: _lowerCamelCase : Union[str, Any] = scale_x + bbox[1] * (1 - scale_x) _lowerCamelCase : List[Any] = bbox[2] * scale_y _lowerCamelCase : List[Any] = scale_x + bbox[3] * (1 - scale_x) _lowerCamelCase : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left _lowerCamelCase : Optional[Any] = cva.resize(_lowerCamelCase , (divid_point_x, output_size[0] - divid_point_y) ) _lowerCamelCase : Optional[int] = img for bbox in img_annos: _lowerCamelCase : Any = bbox[1] * scale_x _lowerCamelCase : Optional[Any] = scale_y + bbox[2] * (1 - scale_y) _lowerCamelCase : Union[str, Any] = bbox[3] * scale_x _lowerCamelCase : Any = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right _lowerCamelCase : str = cva.resize( _lowerCamelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) _lowerCamelCase : Union[str, Any] = img for bbox in img_annos: _lowerCamelCase : Tuple = scale_x + bbox[1] * (1 - scale_x) _lowerCamelCase : List[Any] = scale_y + bbox[2] * (1 - scale_y) _lowerCamelCase : Any = scale_x + bbox[3] * (1 - scale_x) _lowerCamelCase : int = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: _lowerCamelCase : Any = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def lowerCamelCase_( _lowerCamelCase ) -> str: '''simple docstring''' assert number_char > 1, "The number of character should greater than 1" _lowerCamelCase : Tuple = ascii_lowercase + digits return "".join(random.choice(_lowerCamelCase ) for _ in range(_lowerCamelCase ) ) if __name__ == "__main__": main() print('''DONE ✅''')
340
"""simple docstring""" _lowerCAmelCase : dict[tuple[int, int, int], int] = {} def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> int: '''simple docstring''' if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on _lowerCamelCase : Optional[int] = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one _lowerCamelCase : int = _calculate(days - 1 , _lowerCamelCase , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 _lowerCamelCase : Tuple = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter _lowerCamelCase : str = _calculate(days - 1 , _lowerCamelCase , 0 ) _lowerCamelCase : List[Any] = state_late + state_absent + state_ontime _lowerCamelCase : int = prizestrings return prizestrings def lowerCamelCase_( _lowerCamelCase = 30 ) -> int: '''simple docstring''' return _calculate(_lowerCamelCase , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
340
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class _lowerCamelCase ( __SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCAmelCase_ : Union[List[PIL.Image.Image], np.ndarray] UpperCAmelCase_ : Optional[List[bool]] UpperCAmelCase_ : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
326
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: _UpperCamelCase = None _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} _UpperCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', }, '''tokenizer_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/tokenizer.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/tokenizer.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/tokenizer.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/tokenizer.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/tokenizer.json''', }, } # TODO(PVP) - this should be removed in Transformers v5 _UpperCamelCase = { '''t5-small''': 512, '''t5-base''': 512, '''t5-large''': 512, '''t5-3b''': 512, '''t5-11b''': 512, } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : str = ["input_ids", "attention_mask"] _SCREAMING_SNAKE_CASE : Optional[Any] = TaTokenizer _SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="</s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase=100 , __UpperCAmelCase=None , **__UpperCAmelCase , ) -> List[Any]: '''simple docstring''' # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __UpperCAmelCase : List[Any] = [f'<extra_id_{i}>' for i in range(__UpperCAmelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens __UpperCAmelCase : Any = len(set(filter(lambda __UpperCAmelCase : bool("""extra_id_""" in str(__UpperCAmelCase ) ) , __UpperCAmelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , extra_ids=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , **__UpperCAmelCase , ) __UpperCAmelCase : Optional[int] = vocab_file __UpperCAmelCase : Any = False if not self.vocab_file else True __UpperCAmelCase : Optional[int] = extra_ids @staticmethod def __A ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> int: '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: __UpperCAmelCase : int = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" f' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" f' {pretrained_model_name_or_path} automatically truncating your input to' f' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' f' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , __UpperCAmelCase , ) return max_model_length def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__UpperCAmelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCAmelCase : Any = os.path.join( __UpperCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) logger.info(f'Copy vocab file to {out_vocab_file}' ) return (out_vocab_file,) def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: '''simple docstring''' __UpperCAmelCase : str = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: __UpperCAmelCase : Optional[Any] = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def __A ( self ) -> Any: '''simple docstring''' return list( set(filter(lambda __UpperCAmelCase : bool(re.search(r"""<extra_id_\d+>""" , __UpperCAmelCase ) ) is not None , self.additional_special_tokens ) ) ) def __A ( self ) -> Optional[int]: '''simple docstring''' return [self.convert_tokens_to_ids(__UpperCAmelCase ) for token in self.get_sentinel_tokens()]
254
0
"""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 re from ..utils import cached_file # docstyle-ignore UpperCamelCase_ ="\nHuman: <<task>>\n\nAssistant: " UpperCamelCase_ ="huggingface-tools/default-prompts" UpperCamelCase_ ={"chat": "chat_prompt_template.txt", "run": "run_prompt_template.txt"} def a_ ( _lowercase , _lowercase , _lowercase="run" ): if prompt_or_repo_id is None: _UpperCamelCase : Dict = DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search('''\\s''' , _lowercase ) is not None: return prompt_or_repo_id _UpperCamelCase : Tuple = cached_file( _lowercase , PROMPT_FILES[mode] , repo_type='''dataset''' , user_agent={'''agent''': agent_name} ) with open(_lowercase , '''r''' , encoding='''utf-8''' ) as f: return f.read()
361
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def a_ ( _lowercase , _lowercase , _lowercase ): # Initialise PyTorch model _UpperCamelCase : List[Any] = MobileBertConfig.from_json_file(_lowercase ) print(F"""Building PyTorch model from configuration: {config}""" ) _UpperCamelCase : List[str] = MobileBertForPreTraining(_lowercase ) # Load weights from tf checkpoint _UpperCamelCase : Union[str, Any] = load_tf_weights_in_mobilebert(_lowercase , _lowercase , _lowercase ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , _lowercase ) if __name__ == "__main__": UpperCamelCase_ =argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--mobilebert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained MobileBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) UpperCamelCase_ =parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
128
0
import argparse from collections import defaultdict def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Any: _lowercase : int = F'''{file}_{class_name}_{test_name}''' done_test[_id] += 1 with open(lowerCamelCase_ , 'r' ) as f: _lowercase : Optional[int] = f.readlines() _lowercase : Tuple = F'''class {class_name}(''' _lowercase : int = F'''{4 * " "}def {test_name}(''' _lowercase : int = F'''{8 * " "}{correct_line.split()[0]}''' _lowercase : Optional[Any] = F'''{16 * " "}{correct_line.split()[0]}''' _lowercase : List[Any] = False _lowercase : Optional[int] = False _lowercase : str = False _lowercase : Optional[int] = False _lowercase : List[str] = 0 _lowercase : List[str] = 0 _lowercase : Any = [] for line in lines: if line.startswith(lowerCamelCase_ ): _lowercase : List[str] = True elif in_class and line.startswith(lowerCamelCase_ ): _lowercase : Tuple = True elif in_class and in_func and (line.startswith(lowerCamelCase_ ) or line.startswith(lowerCamelCase_ )): _lowercase : Optional[Any] = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: _lowercase : Tuple = True if in_class and in_func and in_line: if ")" not in line: continue else: _lowercase : Dict = True if in_class and in_func and in_line and insert_line: new_lines.append(F'''{spaces * " "}{correct_line}''' ) _lowercase : Any = False else: new_lines.append(lowerCamelCase_ ) with open(lowerCamelCase_ , 'w' ) as f: for line in new_lines: f.write(lowerCamelCase_ ) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_=None ) -> Tuple: if fail is not None: with open(lowerCamelCase_ , 'r' ) as f: _lowercase : Any = {l.strip() for l in f.readlines()} else: _lowercase : str = None with open(lowerCamelCase_ , 'r' ) as f: _lowercase : str = f.readlines() _lowercase : Union[str, Any] = defaultdict(lowerCamelCase_ ) for line in correct_lines: _lowercase , _lowercase , _lowercase , _lowercase : List[str] = line.split(';' ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : List[Any] = argparse.ArgumentParser() parser.add_argument("--correct_filename", help="filename of tests with expected result") parser.add_argument("--fail_filename", help="filename of test failures", type=str, default=None) SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() main(args.correct_filename, args.fail_filename)
21
import random from typing import Any def UpperCamelCase_( lowerCamelCase_ ) -> list[Any]: for _ in range(len(lowerCamelCase_ ) ): _lowercase : Optional[int] = random.randint(0 , len(lowerCamelCase_ ) - 1 ) _lowercase : str = random.randint(0 , len(lowerCamelCase_ ) - 1 ) _lowercase , _lowercase : Optional[int] = data[b], data[a] return data if __name__ == "__main__": SCREAMING_SNAKE_CASE : str = [0, 1, 2, 3, 4, 5, 6, 7] SCREAMING_SNAKE_CASE : int = ["python", "says", "hello", "!"] print("Fisher-Yates Shuffle:") print("List", integers, strings) print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
21
1
'''simple docstring''' import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'): __lowercase : List[Any] = True from torch.cuda.amp import autocast __lowercase : List[Any] = logging.getLogger(__name__) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any]=None , _SCREAMING_SNAKE_CASE : Dict=None ): return field(default_factory=lambda: default , metadata=_SCREAMING_SNAKE_CASE ) @dataclass class __UpperCamelCase : A_ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) A_ = field( default=lowerCAmelCase_ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) A_ = field( default=lowerCAmelCase_ , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) A_ = field( default=0.1 , metadata={"help": "The dropout ratio for the attention probabilities."} ) A_ = field( default=0.1 , metadata={"help": "The dropout ratio for activations inside the fully connected layer."} ) A_ = field( default=0.1 , metadata={ "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler." } , ) A_ = field( default=0.1 , metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."} , ) A_ = field( default=0.05 , metadata={ "help": ( "Propability of each feature vector along the time axis to be chosen as the start of the vector" "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature" "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``." ) } , ) A_ = field(default=0.0 , metadata={"help": "The LayerDrop probability."} ) @dataclass class __UpperCamelCase : A_ = field( default=lowerCAmelCase_ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) A_ = field( default="train+validation" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) A_ = field( default=lowerCAmelCase_ , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) A_ = field( default=lowerCAmelCase_ , metadata={"help": "The number of processes to use for the preprocessing."} , ) A_ = field( default=lowerCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) A_ = field( default=lowerCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." ) } , ) A_ = list_field( default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "'", "\"", "�"] , metadata={"help": "A list of characters to remove from the transcripts."} , ) @dataclass class __UpperCamelCase : A_ = 42 A_ = True A_ = None A_ = None A_ = None A_ = None def __call__( self , __a ): '''simple docstring''' __a : List[Any] = [{'input_values': feature['input_values']} for feature in features] __a : Optional[int] = [{'input_ids': feature['labels']} for feature in features] __a : Any = self.processor.pad( __a , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' , ) __a : List[str] = self.processor.pad( labels=__a , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='pt' , ) # replace padding with -100 to ignore loss correctly __a : Union[str, Any] = labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1 ) , -100 ) __a : int = labels return batch class __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self , __a , __a ): '''simple docstring''' model.train() __a : int = self._prepare_inputs(__a ) if self.use_amp: with autocast(): __a : Optional[int] = self.compute_loss(__a , __a ) else: __a : Optional[Any] = self.compute_loss(__a , __a ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": __a : int = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": __a : Any = loss.sum() / (inputs['labels'] >= 0).sum() else: raise ValueError(f"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""" ) if self.args.gradient_accumulation_steps > 1: __a : List[str] = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(__a ).backward() elif self.use_apex: with amp.scale_loss(__a , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(__a ) else: loss.backward() return loss.detach() def lowerCamelCase (): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __a : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __a , __a , __a : List[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __a , __a , __a : Any = parser.parse_args_into_dataclasses() # Detecting last checkpoint. __a : Dict = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __a : Union[str, Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) # 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() logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: __a : Optional[Any] = datasets.load_dataset( 'common_voice' , data_args.dataset_config_name , split=data_args.train_split_name ) __a : Dict = datasets.load_dataset('common_voice' , data_args.dataset_config_name , split='test' ) # Create and save tokenizer __a : str = F"""[{"".join(data_args.chars_to_ignore )}]""" def remove_special_characters(_SCREAMING_SNAKE_CASE : Optional[int] ): __a : Any = re.sub(_SCREAMING_SNAKE_CASE , '' , batch['sentence'] ).lower() + ' ' return batch __a : List[str] = train_dataset.map(_SCREAMING_SNAKE_CASE , remove_columns=['sentence'] ) __a : Any = eval_dataset.map(_SCREAMING_SNAKE_CASE , remove_columns=['sentence'] ) def extract_all_chars(_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : int = ' '.join(batch['text'] ) __a : int = list(set(_SCREAMING_SNAKE_CASE ) ) return {"vocab": [vocab], "all_text": [all_text]} __a : List[str] = train_dataset.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , batch_size=-1 , keep_in_memory=_SCREAMING_SNAKE_CASE , remove_columns=train_dataset.column_names , ) __a : Dict = train_dataset.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , batch_size=-1 , keep_in_memory=_SCREAMING_SNAKE_CASE , remove_columns=eval_dataset.column_names , ) __a : Dict = list(set(vocab_train['vocab'][0] ) | set(vocab_test['vocab'][0] ) ) __a : List[str] = {v: k for k, v in enumerate(_SCREAMING_SNAKE_CASE )} __a : List[Any] = vocab_dict[' '] del vocab_dict[" "] __a : Union[str, Any] = len(_SCREAMING_SNAKE_CASE ) __a : List[Any] = len(_SCREAMING_SNAKE_CASE ) with open('vocab.json' , 'w' ) as vocab_file: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __a : Optional[int] = WavaVecaCTCTokenizer( 'vocab.json' , unk_token='[UNK]' , pad_token='[PAD]' , word_delimiter_token='|' , ) __a : Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0.0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) __a : List[str] = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='mean' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , ) if data_args.max_train_samples is not None: __a : Dict = min(len(_SCREAMING_SNAKE_CASE ) , data_args.max_train_samples ) __a : Optional[Any] = train_dataset.select(range(_SCREAMING_SNAKE_CASE ) ) if data_args.max_val_samples is not None: __a : Optional[Any] = eval_dataset.select(range(data_args.max_val_samples ) ) __a : Any = torchaudio.transforms.Resample(48_000 , 16_000 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(_SCREAMING_SNAKE_CASE : Dict ): __a , __a : Union[str, Any] = torchaudio.load(batch['path'] ) __a : List[Any] = resampler(_SCREAMING_SNAKE_CASE ).squeeze().numpy() __a : Tuple = 16_000 __a : Union[str, Any] = batch['text'] return batch __a : int = train_dataset.map( _SCREAMING_SNAKE_CASE , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) __a : Optional[Any] = eval_dataset.map( _SCREAMING_SNAKE_CASE , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(_SCREAMING_SNAKE_CASE : Optional[int] ): # check that all files have the correct sampling rate assert ( len(set(batch['sampling_rate'] ) ) == 1 ), F"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.""" __a : List[Any] = processor( audio=batch['speech'] , text=batch['target_text'] , sampling_rate=batch['sampling_rate'][0] ) batch.update(_SCREAMING_SNAKE_CASE ) return batch __a : Optional[int] = train_dataset.map( _SCREAMING_SNAKE_CASE , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_SCREAMING_SNAKE_CASE , num_proc=data_args.preprocessing_num_workers , ) __a : Tuple = eval_dataset.map( _SCREAMING_SNAKE_CASE , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_SCREAMING_SNAKE_CASE , num_proc=data_args.preprocessing_num_workers , ) # Metric __a : Tuple = datasets.load_metric('wer' ) def compute_metrics(_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : Union[str, Any] = pred.predictions __a : Any = np.argmax(_SCREAMING_SNAKE_CASE , axis=-1 ) __a : Any = processor.tokenizer.pad_token_id __a : str = processor.batch_decode(_SCREAMING_SNAKE_CASE ) # we do not want to group tokens when computing the metrics __a : Optional[Any] = processor.batch_decode(pred.label_ids , group_tokens=_SCREAMING_SNAKE_CASE ) __a : List[str] = wer_metric.compute(predictions=_SCREAMING_SNAKE_CASE , references=_SCREAMING_SNAKE_CASE ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator __a : str = DataCollatorCTCWithPadding(processor=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE ) # Initialize our Trainer __a : List[Any] = CTCTrainer( model=_SCREAMING_SNAKE_CASE , data_collator=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , compute_metrics=_SCREAMING_SNAKE_CASE , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: __a : List[Any] = last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): __a : int = model_args.model_name_or_path else: __a : Union[str, Any] = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) __a : Union[str, Any] = trainer.train(resume_from_checkpoint=_SCREAMING_SNAKE_CASE ) trainer.save_model() __a : Any = train_result.metrics __a : List[Any] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(_SCREAMING_SNAKE_CASE ) ) __a : List[Any] = min(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ) trainer.log_metrics('train' , _SCREAMING_SNAKE_CASE ) trainer.save_metrics('train' , _SCREAMING_SNAKE_CASE ) trainer.save_state() # Evaluation __a : List[str] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __a : Union[str, Any] = trainer.evaluate() __a : Any = data_args.max_val_samples if data_args.max_val_samples is not None else len(_SCREAMING_SNAKE_CASE ) __a : List[str] = min(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ) trainer.log_metrics('eval' , _SCREAMING_SNAKE_CASE ) trainer.save_metrics('eval' , _SCREAMING_SNAKE_CASE ) return results if __name__ == "__main__": main()
294
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowercase : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys __lowercase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
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, ) __UpperCAmelCase ={ "configuration_xlm_roberta": [ "XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMRobertaConfig", "XLMRobertaOnnxConfig", ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =["XLMRobertaTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =["XLMRobertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMRobertaForCausalLM", "XLMRobertaForMaskedLM", "XLMRobertaForMultipleChoice", "XLMRobertaForQuestionAnswering", "XLMRobertaForSequenceClassification", "XLMRobertaForTokenClassification", "XLMRobertaModel", "XLMRobertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLMRobertaForCausalLM", "TFXLMRobertaForMaskedLM", "TFXLMRobertaForMultipleChoice", "TFXLMRobertaForQuestionAnswering", "TFXLMRobertaForSequenceClassification", "TFXLMRobertaForTokenClassification", "TFXLMRobertaModel", "TFXLMRobertaPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxXLMRobertaForMaskedLM", "FlaxXLMRobertaForCausalLM", "FlaxXLMRobertaForMultipleChoice", "FlaxXLMRobertaForQuestionAnswering", "FlaxXLMRobertaForSequenceClassification", "FlaxXLMRobertaForTokenClassification", "FlaxXLMRobertaModel", "FlaxXLMRobertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class lowerCamelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : str = TextToVideoSDPipeline a__ : Union[str, Any] = TEXT_TO_IMAGE_PARAMS a__ : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. a__ : int = frozenset( [ """num_inference_steps""", """generator""", """latents""", """return_dict""", """callback""", """callback_steps""", ] ) def UpperCamelCase__ ( self) -> Optional[Any]: torch.manual_seed(0) __UpperCamelCase :str = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') , up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') , cross_attention_dim=32 , attention_head_dim=4 , ) __UpperCamelCase :Optional[int] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , clip_sample=__lowercase , set_alpha_to_one=__lowercase , ) torch.manual_seed(0) __UpperCamelCase :Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) __UpperCamelCase :Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act='''gelu''' , projection_dim=512 , ) __UpperCamelCase :Optional[Any] = CLIPTextModel(__lowercase) __UpperCamelCase :Optional[int] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') __UpperCamelCase :Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def UpperCamelCase__ ( self , __lowercase , __lowercase=0) -> Optional[int]: if str(__lowercase).startswith('''mps'''): __UpperCamelCase :List[Any] = torch.manual_seed(__lowercase) else: __UpperCamelCase :Tuple = torch.Generator(device=__lowercase).manual_seed(__lowercase) __UpperCamelCase :Dict = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def UpperCamelCase__ ( self) -> Optional[Any]: __UpperCamelCase :int = '''cpu''' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase :Optional[int] = self.get_dummy_components() __UpperCamelCase :Dict = TextToVideoSDPipeline(**__lowercase) __UpperCamelCase :Any = sd_pipe.to(__lowercase) sd_pipe.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :Optional[Any] = self.get_dummy_inputs(__lowercase) __UpperCamelCase :int = '''np''' __UpperCamelCase :List[str] = sd_pipe(**__lowercase).frames __UpperCamelCase :Optional[Any] = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) __UpperCamelCase :str = np.array([1_58.0, 1_60.0, 1_53.0, 1_25.0, 1_00.0, 1_21.0, 1_11.0, 93.0, 1_13.0]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def UpperCamelCase__ ( self) -> Tuple: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__lowercase , expected_max_diff=3E-3) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCamelCase__ ( self) -> Optional[int]: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__lowercase , expected_max_diff=1E-2) @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''') def UpperCamelCase__ ( self) -> Union[str, Any]: pass @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''') def UpperCamelCase__ ( self) -> Dict: pass @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''') def UpperCamelCase__ ( self) -> str: pass def UpperCamelCase__ ( self) -> List[str]: return super().test_progress_bar() @slow @skip_mps class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase :Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy''') __UpperCamelCase :List[str] = TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''') __UpperCamelCase :Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) __UpperCamelCase :str = pipe.to('''cuda''') __UpperCamelCase :Optional[Any] = '''Spiderman is surfing''' __UpperCamelCase :Union[str, Any] = torch.Generator(device='''cpu''').manual_seed(0) __UpperCamelCase :List[Any] = pipe(__lowercase , generator=__lowercase , num_inference_steps=25 , output_type='''pt''').frames __UpperCamelCase :Optional[int] = video_frames.cpu().numpy() assert np.abs(expected_video - video).mean() < 5E-2 def UpperCamelCase__ ( self) -> int: __UpperCamelCase :str = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy''') __UpperCamelCase :Union[str, Any] = TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''') __UpperCamelCase :str = pipe.to('''cuda''') __UpperCamelCase :Union[str, Any] = '''Spiderman is surfing''' __UpperCamelCase :int = torch.Generator(device='''cpu''').manual_seed(0) __UpperCamelCase :List[Any] = pipe(__lowercase , generator=__lowercase , num_inference_steps=2 , output_type='''pt''').frames __UpperCamelCase :Optional[Any] = video_frames.cpu().numpy() assert np.abs(expected_video - video).mean() < 5E-2
43
0
'''simple docstring''' lowerCamelCase_ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def SCREAMING_SNAKE_CASE_ ( ) -> None: _SCREAMING_SNAKE_CASE = input("Enter message: " ) _SCREAMING_SNAKE_CASE = input("Enter key [alphanumeric]: " ) _SCREAMING_SNAKE_CASE = input("Encrypt/Decrypt [e/d]: " ) if mode.lower().startswith("e" ): _SCREAMING_SNAKE_CASE = "encrypt" _SCREAMING_SNAKE_CASE = encrypt_message(__A , __A ) elif mode.lower().startswith("d" ): _SCREAMING_SNAKE_CASE = "decrypt" _SCREAMING_SNAKE_CASE = decrypt_message(__A , __A ) print(f"""\n{mode.title()}ed message:""" ) print(__A ) def SCREAMING_SNAKE_CASE_ ( __A : str , __A : str ) -> str: return translate_message(__A , __A , "encrypt" ) def SCREAMING_SNAKE_CASE_ ( __A : str , __A : str ) -> str: return translate_message(__A , __A , "decrypt" ) def SCREAMING_SNAKE_CASE_ ( __A : str , __A : str , __A : str ) -> str: _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = key.upper() for symbol in message: _SCREAMING_SNAKE_CASE = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(__A ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__A ): _SCREAMING_SNAKE_CASE = 0 else: translated.append(__A ) return "".join(__A ) if __name__ == "__main__": main()
111
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase_ = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ 'CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'CTRLForSequenceClassification', 'CTRLLMHeadModel', 'CTRLModel', 'CTRLPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ 'TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCTRLForSequenceClassification', 'TFCTRLLMHeadModel', 'TFCTRLModel', 'TFCTRLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
111
1
"""simple docstring""" import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated a_ = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ a_ = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : str = numpy.dtype(numpy.uintaa ).newbyteorder('''>''' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=__UpperCamelCase )[0] @deprecated(__UpperCamelCase , '''Please use tf.data to implement this functionality.''' ) def __UpperCAmelCase ( __UpperCamelCase ): print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__UpperCamelCase ) as bytestream: __lowercase : Any = _readaa(__UpperCamelCase ) if magic != 20_51: raise ValueError( '''Invalid magic number %d in MNIST image file: %s''' % (magic, f.name) ) __lowercase : List[Any] = _readaa(__UpperCamelCase ) __lowercase : Tuple = _readaa(__UpperCamelCase ) __lowercase : Tuple = _readaa(__UpperCamelCase ) __lowercase : Optional[int] = bytestream.read(rows * cols * num_images ) __lowercase : int = numpy.frombuffer(__UpperCamelCase , dtype=numpy.uinta ) __lowercase : Dict = data.reshape(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , 1 ) return data @deprecated(__UpperCamelCase , '''Please use tf.one_hot on tensors.''' ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): __lowercase : List[Any] = labels_dense.shape[0] __lowercase : Union[str, Any] = numpy.arange(__UpperCamelCase ) * num_classes __lowercase : List[str] = numpy.zeros((num_labels, num_classes) ) __lowercase : Dict = 1 return labels_one_hot @deprecated(__UpperCamelCase , '''Please use tf.data to implement this functionality.''' ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase=False , __UpperCamelCase=10 ): print('''Extracting''' , f.name ) with gzip.GzipFile(fileobj=__UpperCamelCase ) as bytestream: __lowercase : str = _readaa(__UpperCamelCase ) if magic != 20_49: raise ValueError( '''Invalid magic number %d in MNIST label file: %s''' % (magic, f.name) ) __lowercase : List[Any] = _readaa(__UpperCamelCase ) __lowercase : List[str] = bytestream.read(__UpperCamelCase ) __lowercase : List[str] = numpy.frombuffer(__UpperCamelCase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__UpperCamelCase , __UpperCamelCase ) return labels class UpperCAmelCase_ : @deprecated( UpperCamelCase_ , '''Please use alternatives such as official/mnist/_DataSet.py''' ''' from tensorflow/models.''' , ) def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=False , UpperCamelCase_=False , UpperCamelCase_=dtypes.floataa , UpperCamelCase_=True , UpperCamelCase_=None , ) -> int: __lowercase ,__lowercase : Union[str, Any] = random_seed.get_seed(UpperCamelCase_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __lowercase : Union[str, Any] = dtypes.as_dtype(UpperCamelCase_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('''Invalid image dtype %r, expected uint8 or float32''' % dtype ) if fake_data: __lowercase : str = 1_00_00 __lowercase : Optional[int] = one_hot else: assert ( images.shape[0] == labels.shape[0] ), F"""images.shape: {images.shape} labels.shape: {labels.shape}""" __lowercase : str = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __lowercase : Tuple = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __lowercase : Dict = images.astype(numpy.floataa ) __lowercase : Any = numpy.multiply(UpperCamelCase_ , 1.0 / 2_5_5.0 ) __lowercase : str = images __lowercase : Optional[int] = labels __lowercase : int = 0 __lowercase : List[Any] = 0 @property def _lowerCamelCase ( self ) -> Optional[int]: return self._images @property def _lowerCamelCase ( self ) -> int: return self._labels @property def _lowerCamelCase ( self ) -> List[str]: return self._num_examples @property def _lowerCamelCase ( self ) -> str: return self._epochs_completed def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_=False , UpperCamelCase_=True ) -> Union[str, Any]: if fake_data: __lowercase : Optional[int] = [1] * 7_84 __lowercase : List[str] = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(UpperCamelCase_ )], [fake_label for _ in range(UpperCamelCase_ )], ) __lowercase : str = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __lowercase : int = numpy.arange(self._num_examples ) numpy.random.shuffle(UpperCamelCase_ ) __lowercase : Any = self.images[perma] __lowercase : Dict = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __lowercase : Optional[int] = self._num_examples - start __lowercase : List[Any] = self._images[start : self._num_examples] __lowercase : Optional[int] = self._labels[start : self._num_examples] # Shuffle the data if shuffle: __lowercase : Any = numpy.arange(self._num_examples ) numpy.random.shuffle(UpperCamelCase_ ) __lowercase : int = self.images[perm] __lowercase : int = self.labels[perm] # Start next epoch __lowercase : str = 0 __lowercase : Dict = batch_size - rest_num_examples __lowercase : Dict = self._index_in_epoch __lowercase : int = self._images[start:end] __lowercase : Any = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __lowercase : List[str] = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__UpperCamelCase , '''Please write your own downloading logic.''' ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): if not gfile.Exists(__UpperCamelCase ): gfile.MakeDirs(__UpperCamelCase ) __lowercase : int = os.path.join(__UpperCamelCase , __UpperCamelCase ) if not gfile.Exists(__UpperCamelCase ): urllib.request.urlretrieve(__UpperCamelCase , __UpperCamelCase ) # noqa: S310 with gfile.GFile(__UpperCamelCase ) as f: __lowercase : Optional[int] = f.size() print('''Successfully downloaded''' , __UpperCamelCase , __UpperCamelCase , '''bytes.''' ) return filepath @deprecated( __UpperCamelCase , '''Please use alternatives such as:''' ''' tensorflow_datasets.load(\'mnist\')''' ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase=False , __UpperCamelCase=False , __UpperCamelCase=dtypes.floataa , __UpperCamelCase=True , __UpperCamelCase=50_00 , __UpperCamelCase=None , __UpperCamelCase=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=__UpperCamelCase , one_hot=__UpperCamelCase , dtype=__UpperCamelCase , seed=__UpperCamelCase ) __lowercase : int = fake() __lowercase : Any = fake() __lowercase : Tuple = fake() return _Datasets(train=__UpperCamelCase , validation=__UpperCamelCase , test=__UpperCamelCase ) if not source_url: # empty string check __lowercase : List[Any] = DEFAULT_SOURCE_URL __lowercase : Optional[Any] = '''train-images-idx3-ubyte.gz''' __lowercase : Dict = '''train-labels-idx1-ubyte.gz''' __lowercase : Union[str, Any] = '''t10k-images-idx3-ubyte.gz''' __lowercase : Any = '''t10k-labels-idx1-ubyte.gz''' __lowercase : Dict = _maybe_download( __UpperCamelCase , __UpperCamelCase , source_url + train_images_file ) with gfile.Open(__UpperCamelCase , '''rb''' ) as f: __lowercase : Any = _extract_images(__UpperCamelCase ) __lowercase : Any = _maybe_download( __UpperCamelCase , __UpperCamelCase , source_url + train_labels_file ) with gfile.Open(__UpperCamelCase , '''rb''' ) as f: __lowercase : str = _extract_labels(__UpperCamelCase , one_hot=__UpperCamelCase ) __lowercase : Dict = _maybe_download( __UpperCamelCase , __UpperCamelCase , source_url + test_images_file ) with gfile.Open(__UpperCamelCase , '''rb''' ) as f: __lowercase : Tuple = _extract_images(__UpperCamelCase ) __lowercase : Optional[int] = _maybe_download( __UpperCamelCase , __UpperCamelCase , source_url + test_labels_file ) with gfile.Open(__UpperCamelCase , '''rb''' ) as f: __lowercase : Optional[Any] = _extract_labels(__UpperCamelCase , one_hot=__UpperCamelCase ) if not 0 <= validation_size <= len(__UpperCamelCase ): __lowercase : Optional[Any] = ( '''Validation size should be between 0 and ''' f"""{len(__UpperCamelCase )}. Received: {validation_size}.""" ) raise ValueError(__UpperCamelCase ) __lowercase : List[str] = train_images[:validation_size] __lowercase : int = train_labels[:validation_size] __lowercase : List[Any] = train_images[validation_size:] __lowercase : Dict = train_labels[validation_size:] __lowercase : str = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed} __lowercase : Tuple = _DataSet(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) __lowercase : Optional[Any] = _DataSet(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) __lowercase : List[Any] = _DataSet(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) return _Datasets(train=__UpperCamelCase , validation=__UpperCamelCase , test=__UpperCamelCase )
249
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : Optional[int] = 3_84 __lowercase : str = 7 if "tiny" in model_name: __lowercase : List[str] = 96 __lowercase : Any = (2, 2, 6, 2) __lowercase : Dict = (3, 6, 12, 24) elif "small" in model_name: __lowercase : str = 96 __lowercase : Optional[int] = (2, 2, 18, 2) __lowercase : Tuple = (3, 6, 12, 24) elif "base" in model_name: __lowercase : Tuple = 1_28 __lowercase : Tuple = (2, 2, 18, 2) __lowercase : int = (4, 8, 16, 32) __lowercase : str = 12 __lowercase : Any = 5_12 elif "large" in model_name: __lowercase : List[str] = 1_92 __lowercase : List[Any] = (2, 2, 18, 2) __lowercase : Optional[Any] = (6, 12, 24, 48) __lowercase : Optional[int] = 12 __lowercase : Optional[Any] = 7_68 # set label information __lowercase : Any = 1_50 __lowercase : Tuple = '''huggingface/label-files''' __lowercase : int = '''ade20k-id2label.json''' __lowercase : Union[str, Any] = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type='''dataset''' ) , '''r''' ) ) __lowercase : Union[str, Any] = {int(__UpperCamelCase ): v for k, v in idalabel.items()} __lowercase : Optional[Any] = {v: k for k, v in idalabel.items()} __lowercase : Any = SwinConfig( embed_dim=__UpperCamelCase , depths=__UpperCamelCase , num_heads=__UpperCamelCase , window_size=__UpperCamelCase , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) __lowercase : List[Any] = UperNetConfig( backbone_config=__UpperCamelCase , auxiliary_in_channels=__UpperCamelCase , num_labels=__UpperCamelCase , idalabel=__UpperCamelCase , labelaid=__UpperCamelCase , ) return config def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : str = [] # fmt: off # stem rename_keys.append(('''backbone.patch_embed.projection.weight''', '''backbone.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''backbone.patch_embed.projection.bias''', '''backbone.embeddings.patch_embeddings.projection.bias''') ) rename_keys.append(('''backbone.patch_embed.norm.weight''', '''backbone.embeddings.norm.weight''') ) rename_keys.append(('''backbone.patch_embed.norm.bias''', '''backbone.embeddings.norm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.norm1.weight""", f"""backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.norm1.bias""", f"""backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table""", f"""backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index""", f"""backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight""", f"""backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias""", f"""backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.norm2.weight""", f"""backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.norm2.bias""", f"""backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight""", f"""backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias""", f"""backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight""", f"""backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight""") ) rename_keys.append((f"""backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias""", f"""backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias""") ) if i < 3: rename_keys.append((f"""backbone.stages.{i}.downsample.reduction.weight""", f"""backbone.encoder.layers.{i}.downsample.reduction.weight""") ) rename_keys.append((f"""backbone.stages.{i}.downsample.norm.weight""", f"""backbone.encoder.layers.{i}.downsample.norm.weight""") ) rename_keys.append((f"""backbone.stages.{i}.downsample.norm.bias""", f"""backbone.encoder.layers.{i}.downsample.norm.bias""") ) rename_keys.append((f"""backbone.norm{i}.weight""", f"""backbone.hidden_states_norms.stage{i+1}.weight""") ) rename_keys.append((f"""backbone.norm{i}.bias""", f"""backbone.hidden_states_norms.stage{i+1}.bias""") ) # decode head rename_keys.extend( [ ('''decode_head.conv_seg.weight''', '''decode_head.classifier.weight'''), ('''decode_head.conv_seg.bias''', '''decode_head.classifier.bias'''), ('''auxiliary_head.conv_seg.weight''', '''auxiliary_head.classifier.weight'''), ('''auxiliary_head.conv_seg.bias''', '''auxiliary_head.classifier.bias'''), ] ) # fmt: on return rename_keys def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): __lowercase : Any = dct.pop(__UpperCamelCase ) __lowercase : Any = val def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): __lowercase : Optional[Any] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __lowercase : Optional[Any] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) __lowercase : Dict = state_dict.pop(f"""backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight""" ) __lowercase : int = state_dict.pop(f"""backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict __lowercase : List[Any] = in_proj_weight[:dim, :] __lowercase : Tuple = in_proj_bias[: dim] __lowercase : List[Any] = in_proj_weight[ dim : dim * 2, : ] __lowercase : int = in_proj_bias[ dim : dim * 2 ] __lowercase : str = in_proj_weight[ -dim :, : ] __lowercase : List[Any] = in_proj_bias[-dim :] # fmt: on def __UpperCAmelCase ( __UpperCamelCase ): __lowercase ,__lowercase : str = x.shape __lowercase : List[str] = x.reshape(__UpperCamelCase , 4 , in_channel // 4 ) __lowercase : Dict = x[:, [0, 2, 1, 3], :].transpose(1 , 2 ).reshape(__UpperCamelCase , __UpperCamelCase ) return x def __UpperCAmelCase ( __UpperCamelCase ): __lowercase ,__lowercase : Optional[int] = x.shape __lowercase : Union[str, Any] = x.reshape(__UpperCamelCase , in_channel // 4 , 4 ) __lowercase : int = x[:, :, [0, 2, 1, 3]].transpose(1 , 2 ).reshape(__UpperCamelCase , __UpperCamelCase ) return x def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : int = x.shape[0] __lowercase : List[str] = x.reshape(4 , in_channel // 4 ) __lowercase : Any = x[[0, 2, 1, 3], :].transpose(0 , 1 ).reshape(__UpperCamelCase ) return x def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : Union[str, Any] = x.shape[0] __lowercase : List[str] = x.reshape(in_channel // 4 , 4 ) __lowercase : Union[str, Any] = x[:, [0, 2, 1, 3]].transpose(0 , 1 ).reshape(__UpperCamelCase ) return x def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): __lowercase : List[Any] = { '''upernet-swin-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth''', '''upernet-swin-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth''', '''upernet-swin-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth''', '''upernet-swin-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth''', } __lowercase : Any = model_name_to_url[model_name] __lowercase : Any = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location='''cpu''' , file_name=__UpperCamelCase )[ '''state_dict''' ] for name, param in state_dict.items(): print(__UpperCamelCase , param.shape ) __lowercase : Tuple = get_upernet_config(__UpperCamelCase ) __lowercase : List[Any] = UperNetForSemanticSegmentation(__UpperCamelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __lowercase : Optional[Any] = state_dict.pop(__UpperCamelCase ) if "bn" in key: __lowercase : List[Any] = key.replace('''bn''' , '''batch_norm''' ) __lowercase : Optional[Any] = val # rename keys __lowercase : Tuple = create_rename_keys(__UpperCamelCase ) for src, dest in rename_keys: rename_key(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) read_in_q_k_v(__UpperCamelCase , config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: __lowercase : Optional[Any] = reverse_correct_unfold_reduction_order(__UpperCamelCase ) if "norm" in key: __lowercase : Optional[Any] = reverse_correct_unfold_norm_order(__UpperCamelCase ) model.load_state_dict(__UpperCamelCase ) # verify on image __lowercase : Any = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' __lowercase : str = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ).convert('''RGB''' ) __lowercase : Union[str, Any] = SegformerImageProcessor() __lowercase : int = processor(__UpperCamelCase , return_tensors='''pt''' ).pixel_values with torch.no_grad(): __lowercase : List[Any] = model(__UpperCamelCase ) __lowercase : Union[str, Any] = outputs.logits print(logits.shape ) print('''First values of logits:''' , logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": __lowercase : Tuple = torch.tensor( [[-7.5_958, -7.5_958, -7.4_302], [-7.5_958, -7.5_958, -7.4_302], [-7.4_797, -7.4_797, -7.3_068]] ) elif model_name == "upernet-swin-small": __lowercase : Optional[Any] = torch.tensor( [[-7.1_921, -7.1_921, -6.9_532], [-7.1_921, -7.1_921, -6.9_532], [-7.0_908, -7.0_908, -6.8_534]] ) elif model_name == "upernet-swin-base": __lowercase : Optional[int] = torch.tensor( [[-6.5_851, -6.5_851, -6.4_330], [-6.5_851, -6.5_851, -6.4_330], [-6.4_763, -6.4_763, -6.3_254]] ) elif model_name == "upernet-swin-large": __lowercase : Any = torch.tensor( [[-7.5_297, -7.5_297, -7.3_802], [-7.5_297, -7.5_297, -7.3_802], [-7.4_044, -7.4_044, -7.2_586]] ) print('''Logits:''' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , __UpperCamelCase , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(f"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(__UpperCamelCase ) if push_to_hub: print(f"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(f"""openmmlab/{model_name}""" ) processor.push_to_hub(f"""openmmlab/{model_name}""" ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-swin-tiny', type=str, choices=[F"upernet-swin-{size}" for size in ['tiny', 'small', 'base', 'large']], help='Name of the Swin + UperNet model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) a_ = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
249
1
from __future__ import annotations def a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ): """simple docstring""" UpperCamelCase : list[list[int]] = [] create_all_state(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , [] , SCREAMING_SNAKE_CASE_ ) return result def a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : list[list[int]] , ): """simple docstring""" if level == 0: total_list.append(current_list[:] ) return for i in range(SCREAMING_SNAKE_CASE_ , total_number - level + 2 ): current_list.append(SCREAMING_SNAKE_CASE_ ) create_all_state(i + 1 , SCREAMING_SNAKE_CASE_ , level - 1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) current_list.pop() def a ( SCREAMING_SNAKE_CASE_ : list[list[int]] ): """simple docstring""" for i in total_list: print(*SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": __UpperCAmelCase : List[str] = 4 __UpperCAmelCase : List[str] = 2 __UpperCAmelCase : Dict = generate_all_combinations(n, k) print_all_state(total_list)
315
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) __UpperCAmelCase : Union[str, Any] = logging.getLogger() def a ( ): """simple docstring""" UpperCamelCase : List[Any] = argparse.ArgumentParser() parser.add_argument('''-f''' ) UpperCamelCase : List[str] = parser.parse_args() return args.f class UpperCAmelCase_ ( _a): '''simple docstring''' def _lowercase ( self ): """simple docstring""" UpperCamelCase : List[str] = logging.StreamHandler(sys.stdout ) logger.addHandler(__SCREAMING_SNAKE_CASE ) def _lowercase ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase : Dict = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , '''run_glue_deebert.py''' ) with patch.object(__SCREAMING_SNAKE_CASE , '''argv''' , __SCREAMING_SNAKE_CASE ): UpperCamelCase : int = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(__SCREAMING_SNAKE_CASE , 0.666 ) @slow @require_torch_non_multi_gpu def _lowercase ( self ): """simple docstring""" UpperCamelCase : Any = ''' --model_type roberta --model_name_or_path roberta-base --task_name MRPC --do_train --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --max_seq_length 128 --per_gpu_eval_batch_size=1 --per_gpu_train_batch_size=8 --learning_rate 2e-4 --num_train_epochs 3 --overwrite_output_dir --seed 42 --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --save_steps 0 --overwrite_cache --eval_after_first_stage '''.split() self.run_and_check(__SCREAMING_SNAKE_CASE ) UpperCamelCase : Dict = ''' --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --eval_each_highway --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 '''.split() self.run_and_check(__SCREAMING_SNAKE_CASE ) UpperCamelCase : Union[str, Any] = ''' --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --early_exit_entropy 0.1 --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 '''.split() self.run_and_check(__SCREAMING_SNAKE_CASE )
315
1
'''simple docstring''' import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) a_ = logging.getLogger() a_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __magic_name__ ( self : Tuple , __lowercase : int ) -> Any: os.makedirs(__lowercase , exist_ok=__lowercase ) SCREAMING_SNAKE_CASE__ : List[str] ={'''source''': '''What is love ?''', '''target''': '''life'''} SCREAMING_SNAKE_CASE__ : Dict ={'''train''': 12, '''val''': 2, '''test''': 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: SCREAMING_SNAKE_CASE__ : int ='''\n'''.join([contents[field]] * n_lines[split] ) with open(os.path.join(__lowercase , F"{split}.{field}" ) , '''w''' ) as f: f.write(__lowercase ) def __magic_name__ ( self : Dict , __lowercase : int , __lowercase : str = "pytorch" ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[int] =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE__ : Optional[Any] =os.path.join(__lowercase , '''output''' ) SCREAMING_SNAKE_CASE__ : int =os.path.join(__lowercase , '''data''' ) self._create_dummy_data(data_dir=__lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =F"\n --data_dir {data_dir} \\n --output_dir {output_dir} \\n --model_name_or_path facebook/rag-sequence-base \\n --model_type rag_sequence \\n --do_train \\n --do_predict \\n --n_val -1 \\n --val_check_interval 1.0 \\n --train_batch_size 2 \\n --eval_batch_size 1 \\n --max_source_length 25 \\n --max_target_length 25 \\n --val_max_target_length 25 \\n --test_max_target_length 25 \\n --label_smoothing 0.1 \\n --dropout 0.1 \\n --attention_dropout 0.1 \\n --weight_decay 0.001 \\n --adam_epsilon 1e-08 \\n --max_grad_norm 0.1 \\n --lr_scheduler polynomial \\n --learning_rate 3e-04 \\n --num_train_epochs 1 \\n --warmup_steps 4 \\n --gradient_accumulation_steps 1 \\n --distributed-port 8787 \\n --use_dummy_dataset 1 \\n --distributed_retriever {distributed_retriever} \\n ".split() if gpus > 0: testargs.append(F"--gpus={gpus}" ) if is_apex_available(): testargs.append('''--fp16''' ) else: testargs.append('''--gpus=0''' ) testargs.append('''--distributed_backend=ddp_cpu''' ) testargs.append('''--num_processes=2''' ) SCREAMING_SNAKE_CASE__ : List[Any] =[sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(__lowercase , env=self.get_env() ) SCREAMING_SNAKE_CASE__ : Any =os.path.join(__lowercase , '''metrics.json''' ) with open(__lowercase ) as f: SCREAMING_SNAKE_CASE__ : Union[str, Any] =json.load(__lowercase ) return result @require_torch_gpu def __magic_name__ ( self : Any ) -> str: SCREAMING_SNAKE_CASE__ : Dict =self._run_finetune(gpus=1 ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_multi_gpu def __magic_name__ ( self : Any ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] =self._run_finetune(gpus=2 ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_gpu @require_ray def __magic_name__ ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : str =self._run_finetune(gpus=1 , distributed_retriever='''ray''' ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_multi_gpu @require_ray def __magic_name__ ( self : List[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[Any] =self._run_finetune(gpus=1 , distributed_retriever='''ray''' ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 )
152
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser a_ = re.compile(R'\s+') def _a( UpperCamelCase__ : str ): '''simple docstring''' return {"hash": hashlib.mda(re.sub(UpperCamelCase__, '''''', example['''content'''] ).encode('''utf-8''' ) ).hexdigest()} def _a( UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =[len(UpperCamelCase__ ) for line in example['''content'''].splitlines()] return {"line_mean": np.mean(UpperCamelCase__ ), "line_max": max(UpperCamelCase__ )} def _a( UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =np.mean([c.isalnum() for c in example['''content''']] ) return {"alpha_frac": alpha_frac} def _a( UpperCamelCase__ : Any, UpperCamelCase__ : Any ): '''simple docstring''' if example["hash"] in uniques: uniques.remove(example['''hash'''] ) return True else: return False def _a( UpperCamelCase__ : Any, UpperCamelCase__ : Optional[Any]=5 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] =['''auto-generated''', '''autogenerated''', '''automatically generated'''] SCREAMING_SNAKE_CASE__ : Dict =example['''content'''].splitlines() for _, line in zip(range(UpperCamelCase__ ), UpperCamelCase__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def _a( UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Tuple=5, UpperCamelCase__ : Optional[Any]=0.0_5 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple =['''unit tests''', '''test file''', '''configuration file'''] SCREAMING_SNAKE_CASE__ : List[Any] =example['''content'''].splitlines() SCREAMING_SNAKE_CASE__ : List[str] =0 SCREAMING_SNAKE_CASE__ : Optional[Any] =0 # first test for _, line in zip(range(UpperCamelCase__ ), UpperCamelCase__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test SCREAMING_SNAKE_CASE__ : List[str] =example['''content'''].count('''\n''' ) SCREAMING_SNAKE_CASE__ : Optional[int] =int(coeff * nlines ) for line in lines: count_config += line.lower().count('''config''' ) count_test += line.lower().count('''test''' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def _a( UpperCamelCase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =['''def ''', '''class ''', '''for ''', '''while '''] SCREAMING_SNAKE_CASE__ : List[Any] =example['''content'''].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def _a( UpperCamelCase__ : Any, UpperCamelCase__ : Dict=4 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] =example['''content'''].splitlines() SCREAMING_SNAKE_CASE__ : Optional[Any] =0 for line in lines: counter += line.lower().count('''=''' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def _a( UpperCamelCase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str =tokenizer(example['''content'''], truncation=UpperCamelCase__ )['''input_ids'''] SCREAMING_SNAKE_CASE__ : Optional[Any] =len(example['''content'''] ) / len(UpperCamelCase__ ) return {"ratio": ratio} def _a( UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict ={} results.update(get_hash(UpperCamelCase__ ) ) results.update(line_stats(UpperCamelCase__ ) ) results.update(alpha_stats(UpperCamelCase__ ) ) results.update(char_token_ratio(UpperCamelCase__ ) ) results.update(is_autogenerated(UpperCamelCase__ ) ) results.update(is_config_or_test(UpperCamelCase__ ) ) results.update(has_no_keywords(UpperCamelCase__ ) ) results.update(has_few_assignments(UpperCamelCase__ ) ) return results def _a( UpperCamelCase__ : Tuple, UpperCamelCase__ : List[Any], UpperCamelCase__ : str ): '''simple docstring''' if not check_uniques(UpperCamelCase__, UpperCamelCase__ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def _a( UpperCamelCase__ : str ): '''simple docstring''' with open(UpperCamelCase__, '''rb''' ) as f_in: with gzip.open(str(UpperCamelCase__ ) + '''.gz''', '''wb''', compresslevel=6 ) as f_out: shutil.copyfileobj(UpperCamelCase__, UpperCamelCase__ ) os.unlink(UpperCamelCase__ ) # Settings a_ = HfArgumentParser(PreprocessingArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing a_ = time.time() a_ = ds.map(preprocess, num_proc=args.num_workers) print(F'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes a_ = set(ds.unique('hash')) a_ = len(uniques) / len(ds) print(F'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics a_ = time.time() a_ = ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args}) print(F'''Time to filter dataset: {time.time()-t_start:.2f}''') print(F'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: a_ = time.time() a_ , a_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(F'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file a_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / 'duplicate_clusters.json', 'w') as f: json.dump(duplicate_clusters, f) a_ = output_dir / 'data' data_dir.mkdir(exist_ok=True) a_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): a_ = str(data_dir / F'''file-{file_number+1:012}.json''') a_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F'''Time to save dataset: {time.time()-t_start:.2f}''')
152
1
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A : List[str] = logging.getLogger(__name__) @dataclass class A : '''simple docstring''' A__ = 42 A__ = 42 A__ = 42 @dataclass class A : '''simple docstring''' A__ = 42 A__ = 42 A__ = None A__ = None class A ( __lowercase ): '''simple docstring''' A__ = "train" A__ = "dev" A__ = "test" class A : '''simple docstring''' @staticmethod def lowerCamelCase__ (_UpperCAmelCase : List[Any] , _UpperCAmelCase : Dict ) -> List[InputExample]: """simple docstring""" raise NotImplementedError @staticmethod def lowerCamelCase__ (_UpperCAmelCase : List[str] ) -> List[str]: """simple docstring""" raise NotImplementedError @staticmethod def lowerCamelCase__ (_UpperCAmelCase : Dict , _UpperCAmelCase : List[str] , _UpperCAmelCase : Dict , _UpperCAmelCase : Tuple , _UpperCAmelCase : str=False , _UpperCAmelCase : Any="[CLS]" , _UpperCAmelCase : Optional[Any]=1 , _UpperCAmelCase : Optional[int]="[SEP]" , _UpperCAmelCase : Any=False , _UpperCAmelCase : List[Any]=False , _UpperCAmelCase : Union[str, Any]=0 , _UpperCAmelCase : int=0 , _UpperCAmelCase : Optional[Any]=-100 , _UpperCAmelCase : int=0 , _UpperCAmelCase : Tuple=True , ) -> List[InputFeatures]: """simple docstring""" lowercase__ = {label: i for i, label in enumerate(_a )} lowercase__ = [] for ex_index, example in enumerate(_a ): if ex_index % 1_0000 == 0: logger.info("""Writing example %d of %d""" , _a , len(_a ) ) lowercase__ = [] lowercase__ = [] for word, label in zip(example.words , example.labels ): lowercase__ = tokenizer.tokenize(_a ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(_a ) > 0: tokens.extend(_a ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_a ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. lowercase__ = tokenizer.num_special_tokens_to_add() if len(_a ) > max_seq_length - special_tokens_count: lowercase__ = tokens[: (max_seq_length - special_tokens_count)] lowercase__ = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] lowercase__ = [sequence_a_segment_id] * len(_a ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: lowercase__ = [cls_token] + tokens lowercase__ = [pad_token_label_id] + label_ids lowercase__ = [cls_token_segment_id] + segment_ids lowercase__ = tokenizer.convert_tokens_to_ids(_a ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. lowercase__ = [1 if mask_padding_with_zero else 0] * len(_a ) # Zero-pad up to the sequence length. lowercase__ = max_seq_length - len(_a ) if pad_on_left: lowercase__ = ([pad_token] * padding_length) + input_ids lowercase__ = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask lowercase__ = ([pad_token_segment_id] * padding_length) + segment_ids lowercase__ = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(_a ) == max_seq_length assert len(_a ) == max_seq_length assert len(_a ) == max_seq_length assert len(_a ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(_a ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(_a ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(_a ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(_a ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(_a ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: lowercase__ = None features.append( InputFeatures( input_ids=_a , attention_mask=_a , token_type_ids=_a , label_ids=_a ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A ( __lowercase ): '''simple docstring''' A__ = 42 A__ = nn.CrossEntropyLoss().ignore_index def __init__(self : Optional[Any] , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Tuple , _UpperCAmelCase : str , _UpperCAmelCase : Tuple , _UpperCAmelCase : List[Any] , _UpperCAmelCase : str = None , _UpperCAmelCase : Dict=False , _UpperCAmelCase : Union[str, Any] = Split.train , ) -> List[Any]: """simple docstring""" lowercase__ = os.path.join( _a , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(_a ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. lowercase__ = cached_features_file + '''.lock''' with FileLock(_a ): if os.path.exists(_a ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) lowercase__ = torch.load(_a ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) lowercase__ = token_classification_task.read_examples_from_file(_a , _a ) # TODO clean up all this to leverage built-in features of tokenizers lowercase__ = token_classification_task.convert_examples_to_features( _a , _a , _a , _a , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_a , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , _a ) def __len__(self : str ) -> Union[str, Any]: """simple docstring""" return len(self.features ) def __getitem__(self : Optional[Any] , _UpperCAmelCase : Tuple ) -> InputFeatures: """simple docstring""" return self.features[i] if is_tf_available(): import tensorflow as tf class A : '''simple docstring''' A__ = 42 A__ = -1_00 def __init__(self : Optional[int] , _UpperCAmelCase : str , _UpperCAmelCase : Any , _UpperCAmelCase : List[Any] , _UpperCAmelCase : int , _UpperCAmelCase : List[str] , _UpperCAmelCase : Optional[Any] = None , _UpperCAmelCase : Any=False , _UpperCAmelCase : List[Any] = Split.train , ) -> List[Any]: """simple docstring""" lowercase__ = token_classification_task.read_examples_from_file(_a , _a ) # TODO clean up all this to leverage built-in features of tokenizers lowercase__ = token_classification_task.convert_examples_to_features( _a , _a , _a , _a , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_a , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: lowercase__ = tf.data.Dataset.from_generator( _a , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: lowercase__ = tf.data.Dataset.from_generator( _a , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def lowerCamelCase__ (self : Tuple ) -> Optional[int]: """simple docstring""" lowercase__ = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__(self : Tuple ) -> int: """simple docstring""" return len(self.features ) def __getitem__(self : List[str] , _UpperCAmelCase : Any ) -> InputFeatures: """simple docstring""" return self.features[i]
365
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A : Union[str, Any] = logging.get_logger(__name__) A : int = { 'andreasmadsen/efficient_mlm_m0.40': ( 'https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json' ), } class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = '''roberta-prelayernorm''' def __init__(self : Dict , _UpperCAmelCase : List[Any]=5_0265 , _UpperCAmelCase : List[Any]=768 , _UpperCAmelCase : str=12 , _UpperCAmelCase : Any=12 , _UpperCAmelCase : Any=3072 , _UpperCAmelCase : int="gelu" , _UpperCAmelCase : Tuple=0.1 , _UpperCAmelCase : Tuple=0.1 , _UpperCAmelCase : Any=512 , _UpperCAmelCase : Dict=2 , _UpperCAmelCase : int=0.02 , _UpperCAmelCase : List[Any]=1E-1_2 , _UpperCAmelCase : Tuple=1 , _UpperCAmelCase : int=0 , _UpperCAmelCase : int=2 , _UpperCAmelCase : Optional[Any]="absolute" , _UpperCAmelCase : int=True , _UpperCAmelCase : Optional[int]=None , **_UpperCAmelCase : Any , ) -> List[str]: """simple docstring""" super().__init__(pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , **_UpperCAmelCase ) lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = hidden_act lowercase__ = intermediate_size lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = position_embedding_type lowercase__ = use_cache lowercase__ = classifier_dropout class A ( UpperCAmelCase__ ): '''simple docstring''' @property def lowerCamelCase__ (self : Any ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": lowercase__ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: lowercase__ = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
146
0