code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import os lowerCAmelCase : List[str] = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 1_00, 'D': 5_00, 'M': 10_00} def A_( A : str): UpperCamelCase = 0 UpperCamelCase = 0 while index < len(A) - 1: UpperCamelCase = SYMBOLS[numerals[index]] UpperCamelCase = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def A_( A : int): UpperCamelCase = '' UpperCamelCase = num // 1000 numerals += m_count * "M" num %= 1000 UpperCamelCase = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 UpperCamelCase = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def A_( A : str = "/p089_roman.txt"): UpperCamelCase = 0 with open(os.path.dirname(A) + roman_numerals_filename) as filea: UpperCamelCase = filea.readlines() for line in lines: UpperCamelCase = line.strip() UpperCamelCase = parse_roman_numerals(A) UpperCamelCase = generate_roman_numerals(A) savings += len(A) - len(A) return savings if __name__ == "__main__": print(f"""{solution() = }""")
3
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowercase_ ( lowerCAmelCase_ ): def _lowerCAmelCase ( self : Any ): snake_case__ : Union[str, Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowerCamelCase , 'tf_padding' ) ) self.parent.assertTrue(hasattr(__lowerCamelCase , 'depth_multiplier' ) ) class lowercase_ : def __init__( self : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict=13 , __lowerCamelCase : Optional[Any]=3 , __lowerCamelCase : str=32 , __lowerCamelCase : str=0.2_5 , __lowerCamelCase : List[Any]=8 , __lowerCamelCase : List[Any]=8 , __lowerCamelCase : Union[str, Any]=6 , __lowerCamelCase : Optional[Any]=32 , __lowerCamelCase : Dict=True , __lowerCamelCase : str=True , __lowerCamelCase : int=True , __lowerCamelCase : Tuple="relu6" , __lowerCamelCase : List[str]=1280 , __lowerCamelCase : Optional[Any]=0.1 , __lowerCamelCase : Tuple=0.0_2 , __lowerCamelCase : str=True , __lowerCamelCase : int=True , __lowerCamelCase : int=10 , __lowerCamelCase : int=None , ): snake_case__ : Dict = parent snake_case__ : Union[str, Any] = batch_size snake_case__ : List[Any] = num_channels snake_case__ : List[str] = image_size snake_case__ : Optional[int] = depth_multiplier snake_case__ : int = depth_divisible_by snake_case__ : List[Any] = min_depth snake_case__ : Dict = expand_ratio snake_case__ : Optional[Any] = tf_padding snake_case__ : List[Any] = output_stride snake_case__ : List[str] = first_layer_is_expansion snake_case__ : Optional[Any] = finegrained_output snake_case__ : int = hidden_act snake_case__ : List[Any] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) snake_case__ : List[str] = classifier_dropout_prob snake_case__ : List[Any] = use_labels snake_case__ : Tuple = is_training snake_case__ : Dict = num_labels snake_case__ : Any = initializer_range snake_case__ : int = scope def _lowerCAmelCase ( self : int ): snake_case__ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None if self.use_labels: snake_case__ : Dict = ids_tensor([self.batch_size] , self.num_labels ) snake_case__ : List[str] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case__ : List[Any] = self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Tuple ): return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _lowerCAmelCase ( self : Dict , __lowerCamelCase : str , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] ): snake_case__ : Optional[Any] = MobileNetVaModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() snake_case__ : List[Any] = model(__lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def _lowerCAmelCase ( self : str , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict ): snake_case__ : Optional[int] = self.num_labels snake_case__ : int = MobileNetVaForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() snake_case__ : int = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Dict , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ): snake_case__ : Tuple = self.num_labels snake_case__ : Optional[Any] = MobileNetVaForSemanticSegmentation(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() snake_case__ : Optional[Any] = model(__lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) snake_case__ : Dict = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _lowerCAmelCase ( self : Any ): snake_case__ : List[Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ , snake_case__ : str = config_and_inputs snake_case__ : Union[str, Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowercase_ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) A_ = ( { "feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification, "image-segmentation": MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) A_ = False A_ = False A_ = False A_ = False def _lowerCAmelCase ( self : Dict ): snake_case__ : List[Any] = MobileNetVaModelTester(self ) snake_case__ : str = MobileNetVaConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def _lowerCAmelCase ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason='MobileNetV2 does not use inputs_embeds' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass @unittest.skip(reason='MobileNetV2 does not support input and output embeddings' ) def _lowerCAmelCase ( self : int ): pass @unittest.skip(reason='MobileNetV2 does not output attentions' ) def _lowerCAmelCase ( self : Tuple ): pass def _lowerCAmelCase ( self : Any ): snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : str = model_class(__lowerCamelCase ) snake_case__ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Union[str, Any] = [*signature.parameters.keys()] snake_case__ : int = ['pixel_values'] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _lowerCAmelCase ( self : List[str] ): snake_case__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _lowerCAmelCase ( self : Tuple ): def check_hidden_states_output(__lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : List[str] ): snake_case__ : Tuple = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): snake_case__ : List[str] = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) snake_case__ : List[str] = outputs.hidden_states snake_case__ : List[Any] = 16 self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : List[Any] = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[Any] = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _lowerCAmelCase ( self : List[str] ): snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def _lowerCAmelCase ( self : str ): snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCamelCase ) @slow def _lowerCAmelCase ( self : Dict ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : Any = MobileNetVaModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def UpperCamelCase__ ( ) -> Dict: snake_case__ : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class lowercase_ ( unittest.TestCase ): @cached_property def _lowerCAmelCase ( self : Tuple ): return ( MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224' ) if is_vision_available() else None ) @slow def _lowerCAmelCase ( self : int ): snake_case__ : Dict = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224' ).to(__lowerCamelCase ) snake_case__ : int = self.default_image_processor snake_case__ : Optional[Any] = prepare_img() snake_case__ : str = image_processor(images=__lowerCamelCase , return_tensors='pt' ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): snake_case__ : Any = model(**__lowerCamelCase ) # verify the logits snake_case__ : Tuple = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) snake_case__ : int = torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1E-4 ) ) @slow def _lowerCAmelCase ( self : int ): snake_case__ : str = MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513' ) snake_case__ : int = model.to(__lowerCamelCase ) snake_case__ : Any = MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513' ) snake_case__ : Any = prepare_img() snake_case__ : Dict = image_processor(images=__lowerCamelCase , return_tensors='pt' ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): snake_case__ : Any = model(**__lowerCamelCase ) snake_case__ : Optional[int] = outputs.logits # verify the logits snake_case__ : str = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , __lowerCamelCase ) snake_case__ : Optional[Any] = torch.tensor( [ [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]], [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]], [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]], ] , device=__lowerCamelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __lowerCamelCase , atol=1E-4 ) )
270
0
"""simple docstring""" def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ) -> str: if not (isinstance(__UpperCAmelCase , __UpperCAmelCase ) and isinstance(__UpperCAmelCase , __UpperCAmelCase )): raise ValueError("longest_common_substring() takes two strings for inputs" ) SCREAMING_SNAKE_CASE__ = len(__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = len(__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = [[0] * (texta_length + 1) for _ in range(texta_length + 1 )] SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for i in range(1 , texta_length + 1 ): for j in range(1 , texta_length + 1 ): if texta[i - 1] == texta[j - 1]: SCREAMING_SNAKE_CASE__ = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = dp[i][j] return texta[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
715
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _A = HUGGINGFACE_HUB_CACHE _A = 'config.json' _A = 'diffusion_pytorch_model.bin' _A = 'diffusion_flax_model.msgpack' _A = 'model.onnx' _A = 'diffusion_pytorch_model.safetensors' _A = 'weights.pb' _A = 'https://huggingface.co' _A = default_cache_path _A = 'diffusers_modules' _A = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) _A = ['fp16', 'non-ema'] _A = '.self_attn'
538
0
"""simple docstring""" __magic_name__ = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def _A ( ): """simple docstring""" lowerCamelCase__ = input("""Enter message: """ ) lowerCamelCase__ = input("""Enter key [alphanumeric]: """ ) lowerCamelCase__ = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): lowerCamelCase__ = """encrypt""" lowerCamelCase__ = encrypt_message(__lowercase , __lowercase ) elif mode.lower().startswith("""d""" ): lowerCamelCase__ = """decrypt""" lowerCamelCase__ = decrypt_message(__lowercase , __lowercase ) print(f"""\n{mode.title()}ed message:""" ) print(__lowercase ) def _A ( __lowercase , __lowercase ): """simple docstring""" return translate_message(__lowercase , __lowercase , """encrypt""" ) def _A ( __lowercase , __lowercase ): """simple docstring""" return translate_message(__lowercase , __lowercase , """decrypt""" ) def _A ( __lowercase , __lowercase , __lowercase ): """simple docstring""" lowerCamelCase__ = [] lowerCamelCase__ = 0 lowerCamelCase__ = key.upper() for symbol in message: lowerCamelCase__ = 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(__lowercase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__lowercase ): lowerCamelCase__ = 0 else: translated.append(__lowercase ) return "".join(__lowercase ) if __name__ == "__main__": main()
129
"""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 SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): snake_case = CTRLTokenizer snake_case = False snake_case = False def __UpperCAmelCase ( self : List[str] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCamelCase__ = ["""adapt""", """re@@""", """a@@""", """apt""", """c@@""", """t""", """<unk>"""] lowerCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase__ = ["""#version: 0.2""", """a p""", """ap t</w>""", """r e""", """a d""", """ad apt</w>""", """"""] lowerCamelCase__ = {"""unk_token""": """<unk>"""} lowerCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) lowerCamelCase__ = 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(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def __UpperCAmelCase ( self : str , **SCREAMING_SNAKE_CASE_ : Optional[int] ): kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE_ : List[Any] ): lowerCamelCase__ = """adapt react readapt apt""" lowerCamelCase__ = """adapt react readapt apt""" return input_text, output_text def __UpperCAmelCase ( self : List[Any] ): lowerCamelCase__ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCamelCase__ = """adapt react readapt apt""" lowerCamelCase__ = """adapt re@@ a@@ c@@ t re@@ adapt apt""".split() lowerCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = tokens + [tokenizer.unk_token] lowerCamelCase__ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
129
1
import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class UpperCamelCase_ : '''simple docstring''' def __init__( self , a , a , a = True , a = False ) -> List[Any]: snake_case_ = scheduler snake_case_ = optimizers if isinstance(_UpperCAmelCase , (list, tuple) ) else [optimizers] snake_case_ = split_batches snake_case_ = step_with_optimizer snake_case_ = GradientState() def _UpperCamelCase ( self , *a , **a ) -> Optional[int]: if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*_UpperCAmelCase , **_UpperCAmelCase ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*_UpperCAmelCase , **_UpperCAmelCase ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step snake_case_ = AcceleratorState().num_processes for _ in range(_UpperCAmelCase ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , 'total_steps' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*_UpperCAmelCase , **_UpperCAmelCase ) else: self.scheduler.step(*_UpperCAmelCase , **_UpperCAmelCase ) def _UpperCamelCase ( self ) -> Any: return self.scheduler.get_last_lr() def _UpperCamelCase ( self ) -> Any: return self.scheduler.state_dict() def _UpperCamelCase ( self , a ) -> Optional[Any]: self.scheduler.load_state_dict(_UpperCAmelCase ) def _UpperCamelCase ( self ) -> Optional[int]: return self.scheduler.get_lr() def _UpperCamelCase ( self , *a , **a ) -> Optional[int]: return self.scheduler.print_lr(*_UpperCAmelCase , **_UpperCAmelCase )
714
# 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 lowercase = "\nHuman: <<task>>\n\nAssistant: " lowercase = "huggingface-tools/default-prompts" lowercase = {"chat": "chat_prompt_template.txt", "run": "run_prompt_template.txt"} def __UpperCAmelCase ( a_ , a_ , a_="run"): if prompt_or_repo_id is None: snake_case_ = DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search('\\s' , a_) is not None: return prompt_or_repo_id snake_case_ = cached_file( a_ , PROMPT_FILES[mode] , repo_type='dataset' , user_agent={'agent': agent_name}) with open(a_ , 'r' , encoding='utf-8') as f: return f.read()
607
0
"""simple docstring""" import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 __A : Optional[Any] = { 'return_dict': False, 'output_hidden_states': True, 'output_attentions': True, 'torchscript': True, 'torch_dtype': 'float16', 'use_bfloat16': True, 'tf_legacy_loss': True, 'pruned_heads': {'a': 1}, 'tie_word_embeddings': False, 'is_decoder': True, 'cross_attention_hidden_size': 1_2_8, 'add_cross_attention': True, 'tie_encoder_decoder': True, 'max_length': 5_0, 'min_length': 3, 'do_sample': True, 'early_stopping': True, 'num_beams': 3, 'num_beam_groups': 3, 'diversity_penalty': 0.5, 'temperature': 2.0, 'top_k': 1_0, 'top_p': 0.7, 'typical_p': 0.2, 'repetition_penalty': 0.8, 'length_penalty': 0.8, 'no_repeat_ngram_size': 5, 'encoder_no_repeat_ngram_size': 5, 'bad_words_ids': [1, 2, 3], 'num_return_sequences': 3, 'chunk_size_feed_forward': 5, 'output_scores': True, 'return_dict_in_generate': True, 'forced_bos_token_id': 2, 'forced_eos_token_id': 3, 'remove_invalid_values': True, 'architectures': ['BertModel'], 'finetuning_task': 'translation', 'id2label': {0: 'label'}, 'label2id': {'label': '0'}, 'tokenizer_class': 'BertTokenizerFast', 'prefix': 'prefix', 'bos_token_id': 6, 'pad_token_id': 7, 'eos_token_id': 8, 'sep_token_id': 9, 'decoder_start_token_id': 1_0, 'exponential_decay_length_penalty': (5, 1.01), 'suppress_tokens': [0, 1], 'begin_suppress_tokens': 2, 'task_specific_params': {'translation': 'some_params'}, 'problem_type': 'regression', } @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @classmethod def snake_case ( cls : str ): __lowercase : List[str] = TOKEN HfFolder.save_token(lowercase__ ) @classmethod def snake_case ( cls : Optional[Any] ): try: delete_repo(token=cls._token , repo_id="test-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config" ) except HTTPError: pass def snake_case ( self : Any ): __lowercase : Optional[Any] = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) config.push_to_hub("test-config" , use_auth_token=self._token ) __lowercase : List[str] = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase__ , getattr(lowercase__ , lowercase__ ) ) # Reset repo delete_repo(token=self._token , repo_id="test-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase__ , repo_id="test-config" , push_to_hub=lowercase__ , use_auth_token=self._token ) __lowercase : Optional[int] = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase__ , getattr(lowercase__ , lowercase__ ) ) def snake_case ( self : str ): __lowercase : str = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token ) __lowercase : Optional[int] = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase__ , getattr(lowercase__ , lowercase__ ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase__ , repo_id="valid_org/test-config-org" , push_to_hub=lowercase__ , use_auth_token=self._token ) __lowercase : List[Any] = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase__ , getattr(lowercase__ , lowercase__ ) ) def snake_case ( self : List[str] ): CustomConfig.register_for_auto_class() __lowercase : Any = CustomConfig(attribute=4_2 ) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} ) __lowercase : List[str] = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=lowercase__ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig" ) self.assertEqual(new_config.attribute , 4_2 ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def snake_case ( self : Union[str, Any] ): __lowercase : Dict = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated __lowercase : Optional[int] = c.n_embd + 1 # int __lowercase : int = c.resid_pdrop + 1.0 # float __lowercase : int = not c.scale_attn_weights # bool __lowercase : Union[str, Any] = c.summary_type + "foo" # str c.update_from_string( f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(lowercase__ , c.n_embd , "mismatch for key: n_embd" ) self.assertEqual(lowercase__ , c.resid_pdrop , "mismatch for key: resid_pdrop" ) self.assertEqual(lowercase__ , c.scale_attn_weights , "mismatch for key: scale_attn_weights" ) self.assertEqual(lowercase__ , c.summary_type , "mismatch for key: summary_type" ) def snake_case ( self : str ): __lowercase : Optional[Any] = PretrainedConfig() __lowercase : List[Any] = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( lowercase__ , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] ) __lowercase : Any = [key for key, value in config_common_kwargs.items() if value == getattr(lowercase__ , lowercase__ )] if len(lowercase__ ) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" f' {", ".join(lowercase__ )}.' ) def snake_case ( self : List[str] ): with self.assertRaises(lowercase__ ): # config is in subfolder, the following should not work without specifying the subfolder __lowercase : str = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" ) __lowercase : Optional[int] = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" ) self.assertIsNotNone(lowercase__ ) def snake_case ( self : str ): # A mock response for an HTTP head request to emulate server down __lowercase : Tuple = mock.Mock() __lowercase : Optional[Any] = 5_0_0 __lowercase : Tuple = {} __lowercase : List[Any] = HTTPError __lowercase : Optional[Any] = {} # Download this model to make sure it's in the cache. __lowercase : str = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=lowercase__ ) as mock_head: __lowercase : List[Any] = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() def snake_case ( self : Any ): # This test is for deprecated behavior and can be removed in v5 __lowercase : Any = BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" ) def snake_case ( self : List[str] ): __lowercase : Dict = AutoConfig.from_pretrained("bert-base-cased" ) __lowercase : Tuple = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(lowercase__ ) __lowercase : Tuple = 2 json.dump(configuration.to_dict() , open(os.path.join(lowercase__ , "config.4.0.0.json" ) , "w" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 __lowercase : str = AutoConfig.from_pretrained(lowercase__ ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 __lowercase : int = ["config.42.0.0.json"] __lowercase : Dict = 7_6_8 configuration.save_pretrained(lowercase__ ) shutil.move(os.path.join(lowercase__ , "config.4.0.0.json" ) , os.path.join(lowercase__ , "config.42.0.0.json" ) ) __lowercase : Optional[Any] = AutoConfig.from_pretrained(lowercase__ ) self.assertEqual(new_configuration.hidden_size , 7_6_8 ) def snake_case ( self : List[Any] ): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. __lowercase : Any = "hf-internal-testing/test-two-configs" import transformers as new_transformers __lowercase : Any = "v4.0.0" __lowercase ,__lowercase : str = new_transformers.models.auto.AutoConfig.from_pretrained( lowercase__ , return_unused_kwargs=lowercase__ ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(lowercase__ , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers __lowercase : List[str] = "v3.0.0" __lowercase : Dict = old_transformers.models.auto.AutoConfig.from_pretrained(lowercase__ ) self.assertEqual(old_configuration.hidden_size , 7_6_8 )
575
"""simple docstring""" from math import factorial, pi def snake_case__ ( _lowerCamelCase, _lowerCamelCase = 30 ) ->float: """simple docstring""" if not isinstance(_lowerCamelCase, (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(_lowerCamelCase, _lowerCamelCase ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) __lowercase : List[str] = float(_lowerCamelCase ) __lowercase : Any = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(_lowerCamelCase ) ) def snake_case__ ( _lowerCamelCase, _lowerCamelCase = 30 ) ->float: """simple docstring""" if not isinstance(_lowerCamelCase, (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(_lowerCamelCase, _lowerCamelCase ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) __lowercase : List[str] = float(_lowerCamelCase ) __lowercase : str = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(_lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(1_0)) print(maclaurin_sin(-1_0)) print(maclaurin_sin(1_0, 1_5)) print(maclaurin_sin(-1_0, 1_5)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(1_0, 1_5)) print(maclaurin_cos(-1_0, 1_5))
575
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json', } class __a ( _snake_case ): __SCREAMING_SNAKE_CASE : Tuple = 'gpt_neox_japanese' def __init__( self : Any , lowercase__ : Dict=3_20_00 , lowercase__ : Dict=25_60 , lowercase__ : str=32 , lowercase__ : Optional[int]=32 , lowercase__ : int=4 , lowercase__ : Union[str, Any]="gelu" , lowercase__ : Dict=1.00 , lowercase__ : Optional[int]=1_00_00 , lowercase__ : Optional[int]=20_48 , lowercase__ : Any=0.02 , lowercase__ : List[Any]=1e-5 , lowercase__ : List[str]=True , lowercase__ : Optional[Any]=3_19_96 , lowercase__ : List[Any]=3_19_99 , lowercase__ : Any=0.1 , lowercase__ : Union[str, Any]=0.0 , **lowercase__ : Union[str, Any] , ) ->Any: """simple docstring""" super().__init__(bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__) _lowercase = vocab_size _lowercase = max_position_embeddings _lowercase = hidden_size _lowercase = num_hidden_layers _lowercase = num_attention_heads _lowercase = intermediate_multiple_size _lowercase = hidden_act _lowercase = rotary_pct _lowercase = rotary_emb_base _lowercase = initializer_range _lowercase = layer_norm_eps _lowercase = use_cache _lowercase = attention_dropout _lowercase = hidden_dropout
721
'''simple docstring''' import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json', 'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json', 'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json', } class __a ( _snake_case ): __SCREAMING_SNAKE_CASE : Optional[Any] = 'owlvit_text_model' def __init__( self : Union[str, Any] , lowercase__ : Union[str, Any]=4_94_08 , lowercase__ : List[str]=5_12 , lowercase__ : Optional[Any]=20_48 , lowercase__ : List[str]=12 , lowercase__ : List[Any]=8 , lowercase__ : List[Any]=16 , lowercase__ : List[str]="quick_gelu" , lowercase__ : Tuple=1e-5 , lowercase__ : int=0.0 , lowercase__ : str=0.02 , lowercase__ : List[Any]=1.0 , lowercase__ : int=0 , lowercase__ : int=4_94_06 , lowercase__ : int=4_94_07 , **lowercase__ : Any , ) ->Tuple: """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__) _lowercase = vocab_size _lowercase = hidden_size _lowercase = intermediate_size _lowercase = num_hidden_layers _lowercase = num_attention_heads _lowercase = max_position_embeddings _lowercase = hidden_act _lowercase = layer_norm_eps _lowercase = attention_dropout _lowercase = initializer_range _lowercase = initializer_factor @classmethod def _UpperCAmelCase ( cls : List[Any] , lowercase__ : Union[str, os.PathLike] , **lowercase__ : Tuple) ->"PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(lowercase__) _lowercase , _lowercase = cls.get_config_dict(lowercase__ , **lowercase__) # get the text config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""") == "owlvit": _lowercase = 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(lowercase__ , **lowercase__) class __a ( _snake_case ): __SCREAMING_SNAKE_CASE : str = 'owlvit_vision_model' def __init__( self : Optional[int] , lowercase__ : Dict=7_68 , lowercase__ : Tuple=30_72 , lowercase__ : List[str]=12 , lowercase__ : str=12 , lowercase__ : Any=3 , lowercase__ : Union[str, Any]=7_68 , lowercase__ : Union[str, Any]=32 , lowercase__ : Dict="quick_gelu" , lowercase__ : Tuple=1e-5 , lowercase__ : List[Any]=0.0 , lowercase__ : List[str]=0.02 , lowercase__ : List[Any]=1.0 , **lowercase__ : List[Any] , ) ->int: """simple docstring""" super().__init__(**lowercase__) _lowercase = hidden_size _lowercase = intermediate_size _lowercase = num_hidden_layers _lowercase = num_attention_heads _lowercase = num_channels _lowercase = image_size _lowercase = patch_size _lowercase = hidden_act _lowercase = layer_norm_eps _lowercase = attention_dropout _lowercase = initializer_range _lowercase = initializer_factor @classmethod def _UpperCAmelCase ( cls : Optional[int] , lowercase__ : Union[str, os.PathLike] , **lowercase__ : Optional[int]) ->"PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(lowercase__) _lowercase , _lowercase = cls.get_config_dict(lowercase__ , **lowercase__) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""") == "owlvit": _lowercase = 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(lowercase__ , **lowercase__) class __a ( _snake_case ): __SCREAMING_SNAKE_CASE : Optional[Any] = 'owlvit' __SCREAMING_SNAKE_CASE : Tuple = True def __init__( self : str , lowercase__ : List[str]=None , lowercase__ : int=None , lowercase__ : str=5_12 , lowercase__ : Any=2.6592 , lowercase__ : List[str]=True , **lowercase__ : str , ) ->Tuple: """simple docstring""" super().__init__(**lowercase__) if text_config is None: _lowercase = {} logger.info("""text_config is None. Initializing the OwlViTTextConfig with default values.""") if vision_config is None: _lowercase = {} logger.info("""vision_config is None. initializing the OwlViTVisionConfig with default values.""") _lowercase = OwlViTTextConfig(**lowercase__) _lowercase = OwlViTVisionConfig(**lowercase__) _lowercase = projection_dim _lowercase = logit_scale_init_value _lowercase = return_dict _lowercase = 1.0 @classmethod def _UpperCAmelCase ( cls : int , lowercase__ : Union[str, os.PathLike] , **lowercase__ : List[str]) ->"PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(lowercase__) _lowercase , _lowercase = cls.get_config_dict(lowercase__ , **lowercase__) 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(lowercase__ , **lowercase__) @classmethod def _UpperCAmelCase ( cls : Optional[int] , lowercase__ : Dict , lowercase__ : Dict , **lowercase__ : str) ->Union[str, Any]: """simple docstring""" _lowercase = {} _lowercase = text_config _lowercase = vision_config return cls.from_dict(lowercase__ , **lowercase__) def _UpperCAmelCase ( self : Tuple) ->Tuple: """simple docstring""" _lowercase = copy.deepcopy(self.__dict__) _lowercase = self.text_config.to_dict() _lowercase = self.vision_config.to_dict() _lowercase = self.__class__.model_type return output class __a ( _snake_case ): @property def _UpperCAmelCase ( self : List[str]) ->Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ]) @property def _UpperCAmelCase ( self : Union[str, Any]) ->Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""logits_per_image""", {0: """batch"""}), ("""logits_per_text""", {0: """batch"""}), ("""text_embeds""", {0: """batch"""}), ("""image_embeds""", {0: """batch"""}), ]) @property def _UpperCAmelCase ( self : str) ->float: """simple docstring""" return 1e-4 def _UpperCAmelCase ( self : str , lowercase__ : "ProcessorMixin" , lowercase__ : int = -1 , lowercase__ : int = -1 , lowercase__ : Optional["TensorType"] = None , ) ->Mapping[str, Any]: """simple docstring""" _lowercase = super().generate_dummy_inputs( processor.tokenizer , batch_size=lowercase__ , seq_length=lowercase__ , framework=lowercase__) _lowercase = super().generate_dummy_inputs( processor.image_processor , batch_size=lowercase__ , framework=lowercase__) return {**text_input_dict, **image_input_dict} @property def _UpperCAmelCase ( self : Any) ->int: """simple docstring""" return 14
572
0
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=1E-1_2 ): __a = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__UpperCamelCase , axis=1 ) , a_min=__UpperCamelCase ) ).T __a = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__UpperCamelCase , axis=1 ) , a_min=__UpperCamelCase ) ).T return jnp.matmul(__UpperCamelCase , norm_emb_a.T ) class __UpperCAmelCase ( nn.Module ): """simple docstring""" _lowerCamelCase = 42 _lowerCamelCase = jnp.floataa def snake_case_ ( self ): __a = FlaxCLIPVisionModule(self.config.vision_config ) __a = nn.Dense(self.config.projection_dim , use_bias=A_ , dtype=self.dtype ) __a = self.param("""concept_embeds""" , jax.nn.initializers.ones , (17, self.config.projection_dim) ) __a = self.param( """special_care_embeds""" , jax.nn.initializers.ones , (3, self.config.projection_dim) ) __a = self.param("""concept_embeds_weights""" , jax.nn.initializers.ones , (17,) ) __a = self.param("""special_care_embeds_weights""" , jax.nn.initializers.ones , (3,) ) def __call__( self , __A ): __a = self.vision_model(A_ )[1] __a = self.visual_projection(A_ ) __a = jax_cosine_distance(A_ , self.special_care_embeds ) __a = jax_cosine_distance(A_ , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs __a = 0.0 __a = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment __a = jnp.round(A_ , 3 ) __a = jnp.any(special_scores > 0 , axis=1 , keepdims=A_ ) # Use a lower threshold if an image has any special care concept __a = is_special_care * 0.01 __a = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment __a = jnp.round(A_ , 3 ) __a = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class __UpperCAmelCase ( UpperCamelCase_ ): """simple docstring""" _lowerCamelCase = CLIPConfig _lowerCamelCase = """clip_input""" _lowerCamelCase = FlaxStableDiffusionSafetyCheckerModule def __init__( self , __A , __A = None , __A = 0 , __A = jnp.floataa , __A = True , **__A , ): if input_shape is None: __a = (1, 224, 224, 3) __a = self.module_class(config=A_ , dtype=A_ , **A_ ) super().__init__(A_ , A_ , input_shape=A_ , seed=A_ , dtype=A_ , _do_init=_do_init ) def snake_case_ ( self , __A , __A , __A = None ): # init input tensor __a = jax.random.normal(A_ , A_ ) __a = jax.random.split(A_ ) __a = {'''params''': params_rng, '''dropout''': dropout_rng} __a = self.module.init(A_ , A_ )['''params'''] return random_params def __call__( self , __A , __A = None , ): __a = jnp.transpose(A_ , (0, 2, 3, 1) ) return self.module.apply( {"""params""": params or self.params} , jnp.array(A_ , dtype=jnp.floataa ) , rngs={} , )
99
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def UpperCamelCase( __UpperCamelCase : int ,__UpperCamelCase : Dict ,__UpperCamelCase : Dict=1e-1_2 ): lowerCAmelCase_ : Optional[Any] = jnp.divide(emb_a.T ,jnp.clip(jnp.linalg.norm(__UpperCamelCase ,axis=1 ) ,a_min=__UpperCamelCase ) ).T lowerCAmelCase_ : int = jnp.divide(emb_a.T ,jnp.clip(jnp.linalg.norm(__UpperCamelCase ,axis=1 ) ,a_min=__UpperCamelCase ) ).T return jnp.matmul(__UpperCamelCase ,norm_emb_a.T ) class __snake_case ( nn.Module ): _a = 42 _a = jnp.floataa def UpperCAmelCase__ ( self : str): lowerCAmelCase_ : List[str] = FlaxCLIPVisionModule(self.config.vision_config) lowerCAmelCase_ : Union[str, Any] = nn.Dense(self.config.projection_dim , use_bias=A_ , dtype=self.dtype) lowerCAmelCase_ : List[str] = self.param('''concept_embeds''' , jax.nn.initializers.ones , (1_7, self.config.projection_dim)) lowerCAmelCase_ : Optional[int] = self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim)) lowerCAmelCase_ : int = self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (1_7,)) lowerCAmelCase_ : str = self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,)) def __call__( self : Optional[Any] , A_ : Tuple): lowerCAmelCase_ : Tuple = self.vision_model(A_)[1] lowerCAmelCase_ : Any = self.visual_projection(A_) lowerCAmelCase_ : List[Any] = jax_cosine_distance(A_ , self.special_care_embeds) lowerCAmelCase_ : Any = jax_cosine_distance(A_ , self.concept_embeds) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs lowerCAmelCase_ : int = 0.0 lowerCAmelCase_ : List[Any] = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment lowerCAmelCase_ : str = jnp.round(A_ , 3) lowerCAmelCase_ : int = jnp.any(special_scores > 0 , axis=1 , keepdims=A_) # Use a lower threshold if an image has any special care concept lowerCAmelCase_ : Any = is_special_care * 0.01 lowerCAmelCase_ : Dict = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment lowerCAmelCase_ : str = jnp.round(A_ , 3) lowerCAmelCase_ : List[str] = jnp.any(concept_scores > 0 , axis=1) return has_nsfw_concepts class __snake_case ( UpperCamelCase_ ): _a = CLIPConfig _a = '''clip_input''' _a = FlaxStableDiffusionSafetyCheckerModule def __init__( self : Optional[Any] , A_ : CLIPConfig , A_ : Optional[Tuple] = None , A_ : int = 0 , A_ : jnp.dtype = jnp.floataa , A_ : bool = True , **A_ : Union[str, Any] , ): if input_shape is None: lowerCAmelCase_ : List[Any] = (1, 2_2_4, 2_2_4, 3) lowerCAmelCase_ : List[Any] = self.module_class(config=A_ , dtype=A_ , **A_) super().__init__(A_ , A_ , input_shape=A_ , seed=A_ , dtype=A_ , _do_init=_do_init) def UpperCAmelCase__ ( self : List[str] , A_ : jax.random.KeyArray , A_ : Tuple , A_ : FrozenDict = None): # init input tensor lowerCAmelCase_ : Optional[Any] = jax.random.normal(A_ , A_) lowerCAmelCase_ , lowerCAmelCase_ : Any = jax.random.split(A_) lowerCAmelCase_ : Union[str, Any] = {'''params''': params_rng, '''dropout''': dropout_rng} lowerCAmelCase_ : str = self.module.init(A_ , A_)['''params'''] return random_params def __call__( self : Any , A_ : str , A_ : dict = None , ): lowerCAmelCase_ : Dict = jnp.transpose(A_ , (0, 2, 3, 1)) return self.module.apply( {'''params''': params or self.params} , jnp.array(A_ , dtype=jnp.floataa) , rngs={} , )
171
0
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE ( snake_case, snake_case, snake_case, snake_case): # Initialise PyTorch model __snake_case = BigBirdConfig.from_json_file(snake_case) print(f"Building PyTorch model from configuration: {config}") if is_trivia_qa: __snake_case = BigBirdForQuestionAnswering(snake_case) else: __snake_case = BigBirdForPreTraining(snake_case) # Load weights from tf checkpoint load_tf_weights_in_big_bird(snake_case, snake_case, is_trivia_qa=snake_case) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}") model.save_pretrained(snake_case) if __name__ == "__main__": __lowercase : Union[str, 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( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) __lowercase : Tuple = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
705
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class _A ( unittest.TestCase ): """simple docstring""" def lowercase ( self : Tuple ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self : int ) -> Tuple: __snake_case = StableDiffusionKDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) __snake_case = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) sd_pipe.set_scheduler('''sample_euler''' ) __snake_case = '''A painting of a squirrel eating a burger''' __snake_case = torch.manual_seed(0 ) __snake_case = sd_pipe([prompt] , generator=A_ , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __snake_case = np.array([0.04_47, 0.04_92, 0.04_68, 0.04_08, 0.03_83, 0.04_08, 0.03_54, 0.03_80, 0.03_39] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowercase ( self : Optional[Any] ) -> Tuple: __snake_case = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) __snake_case = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) sd_pipe.set_scheduler('''sample_euler''' ) __snake_case = '''A painting of a squirrel eating a burger''' __snake_case = torch.manual_seed(0 ) __snake_case = sd_pipe([prompt] , generator=A_ , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __snake_case = np.array([0.12_37, 0.13_20, 0.14_38, 0.13_59, 0.13_90, 0.11_32, 0.12_77, 0.11_75, 0.11_12] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def lowercase ( self : List[str] ) -> Optional[Any]: __snake_case = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) __snake_case = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) sd_pipe.set_scheduler('''sample_dpmpp_2m''' ) __snake_case = '''A painting of a squirrel eating a burger''' __snake_case = torch.manual_seed(0 ) __snake_case = sd_pipe( [prompt] , generator=A_ , guidance_scale=7.5 , num_inference_steps=15 , output_type='''np''' , use_karras_sigmas=A_ , ) __snake_case = output.images __snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __snake_case = np.array( [0.11_38_16_89, 0.12_11_29_21, 0.1_38_94_57, 0.12_54_96_06, 0.1_24_49_64, 0.10_83_15_17, 0.11_56_28_66, 0.10_86_78_16, 0.10_49_90_48] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
93
0
'''simple docstring''' from collections import namedtuple lowercase =namedtuple('from_to', 'from_ to') lowercase ={ 'cubicmeter': from_to(1, 1), 'litre': from_to(0.001, 1000), 'kilolitre': from_to(1, 1), 'gallon': from_to(0.0_0454, 264.172), 'cubicyard': from_to(0.7_6455, 1.3_0795), 'cubicfoot': from_to(0.028, 35.3147), 'cup': from_to(0.0_0023_6588, 4226.75), } def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : int ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( f"Invalid \'from_type\' value: {from_type!r} Supported values are:\n" + ', '.join(__lowerCamelCase ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"Invalid \'to_type\' value: {to_type!r}. Supported values are:\n" + ', '.join(__lowerCamelCase ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
446
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class A_ : '''simple docstring''' def __init__(self , lowercase__ , lowercase__=2 , lowercase__=True , lowercase__=False , lowercase__=10 , lowercase__=3 , lowercase__=32 * 8 , lowercase__=32 * 8 , lowercase__=4 , lowercase__=64 , ) -> Dict: __UpperCAmelCase = parent __UpperCAmelCase = batch_size __UpperCAmelCase = is_training __UpperCAmelCase = use_auxiliary_loss __UpperCAmelCase = num_queries __UpperCAmelCase = num_channels __UpperCAmelCase = min_size __UpperCAmelCase = max_size __UpperCAmelCase = num_labels __UpperCAmelCase = hidden_dim __UpperCAmelCase = hidden_dim def lowerCAmelCase_ (self ) -> Dict: __UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( lowercase__ ) __UpperCAmelCase = torch.ones([self.batch_size, self.min_size, self.max_size] , device=lowercase__ ) __UpperCAmelCase = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=lowercase__ ) > 0.5 ).float() __UpperCAmelCase = (torch.rand((self.batch_size, self.num_labels) , device=lowercase__ ) > 0.5).long() __UpperCAmelCase = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowerCAmelCase_ (self ) -> Dict: __UpperCAmelCase = MaskaFormerConfig( hidden_size=self.hidden_dim , ) __UpperCAmelCase = self.num_queries __UpperCAmelCase = self.num_labels __UpperCAmelCase = [1, 1, 1, 1] __UpperCAmelCase = self.num_channels __UpperCAmelCase = 64 __UpperCAmelCase = 128 __UpperCAmelCase = self.hidden_dim __UpperCAmelCase = self.hidden_dim __UpperCAmelCase = self.hidden_dim return config def lowerCAmelCase_ (self ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = self.prepare_config_and_inputs() __UpperCAmelCase = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def lowerCAmelCase_ (self , lowercase__ , lowercase__ ) -> Optional[int]: __UpperCAmelCase = output.encoder_hidden_states __UpperCAmelCase = output.pixel_decoder_hidden_states __UpperCAmelCase = output.transformer_decoder_hidden_states self.parent.assertTrue(len(lowercase__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(lowercase__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(lowercase__ ) , config.decoder_layers ) def lowerCAmelCase_ (self , lowercase__ , lowercase__ , lowercase__ , lowercase__=False ) -> Union[str, Any]: with torch.no_grad(): __UpperCAmelCase = MaskaFormerModel(config=lowercase__ ) model.to(lowercase__ ) model.eval() __UpperCAmelCase = model(pixel_values=lowercase__ , pixel_mask=lowercase__ ) __UpperCAmelCase = model(lowercase__ , output_hidden_states=lowercase__ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(lowercase__ , lowercase__ ) def lowerCAmelCase_ (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> List[str]: __UpperCAmelCase = MaskaFormerForUniversalSegmentation(config=lowercase__ ) model.to(lowercase__ ) model.eval() def comm_check_on_output(lowercase__ ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __UpperCAmelCase = model(pixel_values=lowercase__ , pixel_mask=lowercase__ ) __UpperCAmelCase = model(lowercase__ ) comm_check_on_output(lowercase__ ) __UpperCAmelCase = model( pixel_values=lowercase__ , pixel_mask=lowercase__ , mask_labels=lowercase__ , class_labels=lowercase__ ) comm_check_on_output(lowercase__ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class A_ ( _a , _a , unittest.TestCase ): '''simple docstring''' a__ = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () a__ = {"feature-extraction": MaskaFormerModel} if is_torch_available() else {} a__ = False a__ = False a__ = False a__ = False def lowerCAmelCase_ (self ) -> Optional[Any]: __UpperCAmelCase = MaskaFormerModelTester(self ) __UpperCAmelCase = ConfigTester(self , config_class=lowercase__ , has_text_modality=lowercase__ ) def lowerCAmelCase_ (self ) -> Any: self.config_tester.run_common_tests() def lowerCAmelCase_ (self ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(lowercase__ , **lowercase__ , output_hidden_states=lowercase__ ) def lowerCAmelCase_ (self ) -> Any: __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*lowercase__ ) @unittest.skip(reason='''Mask2Former does not use inputs_embeds''' ) def lowerCAmelCase_ (self ) -> Tuple: pass @unittest.skip(reason='''Mask2Former does not have a get_input_embeddings method''' ) def lowerCAmelCase_ (self ) -> str: pass @unittest.skip(reason='''Mask2Former is not a generative model''' ) def lowerCAmelCase_ (self ) -> Optional[Any]: pass @unittest.skip(reason='''Mask2Former does not use token embeddings''' ) def lowerCAmelCase_ (self ) -> List[Any]: pass @require_torch_multi_gpu @unittest.skip( reason='''Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def lowerCAmelCase_ (self ) -> Optional[int]: pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def lowerCAmelCase_ (self ) -> Optional[Any]: pass def lowerCAmelCase_ (self ) -> Dict: __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase = model_class(lowercase__ ) __UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase = [*signature.parameters.keys()] __UpperCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase__ ) @slow def lowerCAmelCase_ (self ) -> int: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: __UpperCAmelCase = MaskaFormerModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def lowerCAmelCase_ (self ) -> List[str]: __UpperCAmelCase = (self.model_tester.min_size,) * 2 __UpperCAmelCase = { '''pixel_values''': torch.randn((2, 3, *size) , device=lowercase__ ), '''mask_labels''': torch.randn((2, 10, *size) , device=lowercase__ ), '''class_labels''': torch.zeros(2 , 10 , device=lowercase__ ).long(), } __UpperCAmelCase = self.model_tester.get_config() __UpperCAmelCase = MaskaFormerForUniversalSegmentation(lowercase__ ).to(lowercase__ ) __UpperCAmelCase = model(**lowercase__ ) self.assertTrue(outputs.loss is not None ) def lowerCAmelCase_ (self ) -> Any: __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(lowercase__ , **lowercase__ , output_hidden_states=lowercase__ ) def lowerCAmelCase_ (self ) -> Dict: __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase = model_class(lowercase__ ).to(lowercase__ ) __UpperCAmelCase = model(**lowercase__ , output_attentions=lowercase__ ) self.assertTrue(outputs.attentions is not None ) def lowerCAmelCase_ (self ) -> str: if not self.model_tester.is_training: return __UpperCAmelCase = self.all_model_classes[1] __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() __UpperCAmelCase = model_class(lowercase__ ) model.to(lowercase__ ) model.train() __UpperCAmelCase = model(lowercase__ , mask_labels=lowercase__ , class_labels=lowercase__ ).loss loss.backward() def lowerCAmelCase_ (self ) -> List[Any]: __UpperCAmelCase = self.all_model_classes[1] __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() __UpperCAmelCase = True __UpperCAmelCase = True __UpperCAmelCase = model_class(lowercase__ ).to(lowercase__ ) model.train() __UpperCAmelCase = model(lowercase__ , mask_labels=lowercase__ , class_labels=lowercase__ ) __UpperCAmelCase = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __UpperCAmelCase = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() __UpperCAmelCase = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __UpperCAmelCase = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=lowercase__ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) A_ : List[Any] = 1e-4 def __a ( ) -> str: '''simple docstring''' __UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def lowerCAmelCase_ (self ) -> Union[str, Any]: return "facebook/mask2former-swin-small-coco-instance" @cached_property def lowerCAmelCase_ (self ) -> List[str]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def lowerCAmelCase_ (self ) -> Optional[Any]: __UpperCAmelCase = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(lowercase__ ) __UpperCAmelCase = self.default_image_processor __UpperCAmelCase = prepare_img() __UpperCAmelCase = image_processor(lowercase__ , return_tensors='''pt''' ).to(lowercase__ ) __UpperCAmelCase = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowercase__ , (1, 3, 384, 384) ) with torch.no_grad(): __UpperCAmelCase = model(**lowercase__ ) __UpperCAmelCase = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(lowercase__ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , lowercase__ , atol=lowercase__ ) ) __UpperCAmelCase = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(lowercase__ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , lowercase__ , atol=lowercase__ ) ) __UpperCAmelCase = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(lowercase__ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , lowercase__ , atol=lowercase__ ) ) def lowerCAmelCase_ (self ) -> List[str]: __UpperCAmelCase = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowercase__ ).eval() __UpperCAmelCase = self.default_image_processor __UpperCAmelCase = prepare_img() __UpperCAmelCase = image_processor(lowercase__ , return_tensors='''pt''' ).to(lowercase__ ) __UpperCAmelCase = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowercase__ , (1, 3, 384, 384) ) with torch.no_grad(): __UpperCAmelCase = model(**lowercase__ ) # masks_queries_logits __UpperCAmelCase = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) __UpperCAmelCase = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] __UpperCAmelCase = torch.tensor(lowercase__ ).to(lowercase__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , lowercase__ , atol=lowercase__ ) ) # class_queries_logits __UpperCAmelCase = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) __UpperCAmelCase = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(lowercase__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , lowercase__ , atol=lowercase__ ) ) def lowerCAmelCase_ (self ) -> Optional[int]: __UpperCAmelCase = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowercase__ ).eval() __UpperCAmelCase = self.default_image_processor __UpperCAmelCase = image_processor( [np.zeros((3, 800, 1_333) ), np.zeros((3, 800, 1_333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='''pt''' , ) __UpperCAmelCase = inputs['''pixel_values'''].to(lowercase__ ) __UpperCAmelCase = [el.to(lowercase__ ) for el in inputs['''mask_labels''']] __UpperCAmelCase = [el.to(lowercase__ ) for el in inputs['''class_labels''']] with torch.no_grad(): __UpperCAmelCase = model(**lowercase__ ) self.assertTrue(outputs.loss is not None )
303
0
"""simple docstring""" from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function snake_case__ : Optional[Any] = 1.054571817e-34 # unit of ℏ : J * s snake_case__ : List[Any] = 3e8 # unit of c : m * s^-1 def _snake_case ( _snake_case : float , _snake_case : float , _snake_case : float ): if (force, area, distance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if force < 0: raise ValueError('''Magnitude of force can not be negative''' ) if distance < 0: raise ValueError('''Distance can not be negative''' ) if area < 0: raise ValueError('''Area can not be negative''' ) if force == 0: lowerCAmelCase : Union[str, Any] = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: lowerCAmelCase : List[str] = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: lowerCAmelCase : Optional[Any] = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError('''One and only one argument must be 0''' ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
637
"""simple docstring""" def _snake_case ( _snake_case : float , _snake_case : list[float] ): if discount_rate < 0: raise ValueError('''Discount rate cannot be negative''' ) if not cash_flows: raise ValueError('''Cash flows list cannot be empty''' ) lowerCAmelCase : List[str] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_snake_case ) ) return round(_snake_case , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
637
1
"""simple docstring""" from math import factorial def _snake_case ( _snake_case : Tuple , _snake_case : List[Any] ) -> int: '''simple docstring''' if n < k or k < 0: raise ValueError('Please enter positive integers for n and k where n >= k' ) return factorial(snake_case__ ) // (factorial(snake_case__ ) * factorial(n - k )) if __name__ == "__main__": print( '''The number of five-card hands possible from a standard''', F'''fifty-two card deck is: {combinations(52, 5)}\n''', ) print( '''If a class of 40 students must be arranged into groups of''', F'''4 for group projects, there are {combinations(40, 4)} ways''', '''to arrange them.\n''', ) print( '''If 10 teams are competing in a Formula One race, there''', F'''are {combinations(10, 3)} ways that first, second and''', '''third place can be awarded.''', )
7
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer UpperCamelCase__ :List[Any] = logging.get_logger(__name__) UpperCamelCase__ :Tuple = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} # See all MVP models at https://huggingface.co/models?filter=mvp UpperCamelCase__ :List[str] = { """vocab_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json""", }, """added_tokens.json""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json""", }, """merges_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt""", }, """tokenizer_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json""", }, } UpperCamelCase__ :List[Any] = { """RUCAIBox/mvp""": 1_024, } class A( lowerCamelCase__ ): """simple docstring""" A = VOCAB_FILES_NAMES A = PRETRAINED_VOCAB_FILES_MAP A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A = ["input_ids", "attention_mask"] A = MvpTokenizer def __init__( self , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , 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__=True , **SCREAMING_SNAKE_CASE__ , ) -> List[str]: """simple docstring""" super().__init__( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , errors=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , trim_offsets=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) _UpperCamelCase :int = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , SCREAMING_SNAKE_CASE__ ) != add_prefix_space: _UpperCamelCase :int = getattr(SCREAMING_SNAKE_CASE__ , pre_tok_state.pop('''type''' ) ) _UpperCamelCase :Optional[int] = add_prefix_space _UpperCamelCase :List[Any] = pre_tok_class(**SCREAMING_SNAKE_CASE__ ) _UpperCamelCase :Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _UpperCamelCase :Any = '''post_processor''' _UpperCamelCase :Optional[Any] = getattr(self.backend_tokenizer , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if tokenizer_component_instance: _UpperCamelCase :Optional[Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _UpperCamelCase :Optional[Any] = tuple(state['''sep'''] ) if "cls" in state: _UpperCamelCase :Optional[Any] = tuple(state['''cls'''] ) _UpperCamelCase :str = False if state.get('''add_prefix_space''' , SCREAMING_SNAKE_CASE__ ) != add_prefix_space: _UpperCamelCase :Optional[int] = add_prefix_space _UpperCamelCase :Union[str, Any] = True if state.get('''trim_offsets''' , SCREAMING_SNAKE_CASE__ ) != trim_offsets: _UpperCamelCase :Union[str, Any] = trim_offsets _UpperCamelCase :Optional[Any] = True if changes_to_apply: _UpperCamelCase :Union[str, Any] = getattr(SCREAMING_SNAKE_CASE__ , state.pop('''type''' ) ) _UpperCamelCase :Optional[Any] = component_class(**SCREAMING_SNAKE_CASE__ ) setattr(self.backend_tokenizer , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @property def _UpperCamelCase( self ) -> str: """simple docstring""" if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" _UpperCamelCase :List[Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else value _UpperCamelCase :int = value def _UpperCamelCase( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> BatchEncoding: """simple docstring""" _UpperCamelCase :int = kwargs.get('''is_split_into_words''' , SCREAMING_SNAKE_CASE__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> BatchEncoding: """simple docstring""" _UpperCamelCase :Dict = kwargs.get('''is_split_into_words''' , SCREAMING_SNAKE_CASE__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> Tuple[str]: """simple docstring""" _UpperCamelCase :Optional[Any] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> str: """simple docstring""" _UpperCamelCase :Optional[int] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> List[int]: """simple docstring""" _UpperCamelCase :Any = [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]
355
0
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: UpperCamelCase_ = s.rsplit(UpperCamelCase_ , UpperCamelCase_ ) return new.join(UpperCamelCase_ ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: # 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 lowerCAmelCase_ ( UpperCamelCase_ ) -> str: UpperCamelCase_ = {} UpperCamelCase_ = ["group_1", "group_2", "group_3", "group_4"] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: UpperCamelCase_ = key.replace(F'''{group_key}.''' , F'''{group_key}.group.''' ) if "res_path" in key: UpperCamelCase_ = key.replace("res_path." , "res_path.path." ) if key.endswith(".w" ): UpperCamelCase_ = rreplace(UpperCamelCase_ , ".w" , ".weight" , 1 ) if key.endswith(".b" ): UpperCamelCase_ = rreplace(UpperCamelCase_ , ".b" , ".bias" , 1 ) UpperCamelCase_ = value.float() return upgrade @torch.no_grad() def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=True ) -> str: from dall_e import Encoder UpperCamelCase_ = Encoder() if os.path.exists(UpperCamelCase_ ): UpperCamelCase_ = torch.load(UpperCamelCase_ ) else: UpperCamelCase_ = torch.hub.load_state_dict_from_url(UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = ckpt.state_dict() encoder.load_state_dict(UpperCamelCase_ ) if config_path is not None: UpperCamelCase_ = FlavaImageCodebookConfig.from_pretrained(UpperCamelCase_ ) else: UpperCamelCase_ = FlavaImageCodebookConfig() UpperCamelCase_ = FlavaImageCodebook(UpperCamelCase_ ).eval() UpperCamelCase_ = encoder.state_dict() UpperCamelCase_ = upgrade_state_dict(UpperCamelCase_ ) hf_model.load_state_dict(UpperCamelCase_ ) UpperCamelCase_ = hf_model.state_dict() UpperCamelCase_ = count_parameters(UpperCamelCase_ ) UpperCamelCase_ = count_parameters(UpperCamelCase_ ) assert torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1e-3 ) if save_checkpoint: hf_model.save_pretrained(UpperCamelCase_ ) else: return hf_state_dict if __name__ == "__main__": _UpperCAmelCase = 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('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') _UpperCAmelCase = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
721
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } _UpperCAmelCase = { 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } _UpperCAmelCase = { 'facebook/blenderbot_small-90M': 5_1_2, } class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES _UpperCamelCase : str = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : str = BlenderbotSmallTokenizer def __init__( self: Dict , _SCREAMING_SNAKE_CASE: Optional[int]=None , _SCREAMING_SNAKE_CASE: List[str]=None , _SCREAMING_SNAKE_CASE: Optional[int]="<|endoftext|>" , _SCREAMING_SNAKE_CASE: List[Any]="<|endoftext|>" , _SCREAMING_SNAKE_CASE: List[str]="<|endoftext|>" , _SCREAMING_SNAKE_CASE: Optional[Any]=False , _SCREAMING_SNAKE_CASE: int=True , **_SCREAMING_SNAKE_CASE: Optional[int] , ) -> int: """simple docstring""" super().__init__( ByteLevelBPETokenizer( vocab=_SCREAMING_SNAKE_CASE , merges=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE , ) , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = add_prefix_space def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Any=None ) -> List[str]: """simple docstring""" UpperCamelCase_ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase ( self: int , _SCREAMING_SNAKE_CASE: List[int] , _SCREAMING_SNAKE_CASE: Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCamelCase_ = [self.sep_token_id] UpperCamelCase_ = [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]
371
0
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def UpperCamelCase__ ( _A: Optional[Any] , _A: Dict=10 ): '''simple docstring''' __lowerCamelCase = [] for _ in range(_A ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def UpperCamelCase__ ( _A: Tuple , _A: Optional[Any]=10 ): '''simple docstring''' __lowerCamelCase = [] for step in range(_A ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: __lowerCamelCase = os.path.join(_A , """schedule.bin""" ) torch.save(scheduler.state_dict() , _A ) __lowerCamelCase = torch.load(_A ) scheduler.load_state_dict(_A ) return lrs @require_torch class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): self.assertEqual(len(UpperCAmelCase ) , len(UpperCAmelCase ) ) for a, b in zip(UpperCAmelCase , UpperCAmelCase ): self.assertAlmostEqual(UpperCAmelCase , UpperCAmelCase , delta=UpperCAmelCase ) def lowerCamelCase_ ( self ): __lowerCamelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCAmelCase ) __lowerCamelCase = torch.tensor([0.4, 0.2, -0.5] ) __lowerCamelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping __lowerCamelCase = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(1_0_0 ): __lowerCamelCase = criterion(UpperCAmelCase , UpperCAmelCase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def lowerCamelCase_ ( self ): __lowerCamelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCAmelCase ) __lowerCamelCase = torch.tensor([0.4, 0.2, -0.5] ) __lowerCamelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping __lowerCamelCase = Adafactor( params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=UpperCAmelCase , weight_decay=0.0 , relative_step=UpperCAmelCase , scale_parameter=UpperCAmelCase , warmup_init=UpperCAmelCase , ) for _ in range(1_0_0_0 ): __lowerCamelCase = criterion(UpperCAmelCase , UpperCAmelCase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" A = nn.Linear(50 ,50 ) if is_torch_available() else None A = AdamW(m.parameters() ,lr=10.0 ) if is_torch_available() else None A = 10 def lowerCamelCase_ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None ): self.assertEqual(len(UpperCAmelCase ) , len(UpperCAmelCase ) ) for a, b in zip(UpperCAmelCase , UpperCAmelCase ): self.assertAlmostEqual(UpperCAmelCase , UpperCAmelCase , delta=UpperCAmelCase , msg=UpperCAmelCase ) def lowerCamelCase_ ( self ): __lowerCamelCase = {"""num_warmup_steps""": 2, """num_training_steps""": 1_0} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) __lowerCamelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"""num_warmup_steps""": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, """num_cycles""": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, """power""": 2.0, """lr_end""": 1E-7}, [0.0, 5.0, 10.0, 7.6_56, 5.6_25, 3.9_06, 2.5, 1.4_06, 0.6_25, 0.1_56], ), get_inverse_sqrt_schedule: ( {"""num_warmup_steps""": 2}, [0.0, 5.0, 10.0, 8.1_65, 7.0_71, 6.3_25, 5.7_74, 5.3_45, 5.0, 4.7_14], ), } for scheduler_func, data in scheds.items(): __lowerCamelCase , __lowerCamelCase = data __lowerCamelCase = scheduler_func(self.optimizer , **UpperCAmelCase ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) __lowerCamelCase = unwrap_schedule(UpperCAmelCase , self.num_steps ) self.assertListAlmostEqual( UpperCAmelCase , UpperCAmelCase , tol=1E-2 , msg=f'''failed for {scheduler_func} in normal scheduler''' , ) __lowerCamelCase = scheduler_func(self.optimizer , **UpperCAmelCase ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(UpperCAmelCase ) # wrap to test picklability of the schedule __lowerCamelCase = unwrap_and_save_reload_schedule(UpperCAmelCase , self.num_steps ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase , msg=f'''failed for {scheduler_func} in save and reload''' ) class UpperCamelCase_ : """simple docstring""" def __init__( self , UpperCAmelCase ): __lowerCamelCase = fn def __call__( self , *UpperCAmelCase , **UpperCAmelCase ): return self.fn(*UpperCAmelCase , **UpperCAmelCase ) @classmethod def lowerCamelCase_ ( self , UpperCAmelCase ): __lowerCamelCase = list(map(self , scheduler.lr_lambdas ) )
479
from __future__ import annotations def UpperCamelCase__ ( _A: float , _A: float , _A: float ): '''simple docstring''' if days_between_payments <= 0: raise ValueError("""days_between_payments must be > 0""" ) if daily_interest_rate < 0: raise ValueError("""daily_interest_rate must be >= 0""" ) if principal <= 0: raise ValueError("""principal must be > 0""" ) return principal * daily_interest_rate * days_between_payments def UpperCamelCase__ ( _A: float , _A: float , _A: float , ): '''simple docstring''' if number_of_compounding_periods <= 0: raise ValueError("""number_of_compounding_periods must be > 0""" ) if nominal_annual_interest_rate_percentage < 0: raise ValueError("""nominal_annual_interest_rate_percentage must be >= 0""" ) if principal <= 0: raise ValueError("""principal must be > 0""" ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def UpperCamelCase__ ( _A: float , _A: float , _A: float , ): '''simple docstring''' if number_of_years <= 0: raise ValueError("""number_of_years must be > 0""" ) if nominal_annual_percentage_rate < 0: raise ValueError("""nominal_annual_percentage_rate must be >= 0""" ) if principal <= 0: raise ValueError("""principal must be > 0""" ) return compound_interest( _A , nominal_annual_percentage_rate / 365 , number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
479
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _snake_case = { """configuration_encodec""": [ """ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EncodecConfig""", ], """feature_extraction_encodec""": ["""EncodecFeatureExtractor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ """ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST""", """EncodecModel""", """EncodecPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
611
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class lowerCAmelCase : def __init__( self :Union[str, Any] , _lowercase :Dict , _lowercase :int=13 , _lowercase :Dict=32 , _lowercase :List[Any]=2 , _lowercase :Any=3 , _lowercase :Optional[Any]=16 , _lowercase :str=[1, 2, 1] , _lowercase :Tuple=[2, 2, 4] , _lowercase :int=2 , _lowercase :Optional[Any]=2.0 , _lowercase :List[Any]=True , _lowercase :Tuple=0.0 , _lowercase :List[str]=0.0 , _lowercase :List[str]=0.1 , _lowercase :Optional[int]="gelu" , _lowercase :Dict=False , _lowercase :Union[str, Any]=True , _lowercase :str=0.02 , _lowercase :str=1e-5 , _lowercase :Optional[Any]=True , _lowercase :Any=None , _lowercase :int=True , _lowercase :Any=10 , _lowercase :Optional[int]=8 , _lowercase :List[str]=["stage1", "stage2", "stage3"] , _lowercase :int=[1, 2, 3] , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = image_size lowercase__ = patch_size lowercase__ = num_channels lowercase__ = embed_dim lowercase__ = depths lowercase__ = num_heads lowercase__ = window_size lowercase__ = mlp_ratio lowercase__ = qkv_bias lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = drop_path_rate lowercase__ = hidden_act lowercase__ = use_absolute_embeddings lowercase__ = patch_norm lowercase__ = layer_norm_eps lowercase__ = initializer_range lowercase__ = is_training lowercase__ = scope lowercase__ = use_labels lowercase__ = type_sequence_label_size lowercase__ = encoder_stride lowercase__ = out_features lowercase__ = out_indices def UpperCAmelCase ( self :int ): '''simple docstring''' lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self :List[Any] ): '''simple docstring''' return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def UpperCAmelCase ( self :Any , _lowercase :List[Any] , _lowercase :List[str] , _lowercase :Optional[Any] ): '''simple docstring''' lowercase__ = MaskFormerSwinModel(config=_lowercase ) model.to(_lowercase ) model.eval() lowercase__ = model(_lowercase ) lowercase__ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowercase__ = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def UpperCAmelCase ( self :Tuple , _lowercase :int , _lowercase :Union[str, Any] , _lowercase :Any ): '''simple docstring''' lowercase__ = MaskFormerSwinBackbone(config=_lowercase ) model.to(_lowercase ) model.eval() lowercase__ = model(_lowercase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_lowercase ): lowercase__ = ["stem"] lowercase__ = MaskFormerSwinBackbone(config=_lowercase ) def UpperCAmelCase ( self :Union[str, Any] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ = config_and_inputs lowercase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase ( lowercase_ , lowercase_ , unittest.TestCase ): __lowerCamelCase = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) __lowerCamelCase = {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {} __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def UpperCAmelCase ( self :Dict ): '''simple docstring''' lowercase__ = MaskFormerSwinModelTester(self ) lowercase__ = ConfigTester(self , config_class=_lowercase , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" " `nn.DataParallel`" ) ) def UpperCAmelCase ( self :List[Any] ): '''simple docstring''' pass def UpperCAmelCase ( self :Optional[int] ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase ( self :str ): '''simple docstring''' return def UpperCAmelCase ( self :Any ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def UpperCAmelCase ( self :Tuple ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowercase ) @unittest.skip("Swin does not use inputs_embeds" ) def UpperCAmelCase ( self :List[str] ): '''simple docstring''' pass @unittest.skip("Swin does not support feedforward chunking" ) def UpperCAmelCase ( self :Union[str, Any] ): '''simple docstring''' pass def UpperCAmelCase ( self :List[str] ): '''simple docstring''' lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(_lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowercase , nn.Linear ) ) def UpperCAmelCase ( self :Dict ): '''simple docstring''' lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(_lowercase ) lowercase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ = [*signature.parameters.keys()] lowercase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , _lowercase ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" ) def UpperCAmelCase ( self :Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def UpperCAmelCase ( self :List[Any] ): '''simple docstring''' pass def UpperCAmelCase ( self :int , _lowercase :List[Any] , _lowercase :Dict , _lowercase :str , _lowercase :str ): '''simple docstring''' lowercase__ = model_class(_lowercase ) model.to(_lowercase ) model.eval() with torch.no_grad(): lowercase__ = model(**self._prepare_for_class(_lowercase , _lowercase ) ) lowercase__ = outputs.hidden_states lowercase__ = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowercase ) , _lowercase ) # Swin has a different seq_length lowercase__ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def UpperCAmelCase ( self :str ): '''simple docstring''' lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: lowercase__ = True self.check_hidden_states_output(_lowercase , _lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ = True self.check_hidden_states_output(_lowercase , _lowercase , _lowercase , _lowercase ) def UpperCAmelCase ( self :Optional[int] ): '''simple docstring''' lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = 3 lowercase__ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowercase__ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowercase__ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowercase__ = True self.check_hidden_states_output(_lowercase , _lowercase , _lowercase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ = True self.check_hidden_states_output(_lowercase , _lowercase , _lowercase , (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" ) def UpperCAmelCase ( self :Dict ): '''simple docstring''' pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def UpperCAmelCase ( self :Optional[Any] ): '''simple docstring''' pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def UpperCAmelCase ( self :Optional[Any] ): '''simple docstring''' pass def UpperCAmelCase ( self :Dict ): '''simple docstring''' lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_lowercase :Optional[Any] ): lowercase__ = 0 return t def check_equivalence(_lowercase :Optional[int] , _lowercase :List[str] , _lowercase :Optional[Any] , _lowercase :str={} ): with torch.no_grad(): lowercase__ = model(**_lowercase , return_dict=_lowercase , **_lowercase ) lowercase__ = model(**_lowercase , return_dict=_lowercase , **_lowercase ).to_tuple() def recursive_check(_lowercase :int , _lowercase :Dict ): if isinstance(_lowercase , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_lowercase , _lowercase ): recursive_check(_lowercase , _lowercase ) elif isinstance(_lowercase , _lowercase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_lowercase , _lowercase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_lowercase ) , set_nan_tensor_to_zero(_lowercase ) , atol=1e-5 ) , msg=( "Tuple and dict output are not equal. Difference:" f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' f''' {torch.isnan(_lowercase ).any()} and `inf`: {torch.isinf(_lowercase )}. Dict has''' f''' `nan`: {torch.isnan(_lowercase ).any()} and `inf`: {torch.isinf(_lowercase )}.''' ) , ) recursive_check(_lowercase , _lowercase ) for model_class in self.all_model_classes: lowercase__ = model_class(_lowercase ) model.to(_lowercase ) model.eval() lowercase__ = self._prepare_for_class(_lowercase , _lowercase ) lowercase__ = self._prepare_for_class(_lowercase , _lowercase ) check_equivalence(_lowercase , _lowercase , _lowercase ) lowercase__ = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) lowercase__ = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) check_equivalence(_lowercase , _lowercase , _lowercase ) lowercase__ = self._prepare_for_class(_lowercase , _lowercase ) lowercase__ = self._prepare_for_class(_lowercase , _lowercase ) check_equivalence(_lowercase , _lowercase , _lowercase , {"output_hidden_states": True} ) lowercase__ = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) lowercase__ = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) check_equivalence(_lowercase , _lowercase , _lowercase , {"output_hidden_states": True} ) @require_torch class lowerCAmelCase ( unittest.TestCase , lowercase_ ): __lowerCamelCase = (MaskFormerSwinBackbone,) if is_torch_available() else () __lowerCamelCase = MaskFormerSwinConfig def UpperCAmelCase ( self :Dict ): '''simple docstring''' lowercase__ = MaskFormerSwinModelTester(self ) def UpperCAmelCase ( self :str ): '''simple docstring''' lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = inputs_dict["pixel_values"].shape[0] for backbone_class in self.all_model_classes: lowercase__ = backbone_class(_lowercase ) backbone.to(_lowercase ) backbone.eval() lowercase__ = backbone(**_lowercase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _lowercase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True lowercase__ = backbone(**_lowercase , output_hidden_states=_lowercase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) lowercase__ , lowercase__ , lowercase__ = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: lowercase__ = backbone(**_lowercase , output_attentions=_lowercase ) self.assertIsNotNone(outputs.attentions )
611
1
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _A ( UpperCAmelCase_ ): def __init__( self : Any , lowerCamelCase__ : pyspark.sql.DataFrame , lowerCamelCase__ : Optional[NamedSplit] = None , lowerCamelCase__ : Optional[Features] = None , lowerCamelCase__ : bool = True , lowerCamelCase__ : str = None , lowerCamelCase__ : bool = False , lowerCamelCase__ : str = None , lowerCamelCase__ : bool = True , lowerCamelCase__ : str = "arrow" , **lowerCamelCase__ : Tuple , ): """simple docstring""" super().__init__( split=lowerCamelCase__ , features=lowerCamelCase__ , cache_dir=lowerCamelCase__ , keep_in_memory=lowerCamelCase__ , streaming=lowerCamelCase__ , **lowerCamelCase__ , ) __UpperCamelCase : Union[str, Any] = load_from_cache_file __UpperCamelCase : Dict = file_format __UpperCamelCase : str = Spark( df=lowerCamelCase__ , features=lowerCamelCase__ , cache_dir=lowerCamelCase__ , working_dir=lowerCamelCase__ , **lowerCamelCase__ , ) def a ( self : List[str] ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) __UpperCamelCase : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowerCamelCase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
269
import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _A ( UpperCAmelCase_ , unittest.TestCase ): lowercase_ : int = KandinskyVaaPipeline lowercase_ : Union[str, Any] = [ '''image_embeds''', '''negative_image_embeds''', ] lowercase_ : int = ['''image_embeds''', '''negative_image_embeds'''] lowercase_ : str = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] lowercase_ : str = False @property def a ( self : int ): """simple docstring""" return 32 @property def a ( self : str ): """simple docstring""" return 32 @property def a ( self : Optional[int] ): """simple docstring""" return self.time_input_dim @property def a ( self : Optional[int] ): """simple docstring""" return self.time_input_dim * 4 @property def a ( self : Optional[Any] ): """simple docstring""" return 1_00 @property def a ( self : str ): """simple docstring""" torch.manual_seed(0 ) __UpperCamelCase : int = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } __UpperCamelCase : Any = UNetaDConditionModel(**lowerCamelCase__ ) return model @property def a ( self : Union[str, Any] ): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def a ( self : int ): """simple docstring""" torch.manual_seed(0 ) __UpperCamelCase : Tuple = VQModel(**self.dummy_movq_kwargs ) return model def a ( self : Tuple ): """simple docstring""" __UpperCamelCase : str = self.dummy_unet __UpperCamelCase : Optional[int] = self.dummy_movq __UpperCamelCase : List[str] = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule="""linear""" , beta_start=0.0_0085 , beta_end=0.012 , clip_sample=lowerCamelCase__ , set_alpha_to_one=lowerCamelCase__ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=lowerCamelCase__ , ) __UpperCamelCase : str = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def a ( self : Optional[int] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Any=0 ): """simple docstring""" __UpperCamelCase : Tuple = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) __UpperCamelCase : Optional[int] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( lowerCamelCase__ ) if str(lowerCamelCase__ ).startswith("""mps""" ): __UpperCamelCase : Optional[int] = torch.manual_seed(lowerCamelCase__ ) else: __UpperCamelCase : int = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) __UpperCamelCase : Dict = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def a ( self : Dict ): """simple docstring""" __UpperCamelCase : Dict = """cpu""" __UpperCamelCase : Dict = self.get_dummy_components() __UpperCamelCase : Union[str, Any] = self.pipeline_class(**lowerCamelCase__ ) __UpperCamelCase : int = pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __UpperCamelCase : List[Any] = pipe(**self.get_dummy_inputs(lowerCamelCase__ ) ) __UpperCamelCase : List[Any] = output.images __UpperCamelCase : int = pipe( **self.get_dummy_inputs(lowerCamelCase__ ) , return_dict=lowerCamelCase__ , )[0] __UpperCamelCase : List[str] = image[0, -3:, -3:, -1] __UpperCamelCase : Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __UpperCamelCase : int = np.array( [0.623_7976, 1.0, 0.3644_1332, 1.0, 0.7063_9634, 0.2987_7186, 0.8565_2125, 0.521_6843, 0.5445_4046] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class _A ( unittest.TestCase ): def a ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def a ( self : List[Any] ): """simple docstring""" __UpperCamelCase : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy""" ) __UpperCamelCase : List[str] = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(lowerCamelCase__ ) __UpperCamelCase : int = KandinskyVaaPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa ) __UpperCamelCase : Optional[int] = pipeline.to(lowerCamelCase__ ) pipeline.set_progress_bar_config(disable=lowerCamelCase__ ) __UpperCamelCase : Optional[Any] = """red cat, 4k photo""" __UpperCamelCase : Tuple = torch.Generator(device="""cuda""" ).manual_seed(0 ) __UpperCamelCase , __UpperCamelCase : Union[str, Any] = pipe_prior( lowerCamelCase__ , generator=lowerCamelCase__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() __UpperCamelCase : Any = torch.Generator(device="""cuda""" ).manual_seed(0 ) __UpperCamelCase : Union[str, Any] = pipeline( image_embeds=lowerCamelCase__ , negative_image_embeds=lowerCamelCase__ , generator=lowerCamelCase__ , num_inference_steps=1_00 , output_type="""np""" , ) __UpperCamelCase : Any = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(lowerCamelCase__ , lowerCamelCase__ )
269
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} __UpperCAmelCase = { """vocab_file""": { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt""", }, """tokenizer_file""": { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json""" ), """google/realm-orqa-nq-openqa""": ( """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json""" ), """google/realm-orqa-nq-reader""": ( """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json""" ), """google/realm-orqa-wq-openqa""": ( """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json""" ), """google/realm-orqa-wq-reader""": ( """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json""" ), }, } __UpperCAmelCase = { """google/realm-cc-news-pretrained-embedder""": 512, """google/realm-cc-news-pretrained-encoder""": 512, """google/realm-cc-news-pretrained-scorer""": 512, """google/realm-cc-news-pretrained-openqa""": 512, """google/realm-orqa-nq-openqa""": 512, """google/realm-orqa-nq-reader""": 512, """google/realm-orqa-wq-openqa""": 512, """google/realm-orqa-wq-reader""": 512, } __UpperCAmelCase = { """google/realm-cc-news-pretrained-embedder""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-encoder""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-scorer""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-nq-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-nq-reader""": {"""do_lower_case""": True}, """google/realm-orqa-wq-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-wq-reader""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowerCamelCase : Dict =VOCAB_FILES_NAMES lowerCamelCase : Union[str, Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : List[Any] =PRETRAINED_INIT_CONFIGURATION lowerCamelCase : List[Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[int] =RealmTokenizer def __init__( self : Dict , lowerCAmelCase : Dict=None , lowerCAmelCase : str=None , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : Optional[Any]="[UNK]" , lowerCAmelCase : int="[SEP]" , lowerCAmelCase : List[str]="[PAD]" , lowerCAmelCase : List[str]="[CLS]" , lowerCAmelCase : str="[MASK]" , lowerCAmelCase : Optional[int]=True , lowerCAmelCase : List[str]=None , **lowerCAmelCase : Optional[int] , ) -> Any: """simple docstring""" super().__init__( lowerCAmelCase , tokenizer_file=lowerCAmelCase , do_lower_case=lowerCAmelCase , unk_token=lowerCAmelCase , sep_token=lowerCAmelCase , pad_token=lowerCAmelCase , cls_token=lowerCAmelCase , mask_token=lowerCAmelCase , tokenize_chinese_chars=lowerCAmelCase , strip_accents=lowerCAmelCase , **lowerCAmelCase , ) __lowerCAmelCase : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowerCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowerCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowerCAmelCase ) != tokenize_chinese_chars ): __lowerCAmelCase : Dict = getattr(lowerCAmelCase , normalizer_state.pop("""type""" ) ) __lowerCAmelCase : Any = do_lower_case __lowerCAmelCase : Tuple = strip_accents __lowerCAmelCase : Any = tokenize_chinese_chars __lowerCAmelCase : Optional[Any] = normalizer_class(**lowerCAmelCase ) __lowerCAmelCase : List[Any] = do_lower_case def SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : List[Any] ) -> Tuple: """simple docstring""" __lowerCAmelCase : List[str] = PaddingStrategy.MAX_LENGTH __lowerCAmelCase : List[Any] = text __lowerCAmelCase : Union[str, Any] = kwargs.pop("""text_pair""" , lowerCAmelCase ) __lowerCAmelCase : int = kwargs.pop("""return_tensors""" , lowerCAmelCase ) __lowerCAmelCase : int = { """input_ids""": [], """attention_mask""": [], """token_type_ids""": [], } for idx, candidate_text in enumerate(lowerCAmelCase ): if batch_text_pair is not None: __lowerCAmelCase : str = batch_text_pair[idx] else: __lowerCAmelCase : Optional[int] = None __lowerCAmelCase : Any = super().__call__(lowerCAmelCase , lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase ) __lowerCAmelCase : Dict = encoded_candidates.get("""input_ids""" ) __lowerCAmelCase : List[str] = encoded_candidates.get("""attention_mask""" ) __lowerCAmelCase : str = encoded_candidates.get("""token_type_ids""" ) if encoded_input_ids is not None: output_data["input_ids"].append(lowerCAmelCase ) if encoded_attention_mask is not None: output_data["attention_mask"].append(lowerCAmelCase ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(lowerCAmelCase ) __lowerCAmelCase : Optional[int] = {key: item for key, item in output_data.items() if len(lowerCAmelCase ) != 0} return BatchEncoding(lowerCAmelCase , tensor_type=lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase : Optional[int] , lowerCAmelCase : Any=None ) -> Any: """simple docstring""" __lowerCAmelCase : Union[str, Any] = [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 SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" __lowerCAmelCase : Optional[int] = [self.sep_token_id] __lowerCAmelCase : Union[str, 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 SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" __lowerCAmelCase : int = self._tokenizer.model.save(lowerCAmelCase , name=lowerCAmelCase ) return tuple(lowerCAmelCase )
218
from __future__ import annotations def snake_case_ (__A : list[int] , __A : int ) -> list[int]: __lowerCAmelCase : List[Any] = 0 __lowerCAmelCase : Optional[Any] = len(__A ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: __lowerCAmelCase : int = i + 1 else: __lowerCAmelCase : List[str] = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(F'{two_pointer([2, 7, 11, 15], 9) = }')
218
1
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def a__ ( lowercase__ , lowercase__ ): '''simple docstring''' UpperCAmelCase_ =checkpoint UpperCAmelCase_ ={} UpperCAmelCase_ =vae_state_dict["encoder.conv_in.weight"] UpperCAmelCase_ =vae_state_dict["encoder.conv_in.bias"] UpperCAmelCase_ =vae_state_dict["encoder.conv_out.weight"] UpperCAmelCase_ =vae_state_dict["encoder.conv_out.bias"] UpperCAmelCase_ =vae_state_dict["encoder.norm_out.weight"] UpperCAmelCase_ =vae_state_dict["encoder.norm_out.bias"] UpperCAmelCase_ =vae_state_dict["decoder.conv_in.weight"] UpperCAmelCase_ =vae_state_dict["decoder.conv_in.bias"] UpperCAmelCase_ =vae_state_dict["decoder.conv_out.weight"] UpperCAmelCase_ =vae_state_dict["decoder.conv_out.bias"] UpperCAmelCase_ =vae_state_dict["decoder.norm_out.weight"] UpperCAmelCase_ =vae_state_dict["decoder.norm_out.bias"] UpperCAmelCase_ =vae_state_dict["quant_conv.weight"] UpperCAmelCase_ =vae_state_dict["quant_conv.bias"] UpperCAmelCase_ =vae_state_dict["post_quant_conv.weight"] UpperCAmelCase_ =vae_state_dict["post_quant_conv.bias"] # Retrieves the keys for the encoder down blocks only UpperCAmelCase_ =len({".".join(layer.split("." )[:3] ) for layer in vae_state_dict if "encoder.down" in layer} ) UpperCAmelCase_ ={ layer_id: [key for key in vae_state_dict if F'down.{layer_id}' in key] for layer_id in range(lowercase__ ) } # Retrieves the keys for the decoder up blocks only UpperCAmelCase_ =len({".".join(layer.split("." )[:3] ) for layer in vae_state_dict if "decoder.up" in layer} ) UpperCAmelCase_ ={ layer_id: [key for key in vae_state_dict if F'up.{layer_id}' in key] for layer_id in range(lowercase__ ) } for i in range(lowercase__ ): UpperCAmelCase_ =[key for key in down_blocks[i] if F'down.{i}' in key and F'down.{i}.downsample' not in key] if F'encoder.down.{i}.downsample.conv.weight' in vae_state_dict: UpperCAmelCase_ =vae_state_dict.pop( F'encoder.down.{i}.downsample.conv.weight' ) UpperCAmelCase_ =vae_state_dict.pop( F'encoder.down.{i}.downsample.conv.bias' ) UpperCAmelCase_ =renew_vae_resnet_paths(lowercase__ ) UpperCAmelCase_ ={"old": F'down.{i}.block', "new": F'down_blocks.{i}.resnets'} assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , config=lowercase__ ) UpperCAmelCase_ =[key for key in vae_state_dict if "encoder.mid.block" in key] UpperCAmelCase_ =2 for i in range(1 , num_mid_res_blocks + 1 ): UpperCAmelCase_ =[key for key in mid_resnets if F'encoder.mid.block_{i}' in key] UpperCAmelCase_ =renew_vae_resnet_paths(lowercase__ ) UpperCAmelCase_ ={"old": F'mid.block_{i}', "new": F'mid_block.resnets.{i - 1}'} assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , config=lowercase__ ) UpperCAmelCase_ =[key for key in vae_state_dict if "encoder.mid.attn" in key] UpperCAmelCase_ =renew_vae_attention_paths(lowercase__ ) UpperCAmelCase_ ={"old": "mid.attn_1", "new": "mid_block.attentions.0"} assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , config=lowercase__ ) conv_attn_to_linear(lowercase__ ) for i in range(lowercase__ ): UpperCAmelCase_ =num_up_blocks - 1 - i UpperCAmelCase_ =[ key for key in up_blocks[block_id] if F'up.{block_id}' in key and F'up.{block_id}.upsample' not in key ] if F'decoder.up.{block_id}.upsample.conv.weight' in vae_state_dict: UpperCAmelCase_ =vae_state_dict[ F'decoder.up.{block_id}.upsample.conv.weight' ] UpperCAmelCase_ =vae_state_dict[ F'decoder.up.{block_id}.upsample.conv.bias' ] UpperCAmelCase_ =renew_vae_resnet_paths(lowercase__ ) UpperCAmelCase_ ={"old": F'up.{block_id}.block', "new": F'up_blocks.{i}.resnets'} assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , config=lowercase__ ) UpperCAmelCase_ =[key for key in vae_state_dict if "decoder.mid.block" in key] UpperCAmelCase_ =2 for i in range(1 , num_mid_res_blocks + 1 ): UpperCAmelCase_ =[key for key in mid_resnets if F'decoder.mid.block_{i}' in key] UpperCAmelCase_ =renew_vae_resnet_paths(lowercase__ ) UpperCAmelCase_ ={"old": F'mid.block_{i}', "new": F'mid_block.resnets.{i - 1}'} assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , config=lowercase__ ) UpperCAmelCase_ =[key for key in vae_state_dict if "decoder.mid.attn" in key] UpperCAmelCase_ =renew_vae_attention_paths(lowercase__ ) UpperCAmelCase_ ={"old": "mid.attn_1", "new": "mid_block.attentions.0"} assign_to_checkpoint(lowercase__ , lowercase__ , lowercase__ , additional_replacements=[meta_path] , config=lowercase__ ) conv_attn_to_linear(lowercase__ ) return new_checkpoint def a__ ( lowercase__ , lowercase__ , ): '''simple docstring''' UpperCAmelCase_ =requests.get( " https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml" ) UpperCAmelCase_ =io.BytesIO(r.content ) UpperCAmelCase_ =OmegaConf.load(lowercase__ ) UpperCAmelCase_ =5_1_2 UpperCAmelCase_ ="cuda" if torch.cuda.is_available() else "cpu" if checkpoint_path.endswith("safetensors" ): from safetensors import safe_open UpperCAmelCase_ ={} with safe_open(lowercase__ , framework="pt" , device="cpu" ) as f: for key in f.keys(): UpperCAmelCase_ =f.get_tensor(lowercase__ ) else: UpperCAmelCase_ =torch.load(lowercase__ , map_location=lowercase__ )["state_dict"] # Convert the VAE model. UpperCAmelCase_ =create_vae_diffusers_config(lowercase__ , image_size=lowercase__ ) UpperCAmelCase_ =custom_convert_ldm_vae_checkpoint(lowercase__ , lowercase__ ) UpperCAmelCase_ =AutoencoderKL(**lowercase__ ) vae.load_state_dict(lowercase__ ) vae.save_pretrained(lowercase__ ) if __name__ == "__main__": __lowercase : Tuple =argparse.ArgumentParser() parser.add_argument("""--vae_pt_path""", default=None, type=str, required=True, help="""Path to the VAE.pt to convert.""") parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the VAE.pt to convert.""") __lowercase : Optional[int] =parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
54
import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) __lowercase : Tuple =logging.getLogger(__name__) __lowercase : Optional[int] =tf.data.AUTOTUNE def a__ ( ): '''simple docstring''' UpperCAmelCase_ =argparse.ArgumentParser(description="Train a masked language model on TPU." ) parser.add_argument( "--pretrained_model_config" , type=lowercase__ , default="roberta-base" , help="The model config to use. Note that we don't copy the model's weights, only the config!" , ) parser.add_argument( "--tokenizer" , type=lowercase__ , default="unigram-tokenizer-wikitext" , help="The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size." , ) parser.add_argument( "--per_replica_batch_size" , type=lowercase__ , default=8 , help="Batch size per TPU core." , ) parser.add_argument( "--no_tpu" , action="store_true" , help="If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances." , ) parser.add_argument( "--tpu_name" , type=lowercase__ , help="Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs." , default="local" , ) parser.add_argument( "--tpu_zone" , type=lowercase__ , help="Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes." , ) parser.add_argument( "--gcp_project" , type=lowercase__ , help="Google cloud project name. Only used for non-Colab TPU nodes." ) parser.add_argument( "--bfloat16" , action="store_true" , help="Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU." , ) parser.add_argument( "--train_dataset" , type=lowercase__ , help="Path to training dataset to load. If the path begins with `gs://`" " then the dataset will be loaded from a Google Cloud Storage bucket." , ) parser.add_argument( "--shuffle_buffer_size" , type=lowercase__ , default=2**1_8 , help="Size of the shuffle buffer (in samples)" , ) parser.add_argument( "--eval_dataset" , type=lowercase__ , help="Path to evaluation dataset to load. If the path begins with `gs://`" " then the dataset will be loaded from a Google Cloud Storage bucket." , ) parser.add_argument( "--num_epochs" , type=lowercase__ , default=1 , help="Number of epochs to train for." , ) parser.add_argument( "--learning_rate" , type=lowercase__ , default=1E-4 , help="Learning rate to use for training." , ) parser.add_argument( "--weight_decay_rate" , type=lowercase__ , default=1E-3 , help="Weight decay rate to use for training." , ) parser.add_argument( "--max_length" , type=lowercase__ , default=5_1_2 , help="Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py" , ) parser.add_argument( "--mlm_probability" , type=lowercase__ , default=0.15 , help="Fraction of tokens to mask during training." , ) parser.add_argument("--output_dir" , type=lowercase__ , required=lowercase__ , help="Path to save model checkpoints to." ) parser.add_argument("--hub_model_id" , type=lowercase__ , help="Model ID to upload to on the Hugging Face Hub." ) UpperCAmelCase_ =parser.parse_args() return args def a__ ( lowercase__ ): '''simple docstring''' try: if args.tpu_name: UpperCAmelCase_ =tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: UpperCAmelCase_ =tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( "Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or " "--gcp_project. When running on a TPU VM, use --tpu_name local." ) tf.config.experimental_connect_to_cluster(lowercase__ ) tf.tpu.experimental.initialize_tpu_system(lowercase__ ) return tpu def a__ ( lowercase__ ): '''simple docstring''' UpperCAmelCase_ =0 for file in file_list: UpperCAmelCase_ =file.split("/" )[-1] UpperCAmelCase_ =re.search(R"-\d+-(\d+)\.tfrecord" , lowercase__ ).group(1 ) UpperCAmelCase_ =int(lowercase__ ) num_samples += sample_count return num_samples def a__ ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None ): '''simple docstring''' UpperCAmelCase_ =count_samples(lowercase__ ) UpperCAmelCase_ =tf.data.Dataset.from_tensor_slices(lowercase__ ) if shuffle: UpperCAmelCase_ =dataset.shuffle(len(lowercase__ ) ) UpperCAmelCase_ =tf.data.TFRecordDataset(lowercase__ , num_parallel_reads=lowercase__ ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here UpperCAmelCase_ =dataset.apply(tf.data.experimental.assert_cardinality(lowercase__ ) ) UpperCAmelCase_ =dataset.map(lowercase__ , num_parallel_calls=lowercase__ ) if shuffle: assert shuffle_buffer_size is not None UpperCAmelCase_ =dataset.shuffle(args.shuffle_buffer_size ) UpperCAmelCase_ =dataset.batch(lowercase__ , drop_remainder=lowercase__ ) UpperCAmelCase_ =dataset.map(lowercase__ , num_parallel_calls=lowercase__ ) UpperCAmelCase_ =dataset.prefetch(lowercase__ ) return dataset def a__ ( lowercase__ ): '''simple docstring''' if not args.no_tpu: UpperCAmelCase_ =initialize_tpu(lowercase__ ) UpperCAmelCase_ =tf.distribute.TPUStrategy(lowercase__ ) else: UpperCAmelCase_ =tf.distribute.OneDeviceStrategy(device="/gpu:0" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("mixed_bfloat16" ) UpperCAmelCase_ =AutoTokenizer.from_pretrained(args.tokenizer ) UpperCAmelCase_ =AutoConfig.from_pretrained(args.pretrained_model_config ) UpperCAmelCase_ =tokenizer.vocab_size UpperCAmelCase_ =tf.io.gfile.glob(os.path.join(args.train_dataset , "*.tfrecord" ) ) if not training_records: raise ValueError(F'No .tfrecord files found in {args.train_dataset}.' ) UpperCAmelCase_ =tf.io.gfile.glob(os.path.join(args.eval_dataset , "*.tfrecord" ) ) if not eval_records: raise ValueError(F'No .tfrecord files found in {args.eval_dataset}.' ) UpperCAmelCase_ =count_samples(lowercase__ ) UpperCAmelCase_ =num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) UpperCAmelCase_ =steps_per_epoch * args.num_epochs with strategy.scope(): UpperCAmelCase_ =TFAutoModelForMaskedLM.from_config(lowercase__ ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built UpperCAmelCase_ , UpperCAmelCase_ =create_optimizer( num_train_steps=lowercase__ , num_warmup_steps=total_train_steps // 2_0 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=lowercase__ , metrics=["accuracy"] ) def decode_fn(lowercase__ ): UpperCAmelCase_ ={ "input_ids": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), "attention_mask": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(lowercase__ , lowercase__ ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. UpperCAmelCase_ =DataCollatorForLanguageModeling( tokenizer=lowercase__ , mlm_probability=args.mlm_probability , mlm=lowercase__ , return_tensors="tf" ) def mask_with_collator(lowercase__ ): # TF really needs an isin() function UpperCAmelCase_ =( ~tf.cast(batch["attention_mask"] , tf.bool ) | (batch["input_ids"] == tokenizer.cls_token_id) | (batch["input_ids"] == tokenizer.sep_token_id) ) UpperCAmelCase_ , UpperCAmelCase_ =data_collator.tf_mask_tokens( batch["input_ids"] , vocab_size=len(lowercase__ ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=lowercase__ , ) return batch UpperCAmelCase_ =args.per_replica_batch_size * strategy.num_replicas_in_sync UpperCAmelCase_ =prepare_dataset( lowercase__ , decode_fn=lowercase__ , mask_fn=lowercase__ , batch_size=lowercase__ , shuffle=lowercase__ , shuffle_buffer_size=args.shuffle_buffer_size , ) UpperCAmelCase_ =prepare_dataset( lowercase__ , decode_fn=lowercase__ , mask_fn=lowercase__ , batch_size=lowercase__ , shuffle=lowercase__ , ) UpperCAmelCase_ =[] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=lowercase__ ) ) model.fit( lowercase__ , validation_data=lowercase__ , epochs=args.num_epochs , callbacks=lowercase__ , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": __lowercase : Union[str, Any] =parse_args() main(args)
54
1
'''simple docstring''' class lowercase : '''simple docstring''' def __init__( self : Union[str, Any] ) -> None: '''simple docstring''' lowerCamelCase__ = {} # Mapping from char to TrieNode lowerCamelCase__ = False def a__ ( self : List[Any] , __lowerCamelCase : list[str] ) -> None: '''simple docstring''' for word in words: self.insert(__lowerCamelCase ) def a__ ( self : int , __lowerCamelCase : str ) -> None: '''simple docstring''' lowerCamelCase__ = self for char in word: if char not in curr.nodes: lowerCamelCase__ = TrieNode() lowerCamelCase__ = curr.nodes[char] lowerCamelCase__ = True def a__ ( self : Optional[Any] , __lowerCamelCase : str ) -> bool: '''simple docstring''' lowerCamelCase__ = self for char in word: if char not in curr.nodes: return False lowerCamelCase__ = curr.nodes[char] return curr.is_leaf def a__ ( self : Optional[Any] , __lowerCamelCase : str ) -> None: '''simple docstring''' def _delete(__lowerCamelCase : TrieNode , __lowerCamelCase : str , __lowerCamelCase : int ) -> bool: if index == len(__lowerCamelCase ): # If word does not exist if not curr.is_leaf: return False lowerCamelCase__ = False return len(curr.nodes ) == 0 lowerCamelCase__ = word[index] lowerCamelCase__ = curr.nodes.get(__lowerCamelCase ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted lowerCamelCase__ = _delete(__lowerCamelCase , __lowerCamelCase , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , __lowerCamelCase , 0 ) def lowerCamelCase_ ( lowercase__ , lowercase__) -> Union[str, Any]: if node.is_leaf: print(lowercase__ , end=" ") for key, value in node.nodes.items(): print_words(lowercase__ , word + key) def lowerCamelCase_ ( ) -> Optional[Any]: lowerCamelCase__ = "banana bananas bandana band apple all beast".split() lowerCamelCase__ = TrieNode() root.insert_many(lowercase__) # print_words(root, "") assert all(root.find(lowercase__) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def lowerCamelCase_ ( lowercase__ , lowercase__) -> Tuple: print(str(lowercase__) , "works!" if passes else "doesn't work :(") def lowerCamelCase_ ( ) -> List[Any]: assert test_trie() def lowerCamelCase_ ( ) -> List[str]: print_results("Testing trie functionality" , test_trie()) if __name__ == "__main__": main()
712
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def lowerCamelCase_ ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__): lowerCamelCase__ = cva.getAffineTransform(lowercase__ , lowercase__) return cva.warpAffine(lowercase__ , lowercase__ , (rows, cols)) if __name__ == "__main__": # read original image __A : Any = cva.imread( str(Path(__file__).resolve().parent.parent / """image_data""" / """lena.jpg""") ) # turn image in gray scale value __A : int = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape __A , __A : Dict = gray_img.shape # set different points to rotate image __A : int = np.array([[50, 50], [2_00, 50], [50, 2_00]], np.floataa) __A : Any = np.array([[10, 1_00], [2_00, 50], [1_00, 2_50]], np.floataa) __A : str = np.array([[50, 50], [1_50, 50], [1_20, 2_00]], np.floataa) __A : Optional[int] = np.array([[10, 1_00], [80, 50], [1_80, 2_50]], np.floataa) # add all rotated images in a list __A : List[Any] = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations __A : int = plt.figure(1) __A : int = ["""Original""", """Rotation 1""", """Rotation 2""", """Rotation 3"""] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, """gray""") plt.title(titles[i]) plt.axis("""off""") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
187
0
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCamelCase : def __init__( self : Optional[int] , _lowerCAmelCase : List[str] , _lowerCAmelCase : int=13 , _lowerCAmelCase : Any=32 , _lowerCAmelCase : str=3 , _lowerCAmelCase : int=4 , _lowerCAmelCase : Optional[int]=[10, 20, 30, 40] , _lowerCAmelCase : Optional[Any]=[2, 2, 3, 2] , _lowerCAmelCase : List[str]=True , _lowerCAmelCase : int=True , _lowerCAmelCase : List[str]=37 , _lowerCAmelCase : List[str]="gelu" , _lowerCAmelCase : List[Any]=10 , _lowerCAmelCase : int=0.02 , _lowerCAmelCase : str=["stage2", "stage3", "stage4"] , _lowerCAmelCase : Dict=[2, 3, 4] , _lowerCAmelCase : Tuple=None , ) -> Any: """simple docstring""" __lowercase = parent __lowercase = batch_size __lowercase = image_size __lowercase = num_channels __lowercase = num_stages __lowercase = hidden_sizes __lowercase = depths __lowercase = is_training __lowercase = use_labels __lowercase = intermediate_size __lowercase = hidden_act __lowercase = num_labels __lowercase = initializer_range __lowercase = out_features __lowercase = out_indices __lowercase = scope def _a ( self : Dict ) -> Optional[int]: """simple docstring""" __lowercase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size] , self.num_labels ) __lowercase = self.get_config() return config, pixel_values, labels def _a ( self : List[str] ) -> Any: """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def _a ( self : Optional[Any] , _lowerCAmelCase : List[str] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Tuple ) -> Dict: """simple docstring""" __lowercase = ConvNextModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowercase = model(_lowerCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _a ( self : Optional[int] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Optional[Any] ) -> Dict: """simple docstring""" __lowercase = ConvNextForImageClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowercase = model(_lowerCAmelCase , labels=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : int , _lowerCAmelCase : Optional[Any] ) -> Optional[Any]: """simple docstring""" __lowercase = ConvNextBackbone(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowercase = model(_lowerCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None __lowercase = None __lowercase = ConvNextBackbone(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() __lowercase = model(_lowerCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _a ( self : List[str] ) -> List[str]: """simple docstring""" __lowercase = self.prepare_config_and_inputs() __lowercase , __lowercase , __lowercase = config_and_inputs __lowercase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): __snake_case :Optional[Any] = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) __snake_case :List[str] = ( {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification} if is_torch_available() else {} ) __snake_case :str = True __snake_case :Any = False __snake_case :Any = False __snake_case :Any = False __snake_case :int = False def _a ( self : Optional[int] ) -> Dict: """simple docstring""" __lowercase = ConvNextModelTester(self ) __lowercase = ConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=37 ) def _a ( self : Optional[Any] ) -> int: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self : Any ) -> Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNext does not use inputs_embeds""" ) def _a ( self : List[Any] ) -> Any: """simple docstring""" pass @unittest.skip(reason="""ConvNext does not support input and output embeddings""" ) def _a ( self : Dict ) -> int: """simple docstring""" pass @unittest.skip(reason="""ConvNext does not use feedforward chunking""" ) def _a ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" pass def _a ( self : Tuple ) -> Tuple: """simple docstring""" __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase = model_class(_lowerCAmelCase ) __lowercase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowercase = [*signature.parameters.keys()] __lowercase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def _a ( self : Any ) -> List[str]: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) def _a ( self : Any ) -> Optional[int]: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCAmelCase ) def _a ( self : Union[str, Any] ) -> Tuple: """simple docstring""" def check_hidden_states_output(_lowerCAmelCase : Tuple , _lowerCAmelCase : int , _lowerCAmelCase : Optional[int] ): __lowercase = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): __lowercase = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) __lowercase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __lowercase = self.model_tester.num_stages self.assertEqual(len(_lowerCAmelCase ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase = True check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowercase = True check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def _a ( self : Optional[int] ) -> List[str]: """simple docstring""" __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase ) @slow def _a ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase = ConvNextModel.from_pretrained(_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) def snake_case ( ): '''simple docstring''' __lowercase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def _a ( self : Tuple ) -> Any: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224""" ) if is_vision_available() else None @slow def _a ( self : str ) -> Optional[Any]: """simple docstring""" __lowercase = ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224""" ).to(_lowerCAmelCase ) __lowercase = self.default_image_processor __lowercase = prepare_img() __lowercase = image_processor(images=_lowerCAmelCase , return_tensors="""pt""" ).to(_lowerCAmelCase ) # forward pass with torch.no_grad(): __lowercase = model(**_lowerCAmelCase ) # verify the logits __lowercase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) __lowercase = torch.tensor([-0.0_260, -0.4_739, 0.1_911] ).to(_lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1e-4 ) ) @require_torch class __UpperCamelCase ( unittest.TestCase , _lowerCAmelCase ): __snake_case :Union[str, Any] = (ConvNextBackbone,) if is_torch_available() else () __snake_case :str = ConvNextConfig __snake_case :Optional[Any] = False def _a ( self : Optional[int] ) -> List[Any]: """simple docstring""" __lowercase = ConvNextModelTester(self )
80
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch a : List[Any] = random.Random() def lowercase_ ( _UpperCamelCase , _UpperCamelCase=1.0 , _UpperCamelCase=None , _UpperCamelCase=None ): '''simple docstring''' if rng is None: __lowercase = global_rng __lowercase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , snake_case_ , snake_case_=7 , snake_case_=4_0_0 , snake_case_=2_0_0_0 , snake_case_=1 , snake_case_=0.0 , snake_case_=1_6_0_0_0 , snake_case_=True , snake_case_=8_0 , snake_case_=1_6 , snake_case_=6_4 , snake_case_="hann_window" , snake_case_=8_0 , snake_case_=7_6_0_0 , snake_case_=1e-1_0 , snake_case_=True , ) -> Tuple: '''simple docstring''' __lowercase = parent __lowercase = batch_size __lowercase = min_seq_length __lowercase = max_seq_length __lowercase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __lowercase = feature_size __lowercase = padding_value __lowercase = sampling_rate __lowercase = do_normalize __lowercase = num_mel_bins __lowercase = hop_length __lowercase = win_length __lowercase = win_function __lowercase = fmin __lowercase = fmax __lowercase = mel_floor __lowercase = return_attention_mask def A ( self ) -> str: '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def A ( self , snake_case_=False , snake_case_=False ) -> Tuple: '''simple docstring''' def _flatten(snake_case_ ): return list(itertools.chain(*snake_case_ ) ) if equal_length: __lowercase = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __lowercase = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __lowercase = [np.asarray(snake_case_ ) for x in speech_inputs] return speech_inputs def A ( self , snake_case_=False , snake_case_=False ) -> Any: '''simple docstring''' if equal_length: __lowercase = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __lowercase = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __lowercase = [np.asarray(snake_case_ ) for x in speech_inputs] return speech_inputs @require_torch class lowerCamelCase_ ( lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase = SpeechTaFeatureExtractor def A ( self ) -> Dict: '''simple docstring''' __lowercase = SpeechTaFeatureExtractionTester(self ) def A ( self , snake_case_ ) -> str: '''simple docstring''' self.assertTrue(np.all(np.mean(snake_case_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(snake_case_ , axis=0 ) - 1 ) < 1e-3 ) ) def A ( self ) -> int: '''simple docstring''' __lowercase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __lowercase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __lowercase = [np.asarray(snake_case_ ) for speech_input in speech_inputs] # Test not batched input __lowercase = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values __lowercase = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1e-3 ) ) # Test batched __lowercase = feat_extract(snake_case_ , return_tensors='''np''' ).input_values __lowercase = feat_extract(snake_case_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(snake_case_ , snake_case_ ): self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1e-3 ) ) def A ( self ) -> Any: '''simple docstring''' __lowercase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowercase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __lowercase = ['''longest''', '''max_length''', '''do_not_pad'''] __lowercase = [None, 1_6_0_0, None] for max_length, padding in zip(snake_case_ , snake_case_ ): __lowercase = feat_extract(snake_case_ , padding=snake_case_ , max_length=snake_case_ , return_tensors='''np''' ) __lowercase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def A ( self ) -> List[str]: '''simple docstring''' __lowercase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowercase = range(8_0_0 , 1_4_0_0 , 2_0_0 ) __lowercase = [floats_list((1, x) )[0] for x in lengths] __lowercase = ['''longest''', '''max_length''', '''do_not_pad'''] __lowercase = [None, 1_6_0_0, None] for max_length, padding in zip(snake_case_ , snake_case_ ): __lowercase = feat_extract(snake_case_ , max_length=snake_case_ , padding=snake_case_ ) __lowercase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def A ( self ) -> List[Any]: '''simple docstring''' __lowercase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowercase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __lowercase = feat_extract( snake_case_ , truncation=snake_case_ , max_length=1_0_0_0 , padding='''max_length''' , return_tensors='''np''' ) __lowercase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def A ( self ) -> List[str]: '''simple docstring''' __lowercase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowercase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __lowercase = feat_extract( snake_case_ , truncation=snake_case_ , max_length=1_0_0_0 , padding='''longest''' , return_tensors='''np''' ) __lowercase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_0_0_0) ) __lowercase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __lowercase = feat_extract( snake_case_ , truncation=snake_case_ , max_length=2_0_0_0 , padding='''longest''' , return_tensors='''np''' ) __lowercase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_2_0_0) ) def A ( self ) -> str: '''simple docstring''' __lowercase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __lowercase = np.random.rand(1_0_0 ).astype(np.floataa ) __lowercase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __lowercase = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __lowercase = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def A ( self ) -> List[str]: '''simple docstring''' __lowercase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __lowercase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __lowercase = [np.asarray(snake_case_ ) for speech_input in speech_inputs] # Test feature size __lowercase = feature_extractor(audio_target=snake_case_ , padding=snake_case_ , return_tensors='''np''' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input __lowercase = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_values __lowercase = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1e-3 ) ) # Test batched __lowercase = feature_extractor(snake_case_ , return_tensors='''np''' ).input_values __lowercase = feature_extractor(snake_case_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(snake_case_ , snake_case_ ): self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __lowercase = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] __lowercase = np.asarray(snake_case_ ) __lowercase = feature_extractor(snake_case_ , return_tensors='''np''' ).input_values __lowercase = feature_extractor(snake_case_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(snake_case_ , snake_case_ ): self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1e-3 ) ) def A ( self ) -> Tuple: '''simple docstring''' __lowercase = self.feat_extract_tester.prepare_inputs_for_target() __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case_ ) == len(snake_case_ ) for x, y in zip(snake_case_ , processed_features[input_name] ) ) ) __lowercase = self.feat_extract_tester.prepare_inputs_for_target(equal_length=snake_case_ ) __lowercase = BatchFeature({input_name: speech_inputs} , tensor_type='''np''' ) __lowercase = processed_features[input_name] if len(batch_features_input.shape ) < 3: __lowercase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def A ( self ) -> List[str]: '''simple docstring''' __lowercase = self.feat_extract_tester.prepare_inputs_for_target(equal_length=snake_case_ ) __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} , tensor_type='''pt''' ) __lowercase = processed_features[input_name] if len(batch_features_input.shape ) < 3: __lowercase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def A ( self ) -> Tuple: '''simple docstring''' __lowercase = self.feature_extraction_class(**self.feat_extract_dict ) __lowercase = self.feat_extract_tester.prepare_inputs_for_target() __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) __lowercase = feat_extract.num_mel_bins # hack! __lowercase = feat_extract.pad(snake_case_ , padding='''longest''' , return_tensors='''np''' )[input_name] __lowercase = feat_extract.pad(snake_case_ , padding='''longest''' , return_tensors='''pt''' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def A ( self ) -> Dict: '''simple docstring''' __lowercase = self.feat_extract_dict __lowercase = True __lowercase = self.feature_extraction_class(**snake_case_ ) __lowercase = self.feat_extract_tester.prepare_inputs_for_target() __lowercase = [len(snake_case_ ) for x in speech_inputs] __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) __lowercase = feat_extract.num_mel_bins # hack! __lowercase = feat_extract.pad(snake_case_ , padding='''longest''' , return_tensors='''np''' ) self.assertIn('''attention_mask''' , snake_case_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , snake_case_ ) def A ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self.feat_extract_dict __lowercase = True __lowercase = self.feature_extraction_class(**snake_case_ ) __lowercase = self.feat_extract_tester.prepare_inputs_for_target() __lowercase = [len(snake_case_ ) for x in speech_inputs] __lowercase = feat_extract.model_input_names[0] __lowercase = BatchFeature({input_name: speech_inputs} ) __lowercase = min(snake_case_ ) __lowercase = feat_extract.num_mel_bins # hack! __lowercase = feat_extract.pad( snake_case_ , padding='''max_length''' , max_length=snake_case_ , truncation=snake_case_ , return_tensors='''np''' ) self.assertIn('''attention_mask''' , snake_case_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def A ( self , snake_case_ ) -> str: '''simple docstring''' from datasets import load_dataset __lowercase = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech __lowercase = ds.sort('''id''' ).select(range(snake_case_ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def A ( self ) -> Optional[int]: '''simple docstring''' __lowercase = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on __lowercase = self._load_datasamples(1 ) __lowercase = SpeechTaFeatureExtractor() __lowercase = feature_extractor(snake_case_ , return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape , (1, 9_3_6_8_0) ) self.assertTrue(torch.allclose(input_values[0, :3_0] , snake_case_ , atol=1e-6 ) ) def A ( self ) -> str: '''simple docstring''' __lowercase = torch.tensor( [-2.6_8_7_0, -3.0_1_0_4, -3.1_3_5_6, -3.5_3_5_2, -3.0_0_4_4, -3.0_3_5_3, -3.4_7_1_9, -3.6_7_7_7, -3.1_5_2_0, -2.9_4_3_5, -2.6_5_5_3, -2.8_7_9_5, -2.9_9_4_4, -2.5_9_2_1, -3.0_2_7_9, -3.0_3_8_6, -3.0_8_6_4, -3.1_2_9_1, -3.2_3_5_3, -2.7_4_4_4, -2.6_8_3_1, -2.7_2_8_7, -3.1_7_6_1, -3.1_5_7_1, -3.2_7_2_6, -3.0_5_8_2, -3.1_0_0_7, -3.4_5_3_3, -3.4_6_9_5, -3.0_9_9_8] ) # fmt: on __lowercase = self._load_datasamples(1 ) __lowercase = SpeechTaFeatureExtractor() __lowercase = feature_extractor(audio_target=snake_case_ , return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape , (1, 3_6_6, 8_0) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , snake_case_ , atol=1e-4 ) )
639
0
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _snake_case ( lowercase , lowercase ) -> Union[str, Any]: assert isinstance(lowercase , lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def _snake_case ( lowercase , lowercase , lowercase ) -> Dict: __a : Optional[int] = tmp_path / """cache""" __a : Optional[int] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a : List[str] = JsonDatasetReader(lowercase , cache_dir=lowercase , keep_in_memory=lowercase ).read() _check_json_dataset(lowercase , lowercase ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def _snake_case ( lowercase , lowercase , lowercase ) -> Any: __a : int = tmp_path / """cache""" __a : Dict = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a : Union[str, Any] = features.copy() if features else default_expected_features __a : Optional[Any] = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) __a : List[Any] = JsonDatasetReader(lowercase , features=lowercase , cache_dir=lowercase ).read() _check_json_dataset(lowercase , lowercase ) @pytest.mark.parametrize( """features""" , [ None, {"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""}, ] , ) def _snake_case ( lowercase , lowercase , lowercase ) -> Any: __a : Tuple = tmp_path / """cache""" __a : Union[str, Any] = {"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""} __a : Tuple = features.copy() if features else default_expected_features __a : List[Any] = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) __a : str = JsonDatasetReader(lowercase , features=lowercase , cache_dir=lowercase ).read() assert isinstance(lowercase , lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def _snake_case ( lowercase , lowercase ) -> str: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} __a : int = {"""col_2""": """int64""", """col_3""": """float64""", """col_1""": """string"""} __a : List[str] = features.copy() __a : str = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) __a : Tuple = tmp_path / """cache""" __a : Any = JsonDatasetReader(lowercase , features=lowercase , cache_dir=lowercase ).read() assert isinstance(lowercase , lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def _snake_case ( lowercase , lowercase , lowercase ) -> str: __a : List[Any] = tmp_path / """cache""" __a : List[str] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a : List[str] = JsonDatasetReader(lowercase , cache_dir=lowercase , split=lowercase ).read() _check_json_dataset(lowercase , lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def _snake_case ( lowercase , lowercase , lowercase ) -> List[Any]: if issubclass(lowercase , lowercase ): __a : str = jsonl_path elif issubclass(lowercase , lowercase ): __a : Tuple = [jsonl_path] __a : Any = tmp_path / """cache""" __a : Tuple = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a : Optional[int] = JsonDatasetReader(lowercase , cache_dir=lowercase ).read() _check_json_dataset(lowercase , lowercase ) def _snake_case ( lowercase , lowercase , lowercase=("train",) ) -> Optional[int]: assert isinstance(lowercase , lowercase ) for split in splits: __a : Optional[int] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def _snake_case ( lowercase , lowercase , lowercase ) -> List[Any]: __a : Optional[int] = tmp_path / """cache""" __a : List[str] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a : int = JsonDatasetReader({"""train""": jsonl_path} , cache_dir=lowercase , keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase , lowercase ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def _snake_case ( lowercase , lowercase , lowercase ) -> Any: __a : str = tmp_path / """cache""" __a : int = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a : str = features.copy() if features else default_expected_features __a : List[str] = ( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) __a : List[str] = JsonDatasetReader({"""train""": jsonl_path} , features=lowercase , cache_dir=lowercase ).read() _check_json_datasetdict(lowercase , lowercase ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def _snake_case ( lowercase , lowercase , lowercase ) -> Dict: if split: __a : str = {split: jsonl_path} else: __a : Dict = """train""" __a : Optional[int] = {"""train""": jsonl_path, """test""": jsonl_path} __a : int = tmp_path / """cache""" __a : Dict = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} __a : Optional[int] = JsonDatasetReader(lowercase , cache_dir=lowercase ).read() _check_json_datasetdict(lowercase , lowercase , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def _snake_case ( lowercase ) -> Any: return json.load(lowercase ) def _snake_case ( lowercase ) -> Union[str, Any]: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE__ : @pytest.mark.parametrize("""lines, load_json_function""" , [(True, load_json_lines), (False, load_json)] ) def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(__UpperCamelCase , __UpperCamelCase , lines=__UpperCamelCase ).write() buffer.seek(0 ) __a : List[str] = load_json_function(__UpperCamelCase ) assert isinstance(__UpperCamelCase , __UpperCamelCase ) assert isinstance(exported_content[0] , __UpperCamelCase ) assert len(__UpperCamelCase ) == 10 @pytest.mark.parametrize( """orient, container, keys, len_at""" , [ ("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None), ("""split""", dict, {"""columns""", """data"""}, """data"""), ("""index""", dict, set("""0123456789""" ), None), ("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""), ("""values""", list, None, None), ("""table""", dict, {"""schema""", """data"""}, """data"""), ] , ) def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(__UpperCamelCase , __UpperCamelCase , lines=__UpperCamelCase , orient=__UpperCamelCase ).write() buffer.seek(0 ) __a : List[str] = load_json(__UpperCamelCase ) assert isinstance(__UpperCamelCase , __UpperCamelCase ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__UpperCamelCase , """keys""" ) and not hasattr(exported_content[0] , """keys""" ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__UpperCamelCase ) == 10 @pytest.mark.parametrize("""lines, load_json_function""" , [(True, load_json_lines), (False, load_json)] ) def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(__UpperCamelCase , __UpperCamelCase , lines=__UpperCamelCase , num_proc=2 ).write() buffer.seek(0 ) __a : List[str] = load_json_function(__UpperCamelCase ) assert isinstance(__UpperCamelCase , __UpperCamelCase ) assert isinstance(exported_content[0] , __UpperCamelCase ) assert len(__UpperCamelCase ) == 10 @pytest.mark.parametrize( """orient, container, keys, len_at""" , [ ("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None), ("""split""", dict, {"""columns""", """data"""}, """data"""), ("""index""", dict, set("""0123456789""" ), None), ("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""), ("""values""", list, None, None), ("""table""", dict, {"""schema""", """data"""}, """data"""), ] , ) def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(__UpperCamelCase , __UpperCamelCase , lines=__UpperCamelCase , orient=__UpperCamelCase , num_proc=2 ).write() buffer.seek(0 ) __a : Any = load_json(__UpperCamelCase ) assert isinstance(__UpperCamelCase , __UpperCamelCase ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__UpperCamelCase , """keys""" ) and not hasattr(exported_content[0] , """keys""" ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__UpperCamelCase ) == 10 def __lowerCamelCase ( self , __UpperCamelCase ): '''simple docstring''' with pytest.raises(__UpperCamelCase ): with io.BytesIO() as buffer: JsonDatasetWriter(__UpperCamelCase , __UpperCamelCase , num_proc=0 ) @pytest.mark.parametrize("""compression, extension""" , [("""gzip""", """gz"""), ("""bz2""", """bz2"""), ("""xz""", """xz""")] ) def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __a : Tuple = tmp_path_factory.mktemp("""data""" ) / f"""test.json.{extension}""" __a : Optional[Any] = str(shared_datadir / f"""test_file.json.{extension}""" ) JsonDatasetWriter(__UpperCamelCase , __UpperCamelCase , compression=__UpperCamelCase ).write() with fsspec.open(__UpperCamelCase , """rb""" , compression="""infer""" ) as f: __a : Optional[int] = f.read() with fsspec.open(__UpperCamelCase , """rb""" , compression="""infer""" ) as f: __a : Dict = f.read() assert exported_content == original_content
697
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = {'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : List[Any] = [ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
697
1
from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
47
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ = TypeVar('''T''') def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (position - 1) // 2 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 1 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 2 class _UpperCamelCase( Generic[T] ): def __init__( self : List[str] ): '''simple docstring''' __a : list[tuple[T, int]] = [] __a : dict[T, int] = {} __a : int = 0 def __len__( self : Any ): '''simple docstring''' return self.elements def __repr__( self : Any ): '''simple docstring''' return str(self.heap ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return self.elements == 0 def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.heap.append((elem, weight) ) __a : List[Any] = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __a , __a : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __a , __a : Dict = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : List[Any] = self.position_map[elem] __a : str = (elem, weight) if position > 0: __a : Tuple = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : Dict = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : List[Any] = self.position_map[elem] if curr_pos == 0: return None __a : List[str] = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : str = self.heap[curr_pos] __a , __a : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : int = self.position_map[elem] __a , __a : Optional[Any] = self.heap[curr_pos] __a : Tuple = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __a , __a : str = self.heap[child_left_position] __a , __a : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __a , __a : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __a , __a : Union[str, Any] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Optional[Any] = self.heap[nodea_pos][0] __a : str = self.heap[nodea_pos][0] __a , __a : int = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __a : str = nodea_pos __a : Optional[int] = nodea_pos class _UpperCamelCase( Generic[T] ): def __init__( self : List[Any] ): '''simple docstring''' __a : dict[T, dict[T, int]] = {} __a : int = 0 def __repr__( self : Tuple ): '''simple docstring''' return str(self.connections ) def __len__( self : Dict ): '''simple docstring''' return self.nodes def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' if node not in self.connections: __a : Tuple = {} self.nodes += 1 def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = weight __a : Any = weight def UpperCAmelCase__ ( lowerCamelCase_ : GraphUndirectedWeighted[T] , ): __a : dict[T, int] = {node: maxsize for node in graph.connections} __a : dict[T, T | None] = {node: None for node in graph.connections} __a : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCamelCase_ , lowerCamelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization __a : Optional[int] = priority_queue.extract_min() __a : int = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : str = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Optional[int] = node # running prim's algorithm while not priority_queue.is_empty(): __a : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Dict = node return dist, parent
47
1
from jiwer import compute_measures import datasets __SCREAMING_SNAKE_CASE : Union[str, Any] = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' __SCREAMING_SNAKE_CASE : Optional[Any] = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' __SCREAMING_SNAKE_CASE : Any = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase_ ( datasets.Metric ): def UpperCamelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCamelCase ( self , lowercase_=None , lowercase_=None , lowercase_=False ): if concatenate_texts: return compute_measures(lowercase_ , lowercase_ )["wer"] else: _snake_case : List[str] = 0 _snake_case : List[str] = 0 for prediction, reference in zip(lowercase_ , lowercase_ ): _snake_case : Union[str, Any] = compute_measures(lowercase_ , lowercase_ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
580
import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class lowercase_ : def __init__( self , lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_="resnet50" , lowercase_=3 , lowercase_=32 , lowercase_=3 , lowercase_=True , lowercase_=True , ): _snake_case : Any = parent _snake_case : int = out_indices if out_indices is not None else [4] _snake_case : Any = stage_names _snake_case : Optional[Any] = out_features _snake_case : Dict = backbone _snake_case : List[str] = batch_size _snake_case : Optional[int] = image_size _snake_case : str = num_channels _snake_case : Optional[Any] = use_pretrained_backbone _snake_case : str = is_training def UpperCamelCase ( self ): _snake_case : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _snake_case : List[str] = self.get_config() return config, pixel_values def UpperCamelCase ( self ): return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def UpperCamelCase ( self , lowercase_ , lowercase_ ): _snake_case : Dict = TimmBackbone(config=lowercase_ ) model.to(lowercase_ ) model.eval() with torch.no_grad(): _snake_case : List[Any] = model(lowercase_ ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 14, 14) , ) def UpperCamelCase ( self ): _snake_case : Dict = self.prepare_config_and_inputs() _snake_case ,_snake_case : List[Any] = config_and_inputs _snake_case : int = {"pixel_values": pixel_values} return config, inputs_dict @require_torch @require_timm class lowercase_ ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): _lowerCamelCase = (TimmBackbone,) if is_torch_available() else () _lowerCamelCase = {'feature-extraction': TimmBackbone} if is_torch_available() else {} _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False def UpperCamelCase ( self ): _snake_case : Dict = TimmBackboneModelTester(self ) _snake_case : Optional[int] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ ) def UpperCamelCase ( self ): 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 UpperCamelCase ( self ): _snake_case : Dict = "resnet18" _snake_case : Tuple = "microsoft/resnet-18" _snake_case : Tuple = AutoBackbone.from_pretrained(lowercase_ , use_timm_backbone=lowercase_ ) _snake_case : List[str] = AutoBackbone.from_pretrained(lowercase_ ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) _snake_case : List[str] = AutoBackbone.from_pretrained(lowercase_ , use_timm_backbone=lowercase_ , out_indices=[1, 2, 3] ) _snake_case : Optional[int] = AutoBackbone.from_pretrained(lowercase_ , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip("TimmBackbone doesn't support feed forward chunking" ) def UpperCamelCase ( self ): pass @unittest.skip("TimmBackbone doesn't have num_hidden_layers attribute" ) def UpperCamelCase ( self ): pass @unittest.skip("TimmBackbone initialization is managed on the timm side" ) def UpperCamelCase ( self ): pass @unittest.skip("TimmBackbone models doesn't have inputs_embeds" ) def UpperCamelCase ( self ): pass @unittest.skip("TimmBackbone models doesn't have inputs_embeds" ) def UpperCamelCase ( self ): pass @unittest.skip("TimmBackbone model cannot be created without specifying a backbone checkpoint" ) def UpperCamelCase ( self ): pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def UpperCamelCase ( self ): pass @unittest.skip("model weights aren't tied in TimmBackbone." ) def UpperCamelCase ( self ): pass @unittest.skip("model weights aren't tied in TimmBackbone." ) def UpperCamelCase ( self ): pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def UpperCamelCase ( self ): pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def UpperCamelCase ( self ): pass @unittest.skip("TimmBackbone doesn't have hidden size info in its configuration." ) def UpperCamelCase ( self ): pass @unittest.skip("TimmBackbone doesn't support output_attentions." ) def UpperCamelCase ( self ): pass @unittest.skip("Safetensors is not supported by timm." ) def UpperCamelCase ( self ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def UpperCamelCase ( self ): pass def UpperCamelCase ( self ): _snake_case ,_snake_case : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : Tuple = model_class(lowercase_ ) _snake_case : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _snake_case : Union[str, Any] = [*signature.parameters.keys()] _snake_case : Optional[int] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowercase_ ) def UpperCamelCase ( self ): _snake_case ,_snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common() _snake_case : Tuple = True _snake_case : Optional[Any] = self.has_attentions # no need to test all models as different heads yield the same functionality _snake_case : Dict = self.all_model_classes[0] _snake_case : List[Any] = model_class(lowercase_ ) model.to(lowercase_ ) _snake_case : List[str] = self._prepare_for_class(lowercase_ , lowercase_ ) _snake_case : List[Any] = model(**lowercase_ ) _snake_case : Optional[int] = outputs[0][-1] # Encoder-/Decoder-only models _snake_case : List[Any] = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: _snake_case : Union[str, Any] = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=lowercase_ ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def UpperCamelCase ( self ): _snake_case ,_snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : int = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() _snake_case : Any = model(**lowercase_ ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None _snake_case : Union[str, Any] = copy.deepcopy(lowercase_ ) _snake_case : int = None _snake_case : Optional[int] = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() _snake_case : int = model(**lowercase_ ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights _snake_case : Dict = copy.deepcopy(lowercase_ ) _snake_case : Dict = False _snake_case : List[Any] = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() _snake_case : Any = model(**lowercase_ )
580
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ :List[str] = logging.get_logger(__name__) UpperCamelCase__ :str = { """transfo-xl-wt103""": """https://huggingface.co/transfo-xl-wt103/resolve/main/config.json""", } class A( lowerCamelCase__ ): """simple docstring""" A = "transfo-xl" A = ["mems"] A = { "n_token": "vocab_size", "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , SCREAMING_SNAKE_CASE__=26_77_35 , SCREAMING_SNAKE_CASE__=[2_00_00, 4_00_00, 20_00_00] , SCREAMING_SNAKE_CASE__=10_24 , SCREAMING_SNAKE_CASE__=10_24 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=64 , SCREAMING_SNAKE_CASE__=40_96 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=18 , SCREAMING_SNAKE_CASE__=16_00 , SCREAMING_SNAKE_CASE__=10_00 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=-1 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__="normal" , SCREAMING_SNAKE_CASE__=0.0_1 , SCREAMING_SNAKE_CASE__=0.0_1 , SCREAMING_SNAKE_CASE__=0.0_2 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=0 , **SCREAMING_SNAKE_CASE__ , ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase :str = vocab_size _UpperCamelCase :Optional[int] = [] self.cutoffs.extend(SCREAMING_SNAKE_CASE__ ) if proj_share_all_but_first: _UpperCamelCase :Tuple = [False] + [True] * len(self.cutoffs ) else: _UpperCamelCase :Optional[Any] = [False] + [False] * len(self.cutoffs ) _UpperCamelCase :Tuple = d_model _UpperCamelCase :int = d_embed _UpperCamelCase :List[str] = d_head _UpperCamelCase :Dict = d_inner _UpperCamelCase :List[str] = div_val _UpperCamelCase :Dict = pre_lnorm _UpperCamelCase :Tuple = n_layer _UpperCamelCase :List[str] = n_head _UpperCamelCase :Any = mem_len _UpperCamelCase :Optional[int] = same_length _UpperCamelCase :Optional[Any] = attn_type _UpperCamelCase :List[Any] = clamp_len _UpperCamelCase :Dict = sample_softmax _UpperCamelCase :Any = adaptive _UpperCamelCase :Tuple = dropout _UpperCamelCase :Optional[int] = dropatt _UpperCamelCase :Union[str, Any] = untie_r _UpperCamelCase :int = init _UpperCamelCase :Dict = init_range _UpperCamelCase :Dict = proj_init_std _UpperCamelCase :List[str] = init_std _UpperCamelCase :Dict = layer_norm_epsilon super().__init__(eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def _UpperCamelCase( self ) -> int: """simple docstring""" logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit." ) return -1 @max_position_embeddings.setter def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" raise NotImplementedError( f"The model {self.model_type} is one of the few models that has no sequence length limit." )
355
"""simple docstring""" import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) UpperCamelCase__ :str = logging.getLogger() def A_ ( snake_case__ , snake_case__ ) -> Optional[Any]: _UpperCamelCase :Optional[int] = '''\n'''.join(snake_case__ ) Path(snake_case__ ).open('''w''' ).writelines(snake_case__ ) UpperCamelCase__ :Dict = """patrickvonplaten/t5-tiny-random""" UpperCamelCase__ :List[Any] = """sshleifer/bart-tiny-random""" UpperCamelCase__ :str = """sshleifer/tiny-mbart""" UpperCamelCase__ :Any = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class A( lowerCamelCase__ ): """simple docstring""" def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" _UpperCamelCase :List[Any] = Path(self.get_auto_remove_tmp_dir() ) / '''utest_input.source''' _UpperCamelCase :Union[str, Any] = input_file_name.parent / '''utest_output.txt''' assert not output_file_name.exists() _UpperCamelCase :int = [''' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County.'''] _dump_articles(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _UpperCamelCase :str = str(Path(self.get_auto_remove_tmp_dir() ) / '''scores.json''' ) _UpperCamelCase :Any = '''translation_en_to_de''' if model == T5_TINY else '''summarization''' _UpperCamelCase :Union[str, Any] = f"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): run_generate() assert Path(SCREAMING_SNAKE_CASE__ ).exists() # os.remove(Path(output_file_name)) def _UpperCamelCase( self ) -> Optional[int]: """simple docstring""" self.run_eval_tester(SCREAMING_SNAKE_CASE__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> List[str]: """simple docstring""" self.run_eval_tester(SCREAMING_SNAKE_CASE__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase :Dict = Path(self.get_auto_remove_tmp_dir() ) / '''utest_input.source''' _UpperCamelCase :Any = input_file_name.parent / '''utest_output.txt''' assert not output_file_name.exists() _UpperCamelCase :Union[str, Any] = { '''en''': ['''Machine learning is great, isn\'t it?''', '''I like to eat bananas''', '''Tomorrow is another great day!'''], '''de''': [ '''Maschinelles Lernen ist großartig, oder?''', '''Ich esse gerne Bananen''', '''Morgen ist wieder ein toller Tag!''', ], } _UpperCamelCase :str = Path(self.get_auto_remove_tmp_dir() ) _UpperCamelCase :Optional[int] = str(tmp_dir / '''scores.json''' ) _UpperCamelCase :int = str(tmp_dir / '''val.target''' ) _dump_articles(SCREAMING_SNAKE_CASE__ , text['''en'''] ) _dump_articles(SCREAMING_SNAKE_CASE__ , text['''de'''] ) _UpperCamelCase :List[str] = '''translation_en_to_de''' if model == T5_TINY else '''summarization''' _UpperCamelCase :str = f"\n run_eval_search.py\n {model}\n {str(SCREAMING_SNAKE_CASE__ )}\n {str(SCREAMING_SNAKE_CASE__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(['''--search''', '''num_beams=1:2 length_penalty=0.9:1.0'''] ) with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): with CaptureStdout() as cs: run_search() _UpperCamelCase :Union[str, Any] = [''' num_beams | length_penalty''', model, '''Best score args'''] _UpperCamelCase :List[Any] = ['''Info'''] if "translation" in task: expected_strings.append('''bleu''' ) else: expected_strings.extend(SCREAMING_SNAKE_CASE__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(SCREAMING_SNAKE_CASE__ ).exists() os.remove(Path(SCREAMING_SNAKE_CASE__ ) )
355
1
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError("At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training") # TF training parameters _a : Optional[int] = False _a : Dict = False def _a (lowercase__ : Namespace ) -> int: """simple docstring""" return TrainCommand(lowercase__ ) class _lowercase ( __lowercase ): @staticmethod def a ( SCREAMING_SNAKE_CASE_ : ArgumentParser ) -> Any: __snake_case = parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE_ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE_ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE_ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE_ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE_ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE_ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE_ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE_ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE_ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE_ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE_ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE_ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE_ ) def __init__( self : str , SCREAMING_SNAKE_CASE_ : Namespace ) -> Optional[int]: __snake_case = logging.get_logger('transformers-cli/training' ) __snake_case = 'tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE_ ) __snake_case = args.output __snake_case = args.column_label __snake_case = args.column_text __snake_case = args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": __snake_case = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) __snake_case = Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) __snake_case = None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) __snake_case = Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) __snake_case = args.validation_split __snake_case = args.train_batch_size __snake_case = args.valid_batch_size __snake_case = args.learning_rate __snake_case = args.adam_epsilon def a ( self : Optional[int] ) -> int: if self.framework == "tf": return self.run_tf() return self.run_torch() def a ( self : Tuple ) -> List[str]: raise NotImplementedError def a ( self : Dict ) -> Optional[int]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
56
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class lowercase__ ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : List[str] = tempfile.mkdtemp() # fmt: off _SCREAMING_SNAKE_CASE : Any = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on _SCREAMING_SNAKE_CASE : Union[str, Any] = dict(zip(__snake_case , range(len(__snake_case ) ) ) ) _SCREAMING_SNAKE_CASE : str = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] _SCREAMING_SNAKE_CASE : Any = {"""unk_token""": """<unk>"""} _SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) _SCREAMING_SNAKE_CASE : Optional[Any] = 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 ) ) _SCREAMING_SNAKE_CASE : Any = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } _SCREAMING_SNAKE_CASE : List[str] = os.path.join(self.tmpdirname , __snake_case ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__snake_case , __snake_case ) def UpperCAmelCase_ ( self , **__snake_case ): return CLIPTokenizer.from_pretrained(self.tmpdirname , **__snake_case ) def UpperCAmelCase_ ( self , **__snake_case ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__snake_case ) def UpperCAmelCase_ ( self , **__snake_case ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **__snake_case ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _SCREAMING_SNAKE_CASE : List[str] = [Image.fromarray(np.moveaxis(__snake_case , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() _SCREAMING_SNAKE_CASE : int = self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() _SCREAMING_SNAKE_CASE : str = CLIPSegProcessor(tokenizer=__snake_case , image_processor=__snake_case ) processor_slow.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE : List[str] = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=__snake_case ) _SCREAMING_SNAKE_CASE : Any = CLIPSegProcessor(tokenizer=__snake_case , image_processor=__snake_case ) processor_fast.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __snake_case ) self.assertIsInstance(processor_fast.tokenizer , __snake_case ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __snake_case ) self.assertIsInstance(processor_fast.image_processor , __snake_case ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : int = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE : str = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=__snake_case , padding_value=1.0 ) _SCREAMING_SNAKE_CASE : Tuple = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__snake_case , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __snake_case ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __snake_case ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() _SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPSegProcessor(tokenizer=__snake_case , image_processor=__snake_case ) _SCREAMING_SNAKE_CASE : List[Any] = self.prepare_image_inputs() _SCREAMING_SNAKE_CASE : List[Any] = image_processor(__snake_case , return_tensors="""np""" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = processor(images=__snake_case , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() _SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() _SCREAMING_SNAKE_CASE : Optional[Any] = CLIPSegProcessor(tokenizer=__snake_case , image_processor=__snake_case ) _SCREAMING_SNAKE_CASE : str = """lower newer""" _SCREAMING_SNAKE_CASE : Any = processor(text=__snake_case ) _SCREAMING_SNAKE_CASE : Tuple = tokenizer(__snake_case ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() _SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() _SCREAMING_SNAKE_CASE : Dict = CLIPSegProcessor(tokenizer=__snake_case , image_processor=__snake_case ) _SCREAMING_SNAKE_CASE : Any = """lower newer""" _SCREAMING_SNAKE_CASE : List[Any] = self.prepare_image_inputs() _SCREAMING_SNAKE_CASE : List[str] = processor(text=__snake_case , images=__snake_case ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__snake_case ): processor() def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() _SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizer() _SCREAMING_SNAKE_CASE : List[Any] = CLIPSegProcessor(tokenizer=__snake_case , image_processor=__snake_case ) _SCREAMING_SNAKE_CASE : str = self.prepare_image_inputs() _SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_image_inputs() _SCREAMING_SNAKE_CASE : List[Any] = processor(images=__snake_case , visual_prompt=__snake_case ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """conditional_pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__snake_case ): processor() def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() _SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() _SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPSegProcessor(tokenizer=__snake_case , image_processor=__snake_case ) _SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _SCREAMING_SNAKE_CASE : int = processor.batch_decode(__snake_case ) _SCREAMING_SNAKE_CASE : int = tokenizer.batch_decode(__snake_case ) self.assertListEqual(__snake_case , __snake_case )
533
0
from ..utils import DummyObject, requires_backends class snake_case ( metaclass=SCREAMING_SNAKE_CASE_ ): '''simple docstring''' snake_case_ : Any = ["""speech"""] def __init__( self : List[str] , *lowerCAmelCase : Optional[int] , **lowerCAmelCase : Optional[Any]) -> Tuple: """simple docstring""" requires_backends(self , ["""speech"""]) class snake_case ( metaclass=SCREAMING_SNAKE_CASE_ ): '''simple docstring''' snake_case_ : Union[str, Any] = ["""speech"""] def __init__( self : Optional[int] , *lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : Optional[int]) -> Optional[Any]: """simple docstring""" requires_backends(self , ["""speech"""])
713
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_camembert import CamembertTokenizer else: a__ = None a__ = logging.get_logger(__name__) a__ = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} a__ = { """vocab_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model""", }, """tokenizer_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/tokenizer.json""", }, } a__ = { """camembert-base""": 5_12, } a__ = """▁""" class snake_case ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' snake_case_ : List[str] = VOCAB_FILES_NAMES snake_case_ : str = PRETRAINED_VOCAB_FILES_MAP snake_case_ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ : List[Any] = ["""input_ids""", """attention_mask"""] snake_case_ : int = CamembertTokenizer def __init__( self : Optional[int] , lowerCAmelCase : Optional[Any]=None , lowerCAmelCase : int=None , lowerCAmelCase : List[Any]="<s>" , lowerCAmelCase : List[str]="</s>" , lowerCAmelCase : Union[str, Any]="</s>" , lowerCAmelCase : Dict="<s>" , lowerCAmelCase : Dict="<unk>" , lowerCAmelCase : Any="<pad>" , lowerCAmelCase : List[str]="<mask>" , lowerCAmelCase : List[str]=["<s>NOTUSED", "</s>NOTUSED"] , **lowerCAmelCase : Dict , ) -> Tuple: """simple docstring""" _snake_case : Dict = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase) if isinstance(lowerCAmelCase , lowerCAmelCase) else mask_token super().__init__( lowerCAmelCase , tokenizer_file=lowerCAmelCase , bos_token=lowerCAmelCase , eos_token=lowerCAmelCase , sep_token=lowerCAmelCase , cls_token=lowerCAmelCase , unk_token=lowerCAmelCase , pad_token=lowerCAmelCase , mask_token=lowerCAmelCase , additional_special_tokens=lowerCAmelCase , **lowerCAmelCase , ) _snake_case : List[str] = vocab_file _snake_case : Optional[Any] = False if not self.vocab_file else True def UpperCamelCase_ ( self : Optional[int] , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _snake_case : Optional[Any] = [self.cls_token_id] _snake_case : List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : str , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None) -> List[int]: """simple docstring""" _snake_case : str = [self.sep_token_id] _snake_case : 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 UpperCamelCase_ ( self : str , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""") if not os.path.isdir(lowerCAmelCase): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''') return _snake_case : Optional[int] = os.path.join( lowerCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]) if os.path.abspath(self.vocab_file) != os.path.abspath(lowerCAmelCase): copyfile(self.vocab_file , lowerCAmelCase) return (out_vocab_file,)
198
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/wavlm-base""": """https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json""", # See all WavLM models at https://huggingface.co/models?filter=wavlm } class UpperCAmelCase_ ( __UpperCamelCase ): """simple docstring""" UpperCamelCase_ : Any ='wavlm' def __init__( self , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_="group" , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=(512, 512, 512, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE_=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE_=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=128 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=320 , SCREAMING_SNAKE_CASE_=800 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.05 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=320 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_="mean" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=(512, 512, 512, 512, 1500) , SCREAMING_SNAKE_CASE_=(5, 3, 3, 1, 1) , SCREAMING_SNAKE_CASE_=(1, 2, 3, 1, 1) , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> str: super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = hidden_size UpperCamelCase :Dict = feat_extract_norm UpperCamelCase :List[Any] = feat_extract_activation UpperCamelCase :Dict = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = conv_bias UpperCamelCase :Union[str, Any] = num_buckets UpperCamelCase :List[Any] = max_bucket_distance UpperCamelCase :Tuple = num_conv_pos_embeddings UpperCamelCase :Optional[int] = num_conv_pos_embedding_groups UpperCamelCase :Optional[int] = len(self.conv_dim ) UpperCamelCase :List[str] = num_hidden_layers UpperCamelCase :Optional[int] = intermediate_size UpperCamelCase :Tuple = hidden_act UpperCamelCase :Optional[Any] = num_attention_heads UpperCamelCase :Dict = hidden_dropout UpperCamelCase :List[Any] = attention_dropout UpperCamelCase :Dict = activation_dropout UpperCamelCase :Optional[Any] = feat_proj_dropout UpperCamelCase :List[Any] = final_dropout UpperCamelCase :List[str] = layerdrop UpperCamelCase :str = layer_norm_eps UpperCamelCase :Dict = initializer_range UpperCamelCase :List[str] = num_ctc_classes UpperCamelCase :Dict = vocab_size UpperCamelCase :List[str] = do_stable_layer_norm UpperCamelCase :Optional[Any] = use_weighted_layer_sum UpperCamelCase :Tuple = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCamelCase :Dict = apply_spec_augment UpperCamelCase :Dict = mask_time_prob UpperCamelCase :Dict = mask_time_length UpperCamelCase :Optional[int] = mask_time_min_masks UpperCamelCase :int = mask_feature_prob UpperCamelCase :List[Any] = mask_feature_length # parameters for pretraining with codevector quantized representations UpperCamelCase :Optional[int] = num_codevectors_per_group UpperCamelCase :List[Any] = num_codevector_groups UpperCamelCase :Optional[Any] = contrastive_logits_temperature UpperCamelCase :Optional[Any] = num_negatives UpperCamelCase :Union[str, Any] = codevector_dim UpperCamelCase :Optional[int] = proj_codevector_dim UpperCamelCase :Tuple = diversity_loss_weight # ctc loss UpperCamelCase :Union[str, Any] = ctc_loss_reduction UpperCamelCase :Optional[Any] = ctc_zero_infinity # adapter UpperCamelCase :List[str] = add_adapter UpperCamelCase :List[Any] = adapter_kernel_size UpperCamelCase :Tuple = adapter_stride UpperCamelCase :str = num_adapter_layers UpperCamelCase :Any = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. UpperCamelCase :Optional[int] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. UpperCamelCase :List[Any] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = xvector_output_dim @property def UpperCAmelCase ( self ) -> Any: return functools.reduce(operator.mul , self.conv_stride , 1 )
658
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class lowerCAmelCase : def __init__( self : List[str] , UpperCAmelCase : List[Any] , UpperCAmelCase : str=14 , UpperCAmelCase : Any=7 , UpperCAmelCase : Dict=True , UpperCAmelCase : List[str]=True , UpperCAmelCase : Any=False , UpperCAmelCase : Tuple=True , UpperCAmelCase : int=99 , UpperCAmelCase : str=32 , UpperCAmelCase : int=4 , UpperCAmelCase : Optional[Any]=4 , UpperCAmelCase : Any=4 , UpperCAmelCase : Optional[int]=37 , UpperCAmelCase : Union[str, Any]="gelu" , UpperCAmelCase : List[Any]=0.1 , UpperCAmelCase : Dict=0.1 , UpperCAmelCase : Optional[int]=512 , UpperCAmelCase : List[Any]=0.0_2 , ) -> List[Any]: lowerCamelCase__ : Tuple = parent lowerCamelCase__ : Tuple = batch_size lowerCamelCase__ : Optional[Any] = seq_length lowerCamelCase__ : str = is_training lowerCamelCase__ : Any = use_input_mask lowerCamelCase__ : Optional[Any] = use_token_type_ids lowerCamelCase__ : Optional[Any] = use_labels lowerCamelCase__ : Optional[Any] = vocab_size lowerCamelCase__ : Optional[int] = hidden_size lowerCamelCase__ : Optional[Any] = rotary_dim lowerCamelCase__ : Optional[Any] = num_hidden_layers lowerCamelCase__ : Optional[Any] = num_attention_heads lowerCamelCase__ : Tuple = intermediate_size lowerCamelCase__ : Union[str, Any] = hidden_act lowerCamelCase__ : List[Any] = hidden_dropout_prob lowerCamelCase__ : int = attention_probs_dropout_prob lowerCamelCase__ : Dict = max_position_embeddings lowerCamelCase__ : Tuple = initializer_range lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : int = vocab_size - 1 lowerCamelCase__ : str = vocab_size - 1 lowerCamelCase__ : str = vocab_size - 1 def A_ ( self : str ) -> int: lowerCamelCase__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : Optional[Any] = None if self.use_input_mask: lowerCamelCase__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase__ : Tuple = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=UpperCAmelCase , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def A_ ( self : Optional[Any] ) -> Union[str, Any]: lowerCamelCase__ : Tuple = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[Any] = config_and_inputs lowerCamelCase__ : List[Any] = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def A_ ( self : int , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Any , UpperCAmelCase : List[str] , UpperCAmelCase : Optional[Any] ) -> Tuple: lowerCamelCase__ : Tuple = 20 lowerCamelCase__ : Dict = model_class_name(UpperCAmelCase ) lowerCamelCase__ : Dict = model.init_cache(input_ids.shape[0] , UpperCAmelCase ) lowerCamelCase__ : int = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) lowerCamelCase__ : List[str] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) lowerCamelCase__ : Optional[int] = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase , past_key_values=UpperCAmelCase , position_ids=UpperCAmelCase , ) lowerCamelCase__ : List[str] = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) lowerCamelCase__ : List[str] = model( input_ids[:, -1:] , attention_mask=UpperCAmelCase , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase , ) lowerCamelCase__ : List[str] = model(UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) def A_ ( self : Union[str, Any] , UpperCAmelCase : Any , UpperCAmelCase : Any , UpperCAmelCase : List[Any] , UpperCAmelCase : List[str] ) -> Optional[Any]: lowerCamelCase__ : Any = 20 lowerCamelCase__ : Any = model_class_name(UpperCAmelCase ) lowerCamelCase__ : List[str] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) lowerCamelCase__ : str = model.init_cache(input_ids.shape[0] , UpperCAmelCase ) lowerCamelCase__ : Dict = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) lowerCamelCase__ : List[Any] = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase , past_key_values=UpperCAmelCase , position_ids=UpperCAmelCase , ) lowerCamelCase__ : Optional[Any] = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) lowerCamelCase__ : List[Any] = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase , position_ids=UpperCAmelCase , ) lowerCamelCase__ : List[Any] = model(UpperCAmelCase , attention_mask=UpperCAmelCase ) lowerCamelCase__ : Dict = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) @require_flax class lowerCAmelCase ( __UpperCamelCase, __UpperCamelCase, unittest.TestCase ): UpperCAmelCase__ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () UpperCAmelCase__ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def A_ ( self : Optional[Any] ) -> Tuple: lowerCamelCase__ : Optional[Any] = FlaxGPTJModelTester(self ) def A_ ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Tuple: for model_class_name in self.all_model_classes: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) @tooslow def A_ ( self : Dict ) -> Tuple: lowerCamelCase__ : str = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) lowerCamelCase__ : Dict = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=UpperCAmelCase , truncation=UpperCAmelCase ) lowerCamelCase__ : str = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) lowerCamelCase__ : Optional[int] = False lowerCamelCase__ : Optional[int] = model.config.eos_token_id lowerCamelCase__ : Union[str, Any] = jax.jit(model.generate ) lowerCamelCase__ : Optional[Any] = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences lowerCamelCase__ : Optional[int] = tokenizer.batch_decode(UpperCAmelCase , skip_special_tokens=UpperCAmelCase ) lowerCamelCase__ : int = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) @is_pt_flax_cross_test def A_ ( self : List[str] ) -> Union[str, Any]: lowerCamelCase__ , lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs lowerCamelCase__ : Dict = self._prepare_for_class(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Optional[int] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowerCamelCase__ : Any = model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCamelCase__ : Union[str, Any] = getattr(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ , lowerCamelCase__ : Tuple = pt_inputs['input_ids'].shape lowerCamelCase__ : Tuple = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase ): lowerCamelCase__ : List[str] = 0 lowerCamelCase__ : Optional[int] = 1 lowerCamelCase__ : Any = 0 lowerCamelCase__ : Any = 1 lowerCamelCase__ : Dict = pt_model_class(UpperCAmelCase ).eval() lowerCamelCase__ : str = model_class(UpperCAmelCase , dtype=jnp.floataa ) lowerCamelCase__ : str = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase ) lowerCamelCase__ : Tuple = fx_state with torch.no_grad(): lowerCamelCase__ : List[str] = pt_model(**UpperCAmelCase ).to_tuple() lowerCamelCase__ : Dict = fx_model(**UpperCAmelCase ).to_tuple() self.assertEqual(len(UpperCAmelCase ) , len(UpperCAmelCase ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(UpperCAmelCase , UpperCAmelCase ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCAmelCase ) lowerCamelCase__ : Tuple = model_class.from_pretrained(UpperCAmelCase , from_pt=UpperCAmelCase ) lowerCamelCase__ : int = fx_model_loaded(**UpperCAmelCase ).to_tuple() self.assertEqual( len(UpperCAmelCase ) , len(UpperCAmelCase ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(UpperCAmelCase , UpperCAmelCase ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @is_pt_flax_cross_test def A_ ( self : Union[str, Any] ) -> int: lowerCamelCase__ , lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs lowerCamelCase__ : Tuple = self._prepare_for_class(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Tuple = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowerCamelCase__ : Union[str, Any] = model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCamelCase__ : int = getattr(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : List[Any] = pt_model_class(UpperCAmelCase ).eval() lowerCamelCase__ : str = model_class(UpperCAmelCase , dtype=jnp.floataa ) lowerCamelCase__ : List[str] = load_flax_weights_in_pytorch_model(UpperCAmelCase , fx_model.params ) lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = pt_inputs['input_ids'].shape lowerCamelCase__ : Dict = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase ): lowerCamelCase__ : List[Any] = 0 lowerCamelCase__ : Tuple = 1 lowerCamelCase__ : Optional[Any] = 0 lowerCamelCase__ : List[str] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): lowerCamelCase__ : Any = pt_model(**UpperCAmelCase ).to_tuple() lowerCamelCase__ : List[Any] = fx_model(**UpperCAmelCase ).to_tuple() self.assertEqual(len(UpperCAmelCase ) , len(UpperCAmelCase ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(UpperCAmelCase , UpperCAmelCase ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCAmelCase ) lowerCamelCase__ : Tuple = pt_model_class.from_pretrained(UpperCAmelCase , from_flax=UpperCAmelCase ) with torch.no_grad(): lowerCamelCase__ : Optional[int] = pt_model_loaded(**UpperCAmelCase ).to_tuple() self.assertEqual( len(UpperCAmelCase ) , len(UpperCAmelCase ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(UpperCAmelCase , UpperCAmelCase ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @tooslow def A_ ( self : List[str] ) -> List[Any]: for model_class_name in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) lowerCamelCase__ : Any = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase )
295
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ = { '''configuration_albert''': ['''ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AlbertConfig''', '''AlbertOnnxConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['''AlbertTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['''AlbertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AlbertForMaskedLM''', '''AlbertForMultipleChoice''', '''AlbertForPreTraining''', '''AlbertForQuestionAnswering''', '''AlbertForSequenceClassification''', '''AlbertForTokenClassification''', '''AlbertModel''', '''AlbertPreTrainedModel''', '''load_tf_weights_in_albert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFAlbertForMaskedLM''', '''TFAlbertForMultipleChoice''', '''TFAlbertForPreTraining''', '''TFAlbertForQuestionAnswering''', '''TFAlbertForSequenceClassification''', '''TFAlbertForTokenClassification''', '''TFAlbertMainLayer''', '''TFAlbertModel''', '''TFAlbertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''FlaxAlbertForMaskedLM''', '''FlaxAlbertForMultipleChoice''', '''FlaxAlbertForPreTraining''', '''FlaxAlbertForQuestionAnswering''', '''FlaxAlbertForSequenceClassification''', '''FlaxAlbertForTokenClassification''', '''FlaxAlbertModel''', '''FlaxAlbertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
715
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging a :int = logging.get_logger(__name__) a :List[Any] = { "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json", "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json", "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json", "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json", "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json", "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Dict = """bloom""" _SCREAMING_SNAKE_CASE :Optional[Any] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Union[str, Any] = { """num_hidden_layers""": """n_layer""", """num_attention_heads""": """n_head""", } def __init__( self , _a=250_880 , _a=64 , _a=2 , _a=8 , _a=1E-5 , _a=0.02 , _a=True , _a=1 , _a=2 , _a=False , _a=0.0 , _a=0.0 , _a=1 , _a=False , **_a , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = vocab_size # Backward compatibility with n_embed kwarg SCREAMING_SNAKE_CASE__ : Union[str, Any] = kwargs.pop("""n_embed""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = hidden_size if n_embed is None else n_embed SCREAMING_SNAKE_CASE__ : Optional[Any] = n_layer SCREAMING_SNAKE_CASE__ : Any = n_head SCREAMING_SNAKE_CASE__ : List[Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_cache SCREAMING_SNAKE_CASE__ : Optional[Any] = pretraining_tp SCREAMING_SNAKE_CASE__ : List[str] = apply_residual_connection_post_layernorm SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout SCREAMING_SNAKE_CASE__ : List[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : Optional[int] = bos_token_id SCREAMING_SNAKE_CASE__ : Union[str, Any] = eos_token_id SCREAMING_SNAKE_CASE__ : List[str] = slow_but_exact super().__init__(bos_token_id=_a , eos_token_id=_a , **_a ) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = version.parse("""1.12""") def __init__( self , _a , _a = "default" , _a = None , _a = False , ) -> Tuple: """simple docstring""" super().__init__(_a , task=_a , patching_specs=_a , use_past=_a ) if not getattr(self._config , """pad_token_id""" , _a ): # TODO: how to do that better? SCREAMING_SNAKE_CASE__ : List[Any] = 0 @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(_a , direction="""inputs""" , inverted_values_shape=_a ) SCREAMING_SNAKE_CASE__ : List[str] = {0: """batch""", 1: """past_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : Dict = {0: """batch""", 1: """sequence"""} return common_inputs @property def _a ( self ) -> int: """simple docstring""" return self._config.n_layer @property def _a ( self ) -> int: """simple docstring""" return self._config.n_head @property def _a ( self ) -> float: """simple docstring""" return 1E-3 def _a ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = super(_a , self ).generate_dummy_inputs( _a , batch_size=_a , seq_length=_a , is_pair=_a , framework=_a ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE__ : Optional[int] = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE__ : Tuple = seqlen + 2 SCREAMING_SNAKE_CASE__ : str = self._config.hidden_size // self.num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) SCREAMING_SNAKE_CASE__ : List[Any] = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) SCREAMING_SNAKE_CASE__ : Tuple = [ (torch.zeros(_a ), torch.zeros(_a )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE__ : Union[str, Any] = common_inputs["""attention_mask"""] if self.use_past: SCREAMING_SNAKE_CASE__ : Tuple = ordered_inputs["""attention_mask"""].dtype SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(_a , _a , dtype=_a )] , dim=1 ) return ordered_inputs @property def _a ( self ) -> int: """simple docstring""" return 13
680
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
1
'''simple docstring''' import enum import shutil import sys UpperCamelCase__ , UpperCamelCase__: Any = shutil.get_terminal_size() UpperCamelCase__: Optional[Any] = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"} class SCREAMING_SNAKE_CASE( enum.Enum ): """simple docstring""" lowerCamelCase__ = 0 lowerCamelCase__ = 1 def snake_case_ ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Tuple="" ) -> List[str]: sys.stdout.write(str(_lowerCAmelCase ) + end ) sys.stdout.flush() def snake_case_ ( _lowerCAmelCase : Dict , _lowerCAmelCase : str , _lowerCAmelCase : Union[str, Any]="" ) -> List[str]: forceWrite(f"""\u001b[{color}m{content}\u001b[0m""" , _lowerCAmelCase ) def snake_case_ ( ) -> int: forceWrite('''\r''' ) def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : str ) -> Dict: forceWrite(f"""\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}""" ) def snake_case_ ( ) -> Optional[int]: forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def snake_case_ ( ) -> List[Any]: reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
528
'''simple docstring''' import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def snake_case_ ( _lowerCAmelCase : Dataset , _lowerCAmelCase : Dict[str, str] ) -> str: UpperCAmelCase : Optional[int] = args.log_outputs UpperCAmelCase : Any = '''_'''.join(args.dataset.split('''/''' ) + [args.config, args.split] ) # load metric UpperCAmelCase : Union[str, Any] = load_metric('''wer''' ) UpperCAmelCase : Dict = load_metric('''cer''' ) # compute metrics UpperCAmelCase : Any = wer.compute(references=result['''target'''] , predictions=result['''prediction'''] ) UpperCAmelCase : str = cer.compute(references=result['''target'''] , predictions=result['''prediction'''] ) # print & log results UpperCAmelCase : Tuple = f"""WER: {wer_result}\nCER: {cer_result}""" print(_lowerCAmelCase ) with open(f"""{dataset_id}_eval_results.txt""" , '''w''' ) as f: f.write(_lowerCAmelCase ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCAmelCase : Union[str, Any] = f"""log_{dataset_id}_predictions.txt""" UpperCAmelCase : Optional[Any] = f"""log_{dataset_id}_targets.txt""" with open(_lowerCAmelCase , '''w''' ) as p, open(_lowerCAmelCase , '''w''' ) as t: # mapping function to write output def write_to_file(_lowerCAmelCase : int , _lowerCAmelCase : str ): p.write(f"""{i}""" + '''\n''' ) p.write(batch['''prediction'''] + '''\n''' ) t.write(f"""{i}""" + '''\n''' ) t.write(batch['''target'''] + '''\n''' ) result.map(_lowerCAmelCase , with_indices=_lowerCAmelCase ) def snake_case_ ( _lowerCAmelCase : str ) -> str: UpperCAmelCase : Optional[int] = '''[,?.!\-\;\:"“%‘”�—’…–]''' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCAmelCase : List[Any] = re.sub(_lowerCAmelCase , '''''' , text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCAmelCase : str = ['''\n\n''', '''\n''', ''' ''', ''' '''] for t in token_sequences_to_ignore: UpperCAmelCase : List[Any] = ''' '''.join(text.split(_lowerCAmelCase ) ) return text def snake_case_ ( _lowerCAmelCase : Optional[Any] ) -> Union[str, Any]: # load dataset UpperCAmelCase : Optional[int] = load_dataset(args.dataset , args.config , split=args.split , use_auth_token=_lowerCAmelCase ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCAmelCase : Any = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCAmelCase : Optional[Any] = feature_extractor.sampling_rate # resample audio UpperCAmelCase : Tuple = dataset.cast_column('''audio''' , Audio(sampling_rate=_lowerCAmelCase ) ) # load eval pipeline if args.device is None: UpperCAmelCase : List[Any] = 0 if torch.cuda.is_available() else -1 UpperCAmelCase : List[Any] = pipeline('''automatic-speech-recognition''' , model=args.model_id , device=args.device ) # map function to decode audio def map_to_pred(_lowerCAmelCase : List[str] ): UpperCAmelCase : Optional[int] = asr( batch['''audio''']['''array'''] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s ) UpperCAmelCase : str = prediction['''text'''] UpperCAmelCase : int = normalize_text(batch['''sentence'''] ) return batch # run inference on all examples UpperCAmelCase : Tuple = dataset.map(_lowerCAmelCase , remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(_lowerCAmelCase , _lowerCAmelCase ) if __name__ == "__main__": UpperCamelCase__: List[Any] = argparse.ArgumentParser() parser.add_argument( "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers" ) parser.add_argument( "--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets", ) parser.add_argument( "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice" ) parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`") parser.add_argument( "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds." ) parser.add_argument( "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second." ) parser.add_argument( "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis." ) parser.add_argument( "--device", type=int, default=None, help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.", ) UpperCamelCase__: List[str] = parser.parse_args() main(args)
528
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) _lowerCamelCase : List[Any] = logging.getLogger() _lowerCamelCase : Optional[int] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class SCREAMING_SNAKE_CASE ( a__ ): """simple docstring""" def A ( self : Optional[Any] , UpperCamelCase__ : Tuple ): """simple docstring""" os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) UpperCamelCase = {"source": "What is love ?", "target": "life"} UpperCamelCase = {"train": 1_2, "val": 2, "test": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: UpperCamelCase = "\n".join([contents[field]] * n_lines[split] ) with open(os.path.join(UpperCamelCase__ , f"""{split}.{field}""" ) , 'w' ) as f: f.write(UpperCamelCase__ ) def A ( self : Any , UpperCamelCase__ : int , UpperCamelCase__ : str = "pytorch" ): """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = os.path.join(UpperCamelCase__ , 'output' ) UpperCamelCase = os.path.join(UpperCamelCase__ , 'data' ) self._create_dummy_data(data_dir=UpperCamelCase__ ) UpperCamelCase = f""" --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ """.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' ) UpperCamelCase = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(UpperCamelCase__ , env=self.get_env() ) UpperCamelCase = os.path.join(UpperCamelCase__ , 'metrics.json' ) with open(UpperCamelCase__ ) as f: UpperCamelCase = json.load(UpperCamelCase__ ) return result @require_torch_gpu def A ( self : Any ): """simple docstring""" UpperCamelCase = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 ) @require_torch_multi_gpu def A ( self : Any ): """simple docstring""" UpperCamelCase = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 ) @require_torch_gpu @require_ray def A ( self : List[str] ): """simple docstring""" UpperCamelCase = 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 A ( self : Any ): """simple docstring""" UpperCamelCase = self._run_finetune(gpus=1 , distributed_retriever='ray' ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 )
430
"""simple docstring""" import math def lowercase_ ( _lowerCamelCase: int ) -> list[int]: '''simple docstring''' __lowerCamelCase : Optional[int] = [] __lowerCamelCase : Tuple = 2 __lowerCamelCase : str = int(math.sqrt(_lowerCamelCase ) ) # Size of every segment __lowerCamelCase : str = [True] * (end + 1) __lowerCamelCase : int = [] while start <= end: if temp[start] is True: in_prime.append(_lowerCamelCase ) for i in range(start * start , end + 1 , _lowerCamelCase ): __lowerCamelCase : List[str] = False start += 1 prime += in_prime __lowerCamelCase : Union[str, Any] = end + 1 __lowerCamelCase : Union[str, Any] = min(2 * end , _lowerCamelCase ) while low <= n: __lowerCamelCase : List[Any] = [True] * (high - low + 1) for each in in_prime: __lowerCamelCase : int = math.floor(low / each ) * each if t < low: t += each for j in range(_lowerCamelCase , high + 1 , _lowerCamelCase ): __lowerCamelCase : Dict = False for j in range(len(_lowerCamelCase ) ): if temp[j] is True: prime.append(j + low ) __lowerCamelCase : List[str] = high + 1 __lowerCamelCase : Union[str, Any] = min(high + end , _lowerCamelCase ) return prime print(sieve(10**6))
646
0
"""simple docstring""" import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger lowerCamelCase_ : Any = get_logger(__name__) class UpperCamelCase_ : def __init__( self : Tuple , lowerCAmelCase_ : Optional[str] = None ) -> str: UpperCAmelCase_ : Optional[Any] = ( os.path.join(lowerCAmelCase_ , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) UpperCAmelCase_ : str = Extractor def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : str ) -> str: from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" UpperCAmelCase_ : Optional[Any] = os.path.abspath(lowerCAmelCase_ ) return os.path.join(self.extract_dir , hash_url_to_filename(lowerCAmelCase_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : bool ) -> bool: return force_extract or ( not os.path.isfile(lowerCAmelCase_ ) and not (os.path.isdir(lowerCAmelCase_ ) and os.listdir(lowerCAmelCase_ )) ) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase_ : str , lowerCAmelCase_ : bool = False ) -> str: UpperCAmelCase_ : str = self.extractor.infer_extractor_format(lowerCAmelCase_ ) if not extractor_format: return input_path UpperCAmelCase_ : Tuple = self._get_output_path(lowerCAmelCase_ ) if self._do_extract(lowerCAmelCase_ , lowerCAmelCase_ ): self.extractor.extract(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return output_path class UpperCamelCase_ (__A ): @classmethod @abstractmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowerCAmelCase_ : Union[Path, str] , **lowerCAmelCase_ : int ) -> bool: ... @staticmethod @abstractmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: ... class UpperCamelCase_ (__A , __A ): __magic_name__ = [] @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : int ) -> List[str]: with open(lowerCAmelCase_ , "rb" ) as f: return f.read(lowerCAmelCase_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : bytes = b"" ) -> bool: if not magic_number: UpperCAmelCase_ : List[Any] = max(len(lowerCAmelCase_ ) for cls_magic_number in cls.magic_numbers ) try: UpperCAmelCase_ : str = cls.read_magic_number(lowerCAmelCase_ , lowerCAmelCase_ ) except OSError: return False return any(magic_number.startswith(lowerCAmelCase_ ) for cls_magic_number in cls.magic_numbers ) class UpperCamelCase_ (__A ): @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowerCAmelCase_ : Union[Path, str] , **lowerCAmelCase_ : Any ) -> bool: return tarfile.is_tarfile(lowerCAmelCase_ ) @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Any , lowerCAmelCase_ : Any ) -> Optional[int]: def resolved(lowerCAmelCase_ : str ) -> str: return os.path.realpath(os.path.abspath(lowerCAmelCase_ ) ) def badpath(lowerCAmelCase_ : str , lowerCAmelCase_ : str ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) ).startswith(lowerCAmelCase_ ) def badlink(lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : str ) -> bool: # Links are interpreted relative to the directory containing the link UpperCAmelCase_ : Any = resolved(os.path.join(lowerCAmelCase_ , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=lowerCAmelCase_ ) UpperCAmelCase_ : int = resolved(lowerCAmelCase_ ) for finfo in members: if badpath(finfo.name , lowerCAmelCase_ ): logger.error(f"""Extraction of {finfo.name} is blocked (illegal path)""" ) elif finfo.issym() and badlink(lowerCAmelCase_ , lowerCAmelCase_ ): logger.error(f"""Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}""" ) elif finfo.islnk() and badlink(lowerCAmelCase_ , lowerCAmelCase_ ): logger.error(f"""Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}""" ) else: yield finfo @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) UpperCAmelCase_ : List[Any] = tarfile.open(lowerCAmelCase_ ) tar_file.extractall(lowerCAmelCase_ , members=TarExtractor.safemembers(lowerCAmelCase_ , lowerCAmelCase_ ) ) tar_file.close() class UpperCamelCase_ (__A ): __magic_name__ = [b'''\x1F\x8B'''] @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: with gzip.open(lowerCAmelCase_ , "rb" ) as gzip_file: with open(lowerCAmelCase_ , "wb" ) as extracted_file: shutil.copyfileobj(lowerCAmelCase_ , lowerCAmelCase_ ) class UpperCamelCase_ (__A ): __magic_name__ = [ b'''PK\x03\x04''', b'''PK\x05\x06''', # empty archive b'''PK\x07\x08''', # spanned archive ] @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : bytes = b"" ) -> bool: if super().is_extractable(lowerCAmelCase_ , magic_number=lowerCAmelCase_ ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(lowerCAmelCase_ , "rb" ) as fp: UpperCAmelCase_ : Optional[int] = _EndRecData(lowerCAmelCase_ ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: UpperCAmelCase_ : str = fp.read(lowerCAmelCase_ ) # CD is where we expect it to be if len(lowerCAmelCase_ ) == sizeCentralDir: UpperCAmelCase_ : Optional[int] = struct.unpack(lowerCAmelCase_ , lowerCAmelCase_ ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) with zipfile.ZipFile(lowerCAmelCase_ , "r" ) as zip_file: zip_file.extractall(lowerCAmelCase_ ) zip_file.close() class UpperCamelCase_ (__A ): __magic_name__ = [b'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: with lzma.open(lowerCAmelCase_ ) as compressed_file: with open(lowerCAmelCase_ , "wb" ) as extracted_file: shutil.copyfileobj(lowerCAmelCase_ , lowerCAmelCase_ ) class UpperCamelCase_ (__A ): __magic_name__ = [b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: if not config.RARFILE_AVAILABLE: raise ImportError("Please pip install rarfile" ) import rarfile os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) UpperCAmelCase_ : List[Any] = rarfile.RarFile(lowerCAmelCase_ ) rf.extractall(lowerCAmelCase_ ) rf.close() class UpperCamelCase_ (__A ): __magic_name__ = [b'''\x28\xb5\x2F\xFD'''] @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: if not config.ZSTANDARD_AVAILABLE: raise ImportError("Please pip install zstandard" ) import zstandard as zstd UpperCAmelCase_ : Tuple = zstd.ZstdDecompressor() with open(lowerCAmelCase_ , "rb" ) as ifh, open(lowerCAmelCase_ , "wb" ) as ofh: dctx.copy_stream(lowerCAmelCase_ , lowerCAmelCase_ ) class UpperCamelCase_ (__A ): __magic_name__ = [b'''\x42\x5A\x68'''] @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: with bza.open(lowerCAmelCase_ , "rb" ) as compressed_file: with open(lowerCAmelCase_ , "wb" ) as extracted_file: shutil.copyfileobj(lowerCAmelCase_ , lowerCAmelCase_ ) class UpperCamelCase_ (__A ): __magic_name__ = [b'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: if not config.PY7ZR_AVAILABLE: raise ImportError("Please pip install py7zr" ) import pyazr os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) with pyazr.SevenZipFile(lowerCAmelCase_ , "r" ) as archive: archive.extractall(lowerCAmelCase_ ) class UpperCamelCase_ (__A ): __magic_name__ = [b'''\x04\x22\x4D\x18'''] @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] ) -> None: if not config.LZ4_AVAILABLE: raise ImportError("Please pip install lz4" ) import lza.frame with lza.frame.open(lowerCAmelCase_ , "rb" ) as compressed_file: with open(lowerCAmelCase_ , "wb" ) as extracted_file: shutil.copyfileobj(lowerCAmelCase_ , lowerCAmelCase_ ) class UpperCamelCase_ : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) __magic_name__ = { '''tar''': TarExtractor, '''gzip''': GzipExtractor, '''zip''': ZipExtractor, '''xz''': XzExtractor, '''rar''': RarExtractor, '''zstd''': ZstdExtractor, '''bz2''': BzipaExtractor, '''7z''': SevenZipExtractor, # <Added version="2.4.0"/> '''lz4''': LzaExtractor, # <Added version="2.4.0"/> } @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ) -> List[str]: return max( len(lowerCAmelCase_ ) for extractor in cls.extractors.values() if issubclass(lowerCAmelCase_ , lowerCAmelCase_ ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : int ) -> int: try: return MagicNumberBaseExtractor.read_magic_number(lowerCAmelCase_ , magic_number_length=lowerCAmelCase_ ) except OSError: return b"" @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : bool = False ) -> bool: warnings.warn( "Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. " "Use 'infer_extractor_format' instead." , category=lowerCAmelCase_ , ) UpperCAmelCase_ : Tuple = cls.infer_extractor_format(lowerCAmelCase_ ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str , lowerCAmelCase_ : Union[Path, str] ) -> str: # <Added version="2.4.0"/> UpperCAmelCase_ : Any = cls._get_magic_number_max_length() UpperCAmelCase_ : Optional[Any] = cls._read_magic_number(lowerCAmelCase_ , lowerCAmelCase_ ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(lowerCAmelCase_ , magic_number=lowerCAmelCase_ ): return extractor_format @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Union[Path, str] , lowerCAmelCase_ : Optional[str] = None , lowerCAmelCase_ : Optional[BaseExtractor] = "deprecated" , ) -> None: os.makedirs(os.path.dirname(lowerCAmelCase_ ) , exist_ok=lowerCAmelCase_ ) # Prevent parallel extractions UpperCAmelCase_ : List[str] = str(Path(lowerCAmelCase_ ).with_suffix(".lock" ) ) with FileLock(lowerCAmelCase_ ): shutil.rmtree(lowerCAmelCase_ , ignore_errors=lowerCAmelCase_ ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): # passed as positional arg warnings.warn( "Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. " "Use 'extractor_format' instead." , category=lowerCAmelCase_ , ) UpperCAmelCase_ : Any = extractor if extractor != "deprecated" else extractor_format else: UpperCAmelCase_ : int = cls.extractors[extractor_format] return extractor.extract(lowerCAmelCase_ , lowerCAmelCase_ ) else: warnings.warn( "Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an " "exception in 3.0.0." , category=lowerCAmelCase_ , ) for extractor in cls.extractors.values(): if extractor.is_extractable(lowerCAmelCase_ ): return extractor.extract(lowerCAmelCase_ , lowerCAmelCase_ )
701
"""simple docstring""" lowerCamelCase_ = { '''a''': '''AAAAA''', '''b''': '''AAAAB''', '''c''': '''AAABA''', '''d''': '''AAABB''', '''e''': '''AABAA''', '''f''': '''AABAB''', '''g''': '''AABBA''', '''h''': '''AABBB''', '''i''': '''ABAAA''', '''j''': '''BBBAA''', '''k''': '''ABAAB''', '''l''': '''ABABA''', '''m''': '''ABABB''', '''n''': '''ABBAA''', '''o''': '''ABBAB''', '''p''': '''ABBBA''', '''q''': '''ABBBB''', '''r''': '''BAAAA''', '''s''': '''BAAAB''', '''t''': '''BAABA''', '''u''': '''BAABB''', '''v''': '''BBBAB''', '''w''': '''BABAA''', '''x''': '''BABAB''', '''y''': '''BABBA''', '''z''': '''BABBB''', ''' ''': ''' ''', } lowerCamelCase_ = {value: key for key, value in encode_dict.items()} def snake_case ( A__ ): UpperCAmelCase_ : Union[str, Any] = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces" ) return encoded def snake_case ( A__ ): if set(A__ ) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces" ) UpperCAmelCase_ : Dict = "" for word in coded.split(): while len(A__ ) != 0: decoded += decode_dict[word[:5]] UpperCAmelCase_ : str = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
463
0
import requests A : str = 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=' def UpperCamelCase ( __magic_name__ : str ) -> None: """simple docstring""" lowercase__ = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["""articles"""] , 1 ): print(f'''{i}.) {article["title"]}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='<Your BBC News API key goes here>')
15
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def _lowerCamelCase ( lowerCamelCase_: str=None ): '''simple docstring''' if subparsers is not None: A : Tuple = subparsers.add_parser('''test''' ) else: A : List[str] = argparse.ArgumentParser('''Accelerate test command''' ) parser.add_argument( '''--config_file''' , default=lowerCamelCase_ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=lowerCamelCase_ ) return parser def _lowerCamelCase ( lowerCamelCase_: str ): '''simple docstring''' A : Dict = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] ) if args.config_file is None: A : Any = script_name else: A : str = f"""--config_file={args.config_file} {script_name}""" A : Tuple = ['''accelerate-launch'''] + test_args.split() A : List[Any] = execute_subprocess_async(lowerCamelCase_ , env=os.environ.copy() ) if result.returncode == 0: print('''Test is a success! You are ready for your distributed training!''' ) def _lowerCamelCase ( ): '''simple docstring''' A : List[str] = test_command_parser() A : Any = parser.parse_args() test_command(lowerCamelCase_ ) if __name__ == "__main__": main()
256
0
from __future__ import annotations def __a ( __lowerCAmelCase ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
308
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 _lowerCamelCase : List[Any] = logging.get_logger(__name__) _lowerCamelCase : Any = { """facebook/levit-128S""": """https://huggingface.co/facebook/levit-128S/resolve/main/config.json""", # See all LeViT models at https://huggingface.co/models?filter=levit } class lowercase ( SCREAMING_SNAKE_CASE_): '''simple docstring''' UpperCAmelCase : Dict = 'levit' def __init__( self : List[str] , snake_case : int=224 , snake_case : Dict=3 , snake_case : List[str]=3 , snake_case : Optional[int]=2 , snake_case : int=1 , snake_case : List[str]=16 , snake_case : Optional[Any]=[128, 256, 384] , snake_case : Optional[int]=[4, 8, 12] , snake_case : Optional[int]=[4, 4, 4] , snake_case : Union[str, Any]=[16, 16, 16] , snake_case : List[str]=0 , snake_case : Any=[2, 2, 2] , snake_case : Any=[2, 2, 2] , snake_case : int=0.02 , **snake_case : Dict , ): '''simple docstring''' super().__init__(**snake_case ) SCREAMING_SNAKE_CASE : Tuple = image_size SCREAMING_SNAKE_CASE : List[Any] = num_channels SCREAMING_SNAKE_CASE : Dict = kernel_size SCREAMING_SNAKE_CASE : Optional[Any] = stride SCREAMING_SNAKE_CASE : int = padding SCREAMING_SNAKE_CASE : Optional[int] = hidden_sizes SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = depths SCREAMING_SNAKE_CASE : Any = key_dim SCREAMING_SNAKE_CASE : List[Any] = drop_path_rate SCREAMING_SNAKE_CASE : Optional[Any] = patch_size SCREAMING_SNAKE_CASE : Any = attention_ratio SCREAMING_SNAKE_CASE : Dict = mlp_ratio SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : Tuple = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class lowercase ( SCREAMING_SNAKE_CASE_): '''simple docstring''' UpperCAmelCase : List[str] = version.parse('1.11') @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return 1E-4
308
1
'''simple docstring''' def UpperCAmelCase_ ( A , A ): '''simple docstring''' return x if y == 0 else greatest_common_divisor(A , x % y ) def UpperCAmelCase_ ( A , A ): '''simple docstring''' return (x * y) // greatest_common_divisor(A , A ) def UpperCAmelCase_ ( A = 2_0 ): '''simple docstring''' _a : List[Any] = 1 for i in range(1 , n + 1 ): _a : Union[str, Any] = lcm(A , A ) return g if __name__ == "__main__": print(f'''{solution() = }''')
120
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { "google/vivit-b-16x2-kinetics400": ( "https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class a ( snake_case__ ): '''simple docstring''' __lowerCAmelCase : str = """vivit""" def __init__( self , lowerCamelCase_=2_2_4 , lowerCamelCase_=3_2 , lowerCamelCase_=[2, 1_6, 1_6] , lowerCamelCase_=3 , lowerCamelCase_=7_6_8 , lowerCamelCase_=1_2 , lowerCamelCase_=1_2 , lowerCamelCase_=3_0_7_2 , lowerCamelCase_="gelu_fast" , lowerCamelCase_=0.0 , lowerCamelCase_=0.0 , lowerCamelCase_=0.02 , lowerCamelCase_=1e-06 , lowerCamelCase_=True , **lowerCamelCase_ , ) -> int: _a : Tuple = hidden_size _a : Dict = num_hidden_layers _a : List[str] = num_attention_heads _a : int = intermediate_size _a : Optional[int] = hidden_act _a : Dict = hidden_dropout_prob _a : List[str] = attention_probs_dropout_prob _a : List[str] = initializer_range _a : List[str] = layer_norm_eps _a : Any = image_size _a : Optional[Any] = num_frames _a : Dict = tubelet_size _a : Union[str, Any] = num_channels _a : Optional[int] = qkv_bias super().__init__(**lowerCamelCase_ )
120
1
'''simple docstring''' class __UpperCamelCase : def __init__( self :List[Any] ,_UpperCamelCase :Optional[Any] ,_UpperCamelCase :List[str] ): snake_case_ : int = name snake_case_ : Tuple = val def __str__( self :Optional[int] ): return F'''{self.__class__.__name__}({self.name}, {self.val})''' def __lt__( self :int ,_UpperCamelCase :List[Any] ): return self.val < other.val class __UpperCamelCase : def __init__( self :List[str] ,_UpperCamelCase :Any ): snake_case_ : Union[str, Any] = {} snake_case_ : Union[str, Any] = {} snake_case_ : List[str] = self.build_heap(_UpperCamelCase ) def __getitem__( self :Dict ,_UpperCamelCase :Dict ): return self.get_value(_UpperCamelCase ) def a__ ( self :Dict ,_UpperCamelCase :str ): return (idx - 1) // 2 def a__ ( self :List[Any] ,_UpperCamelCase :Dict ): return idx * 2 + 1 def a__ ( self :List[str] ,_UpperCamelCase :Tuple ): return idx * 2 + 2 def a__ ( self :Union[str, Any] ,_UpperCamelCase :Any ): return self.heap_dict[key] def a__ ( self :Optional[Any] ,_UpperCamelCase :Tuple ): snake_case_ : Tuple = len(_UpperCamelCase ) - 1 snake_case_ : int = self.get_parent_idx(_UpperCamelCase ) for idx, i in enumerate(_UpperCamelCase ): snake_case_ : Optional[int] = idx snake_case_ : List[Any] = i.val for i in range(_UpperCamelCase ,-1 ,-1 ): self.sift_down(_UpperCamelCase ,_UpperCamelCase ) return array def a__ ( self :List[Any] ,_UpperCamelCase :Tuple ,_UpperCamelCase :Optional[int] ): while True: snake_case_ : Union[str, Any] = self.get_left_child_idx(_UpperCamelCase ) # noqa: E741 snake_case_ : List[str] = self.get_right_child_idx(_UpperCamelCase ) snake_case_ : Tuple = idx if l < len(_UpperCamelCase ) and array[l] < array[idx]: snake_case_ : List[Any] = l if r < len(_UpperCamelCase ) and array[r] < array[smallest]: snake_case_ : str = r if smallest != idx: snake_case_ : List[Any] = array[smallest], array[idx] ( snake_case_ ) : Optional[int] = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) snake_case_ : str = smallest else: break def a__ ( self :Tuple ,_UpperCamelCase :Any ): snake_case_ : List[str] = self.get_parent_idx(_UpperCamelCase ) while p >= 0 and self.heap[p] > self.heap[idx]: snake_case_ : Union[str, Any] = self.heap[idx], self.heap[p] snake_case_ : Any = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) snake_case_ : Dict = p snake_case_ : int = self.get_parent_idx(_UpperCamelCase ) def a__ ( self :Optional[int] ): return self.heap[0] def a__ ( self :int ): snake_case_ : Tuple = self.heap[-1], self.heap[0] snake_case_ : Union[str, Any] = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) snake_case_ : List[Any] = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 ,self.heap ) return x def a__ ( self :int ,_UpperCamelCase :List[Any] ): self.heap.append(_UpperCamelCase ) snake_case_ : List[str] = len(self.heap ) - 1 snake_case_ : List[Any] = node.val self.sift_up(len(self.heap ) - 1 ) def a__ ( self :Union[str, Any] ): return len(self.heap ) == 0 def a__ ( self :List[str] ,_UpperCamelCase :Optional[int] ,_UpperCamelCase :str ): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" snake_case_ : Dict = new_value snake_case_ : List[Any] = new_value self.sift_up(self.idx_of_element[node] ) __A : Optional[int] = Node('R', -1) __A : int = Node('B', 6) __A : List[Any] = Node('A', 3) __A : Tuple = Node('X', 1) __A : int = Node('E', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __A : Any = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('Min Heap - before decrease key') for i in my_min_heap.heap: print(i) print('Min Heap - After decrease key of node [B -> -17]') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
710
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A : str = logging.get_logger(__name__) __A : Dict = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class __UpperCamelCase ( lowercase__ ): lowercase : Tuple = 'pix2struct_text_model' lowercase : int = ['past_key_values'] lowercase : int = { 'hidden_size': 'hidden_size', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self :int ,_UpperCamelCase :List[str]=5_0_2_4_4 ,_UpperCamelCase :Optional[Any]=7_6_8 ,_UpperCamelCase :Dict=6_4 ,_UpperCamelCase :Dict=2_0_4_8 ,_UpperCamelCase :Optional[int]=1_2 ,_UpperCamelCase :Union[str, Any]=1_2 ,_UpperCamelCase :List[str]=3_2 ,_UpperCamelCase :Union[str, Any]=1_2_8 ,_UpperCamelCase :Tuple=0.1 ,_UpperCamelCase :List[str]=1E-6 ,_UpperCamelCase :List[Any]=1.0 ,_UpperCamelCase :Optional[int]="gelu_new" ,_UpperCamelCase :Dict=0 ,_UpperCamelCase :List[str]=False ,_UpperCamelCase :Optional[int]=0 ,_UpperCamelCase :Dict=1 ,_UpperCamelCase :List[Any]=False ,_UpperCamelCase :Tuple=True ,**_UpperCamelCase :List[Any] ,): snake_case_ : List[str] = vocab_size snake_case_ : Any = hidden_size snake_case_ : Any = d_kv snake_case_ : List[Any] = d_ff snake_case_ : Union[str, Any] = num_layers snake_case_ : Union[str, Any] = num_heads snake_case_ : str = relative_attention_num_buckets snake_case_ : Optional[int] = relative_attention_max_distance snake_case_ : Tuple = dropout_rate snake_case_ : Tuple = layer_norm_epsilon snake_case_ : Any = initializer_factor snake_case_ : List[Any] = use_cache snake_case_ : Optional[int] = eos_token_id snake_case_ : List[Any] = decoder_start_token_id # for backwards compatibility snake_case_ : List[str] = dense_act_fn super().__init__( pad_token_id=_UpperCamelCase ,eos_token_id=_UpperCamelCase ,decoder_start_token_id=_UpperCamelCase ,tie_word_embeddings=_UpperCamelCase ,is_decoder=_UpperCamelCase ,**_UpperCamelCase ,) @classmethod def a__ ( cls :Optional[int] ,_UpperCamelCase :Union[str, os.PathLike] ,**_UpperCamelCase :Optional[int] ): cls._set_token_in_kwargs(_UpperCamelCase ) snake_case_ , snake_case_ : Optional[Any] = cls.get_config_dict(_UpperCamelCase ,**_UpperCamelCase ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": snake_case_ : Optional[int] = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCamelCase ,**_UpperCamelCase ) class __UpperCamelCase ( lowercase__ ): lowercase : Dict = 'pix2struct_vision_model' def __init__( self :List[str] ,_UpperCamelCase :Any=7_6_8 ,_UpperCamelCase :List[str]=7_6_8 ,_UpperCamelCase :List[Any]=2_0_4_8 ,_UpperCamelCase :Union[str, Any]=6_4 ,_UpperCamelCase :int=1_2 ,_UpperCamelCase :int=1_2 ,_UpperCamelCase :Any="gelu_new" ,_UpperCamelCase :Optional[int]=1E-6 ,_UpperCamelCase :List[Any]=0.0 ,_UpperCamelCase :Union[str, Any]=0.0 ,_UpperCamelCase :int=1E-1_0 ,_UpperCamelCase :str=1.0 ,_UpperCamelCase :Optional[int]=4_0_9_6 ,_UpperCamelCase :str=3_2 ,_UpperCamelCase :Union[str, Any]=1_2_8 ,**_UpperCamelCase :Union[str, Any] ,): super().__init__(**_UpperCamelCase ) snake_case_ : str = hidden_size snake_case_ : Tuple = patch_embed_hidden_size snake_case_ : Optional[int] = d_ff snake_case_ : Dict = dropout_rate snake_case_ : Optional[int] = num_hidden_layers snake_case_ : Dict = num_attention_heads snake_case_ : Union[str, Any] = initializer_range snake_case_ : Optional[Any] = initializer_factor snake_case_ : List[str] = attention_dropout snake_case_ : List[str] = layer_norm_eps snake_case_ : List[str] = dense_act_fn snake_case_ : int = seq_len snake_case_ : str = relative_attention_num_buckets snake_case_ : Tuple = relative_attention_max_distance snake_case_ : List[str] = d_kv @classmethod def a__ ( cls :Optional[Any] ,_UpperCamelCase :Union[str, os.PathLike] ,**_UpperCamelCase :List[str] ): cls._set_token_in_kwargs(_UpperCamelCase ) snake_case_ , snake_case_ : Tuple = cls.get_config_dict(_UpperCamelCase ,**_UpperCamelCase ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": snake_case_ : Dict = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCamelCase ,**_UpperCamelCase ) class __UpperCamelCase ( lowercase__ ): lowercase : Union[str, Any] = 'pix2struct' lowercase : int = True def __init__( self :int ,_UpperCamelCase :Tuple=None ,_UpperCamelCase :Optional[int]=None ,_UpperCamelCase :Dict=1.0 ,_UpperCamelCase :Optional[int]=0.02 ,_UpperCamelCase :Tuple=False ,_UpperCamelCase :List[str]=False ,_UpperCamelCase :Dict=True ,**_UpperCamelCase :Union[str, Any] ,): super().__init__(tie_word_embeddings=_UpperCamelCase ,is_encoder_decoder=_UpperCamelCase ,**_UpperCamelCase ) if text_config is None: snake_case_ : Optional[int] = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: snake_case_ : List[str] = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) snake_case_ : Optional[int] = PixaStructTextConfig(**_UpperCamelCase ) snake_case_ : List[str] = PixaStructVisionConfig(**_UpperCamelCase ) snake_case_ : Any = self.text_config.decoder_start_token_id snake_case_ : List[Any] = self.text_config.pad_token_id snake_case_ : Optional[int] = self.text_config.eos_token_id snake_case_ : Optional[int] = initializer_factor snake_case_ : List[str] = initializer_range snake_case_ : Union[str, Any] = self.initializer_range snake_case_ : str = self.initializer_range snake_case_ : Dict = is_vqa @classmethod def a__ ( cls :Any ,_UpperCamelCase :PixaStructTextConfig ,_UpperCamelCase :PixaStructVisionConfig ,**_UpperCamelCase :Any ): return cls(text_config=text_config.to_dict() ,vision_config=vision_config.to_dict() ,**_UpperCamelCase ) def a__ ( self :Optional[int] ): snake_case_ : int = copy.deepcopy(self.__dict__ ) snake_case_ : str = self.text_config.to_dict() snake_case_ : Tuple = self.vision_config.to_dict() snake_case_ : Any = self.__class__.model_type return output
267
0
'''simple docstring''' import os def lowercase ( ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = os.path.dirname(os.path.realpath(__magic_name__ ) ) UpperCAmelCase : Any = os.path.join(__magic_name__ , "triangle.txt" ) with open(__magic_name__ ) as f: UpperCAmelCase : str = f.readlines() UpperCAmelCase : Optional[int] = [] for line in triangle: UpperCAmelCase : List[str] = [] for number in line.strip().split(" " ): numbers_from_line.append(int(__magic_name__ ) ) a.append(__magic_name__ ) for i in range(1 , len(__magic_name__ ) ): for j in range(len(a[i] ) ): UpperCAmelCase : Union[str, Any] = a[i - 1][j] if j != len(a[i - 1] ) else 0 UpperCAmelCase : List[str] = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(__magic_name__ , __magic_name__ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
679
'''simple docstring''' import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def lowercase ( __magic_name__="" ): '''simple docstring''' UpperCAmelCase : Dict = tempfile.mkdtemp() return os.path.join(__magic_name__ , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def A_ ( self ): '''simple docstring''' UpperCAmelCase : Any = torch.rand(1_2 , dtype=torch.floataa ) - 0.5 UpperCAmelCase : int = AgentAudio(snake_case ) UpperCAmelCase : str = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(snake_case , agent_type.to_raw() , atol=1e-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(snake_case ) ) # Ensure that the file contains the same value as the original tensor UpperCAmelCase , UpperCAmelCase : str = sf.read(snake_case ) self.assertTrue(torch.allclose(snake_case , torch.tensor(snake_case ) , atol=1e-4 ) ) def A_ ( self ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = torch.rand(1_2 , dtype=torch.floataa ) - 0.5 UpperCAmelCase : Any = get_new_path(suffix=".wav" ) sf.write(snake_case , snake_case , 1_6_0_0_0 ) UpperCAmelCase : Optional[Any] = AgentAudio(snake_case ) self.assertTrue(torch.allclose(snake_case , agent_type.to_raw() , atol=1e-4 ) ) self.assertEqual(agent_type.to_string() , snake_case ) @require_vision @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def A_ ( self ): '''simple docstring''' UpperCAmelCase : Optional[Any] = torch.randint(0 , 2_5_6 , (6_4, 6_4, 3) ) UpperCAmelCase : Tuple = AgentImage(snake_case ) UpperCAmelCase : Tuple = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(snake_case , agent_type._tensor , atol=1e-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(snake_case ) ) def A_ ( self ): '''simple docstring''' UpperCAmelCase : Optional[Any] = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" UpperCAmelCase : Any = Image.open(snake_case ) UpperCAmelCase : List[str] = AgentImage(snake_case ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(snake_case ) ) def A_ ( self ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" UpperCAmelCase : Dict = Image.open(snake_case ) UpperCAmelCase : int = AgentImage(snake_case ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(snake_case ) ) class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def A_ ( self ): '''simple docstring''' UpperCAmelCase : Any = "Hey!" UpperCAmelCase : Tuple = AgentText(snake_case ) self.assertEqual(snake_case , agent_type.to_string() ) self.assertEqual(snake_case , agent_type.to_raw() ) self.assertEqual(snake_case , snake_case )
679
1
"""simple docstring""" import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig __A : Optional[int] = logging.get_logger(__name__) __A : Any = "T5Config" def lowercase ( UpperCamelCase : jnp.array , UpperCamelCase : int , UpperCamelCase : int ): """simple docstring""" A__ : Dict =jnp.zeros_like(UpperCamelCase ) A__ : List[str] =shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) A__ : Union[str, Any] =shifted_input_ids.at[:, 0].set(UpperCamelCase ) A__ : Optional[Any] =jnp.where(shifted_input_ids == -100 , UpperCamelCase , UpperCamelCase ) return shifted_input_ids class __lowerCAmelCase ( _UpperCamelCase): '''simple docstring''' __magic_name__ : List[Any] = """mt5""" __magic_name__ : Optional[Any] = MTaConfig class __lowerCAmelCase ( _UpperCamelCase): '''simple docstring''' __magic_name__ : Dict = """mt5""" __magic_name__ : List[Any] = MTaConfig class __lowerCAmelCase ( _UpperCamelCase): '''simple docstring''' __magic_name__ : Tuple = """mt5""" __magic_name__ : Dict = MTaConfig
595
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A : Dict = { "configuration_rembert": ["REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RemBertConfig", "RemBertOnnxConfig"] } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : str = ["RemBertTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ["RemBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ "REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RemBertForCausalLM", "RemBertForMaskedLM", "RemBertForMultipleChoice", "RemBertForQuestionAnswering", "RemBertForSequenceClassification", "RemBertForTokenClassification", "RemBertLayer", "RemBertModel", "RemBertPreTrainedModel", "load_tf_weights_in_rembert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ "TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRemBertForCausalLM", "TFRemBertForMaskedLM", "TFRemBertForMultipleChoice", "TFRemBertForQuestionAnswering", "TFRemBertForSequenceClassification", "TFRemBertForTokenClassification", "TFRemBertLayer", "TFRemBertModel", "TFRemBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert import RemBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert_fast import RemBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) else: import sys __A : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
595
1
"""simple docstring""" 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.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 6_50, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """pytorch""", """script""": """run_ddp.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 6_00, """eval_accuracy""": 0.7, """eval_loss""": 0.6}, }, { """framework""": """tensorflow""", """script""": """run_tf_dist.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.p3.16xlarge""", """results""": {"""train_runtime""": 6_00, """eval_accuracy""": 0.6, """eval_loss""": 0.7}, }, ] ) class __snake_case ( unittest.TestCase ): """simple docstring""" def UpperCamelCase__( self ): '''simple docstring''' 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 UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' __A : Dict = F"""{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}""" # distributed data settings __A : List[Any] = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # 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=__lowerCamelCase , instance_count=__lowerCamelCase , instance_type=self.instance_type , debugger_hook_config=__lowerCamelCase , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=__lowerCamelCase , py_version='''py36''' , ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' TrainingJobAnalytics(__lowerCamelCase ).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(2,)] ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' __A : Optional[Any] = self.create_estimator(__lowerCamelCase ) # run training estimator.fit() # result dataframe __A : Union[str, Any] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __A : List[str] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __A : Any = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __A : List[Any] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_9999 ) ) # 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 )
177
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase__( self ): '''simple docstring''' __A : Any = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__lowerCamelCase ).to(__lowerCamelCase ) __A : Optional[Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) __A : Optional[int] = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids __A : str = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids __A : Any = model(input_ids.to(__lowerCamelCase ) , labels=labels.to(__lowerCamelCase ) ).loss __A : Tuple = -(labels.shape[-1] * loss.item()) __A : int = -8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
177
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : List[str] = {"configuration_plbart": ["PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "PLBartConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = ["PLBartTokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ "PLBART_PRETRAINED_MODEL_ARCHIVE_LIST", "PLBartForCausalLM", "PLBartForConditionalGeneration", "PLBartForSequenceClassification", "PLBartModel", "PLBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
707
"""simple docstring""" from scipy.stats import spearmanr import datasets __A : Optional[int] = '\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n' __A : List[Any] = '\nArgs:\n predictions (`List[float]`): Predicted labels, as returned by a model.\n references (`List[float]`): Ground truth labels.\n return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n only the spearmanr score. Defaults to `False`.\nReturns:\n spearmanr (`float`): Spearman correlation coefficient.\n p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n Example 1:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n >>> print(results)\n {\'spearmanr\': -0.7}\n\n Example 2:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n ... predictions=[10, 9, 2.5, 6, 4],\n ... return_pvalue=True)\n >>> print(results[\'spearmanr\'])\n -0.7\n >>> print(round(results[\'spearmanr_pvalue\'], 2))\n 0.19\n' __A : Optional[int] = R'\\n@book{kokoska2000crc,\n title={CRC standard probability and statistics tables and formulae},\n author={Kokoska, Stephen and Zwillinger, Daniel},\n year={2000},\n publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\n journal = {Nature Methods},\n year = {2020},\n volume = {17},\n pages = {261--272},\n adsurl = {https://rdcu.be/b08Wh},\n doi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): """simple docstring""" def snake_case ( self : List[str] ): 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.spearmanr.html"] , ) def snake_case ( self : Optional[int] , lowercase__ : str , lowercase__ : Any , lowercase__ : int=False ): __lowercase : Optional[int] = spearmanr(lowercase__ , lowercase__ ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
281
0
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __UpperCamelCase : Tuple = 16 __UpperCamelCase : List[str] = 32 def _UpperCAmelCase ( UpperCAmelCase : Accelerator , UpperCAmelCase : int = 16 ): """simple docstring""" __lowerCamelCase : List[str] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) __lowerCamelCase : Tuple = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCAmelCase : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) __lowerCamelCase : str = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=UpperCAmelCase , max_length=UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __lowerCamelCase : Dict = datasets.map( UpperCAmelCase , batched=UpperCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __lowerCamelCase : Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCAmelCase : Optional[int] ): # On TPU it's best to pad everything to the same length or training will be very slow. __lowerCamelCase : Optional[Any] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __lowerCamelCase : int = 16 elif accelerator.mixed_precision != "no": __lowerCamelCase : List[str] = 8 else: __lowerCamelCase : Any = None return tokenizer.pad( UpperCAmelCase , padding="""longest""" , max_length=UpperCAmelCase , pad_to_multiple_of=UpperCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. __lowerCamelCase : Optional[Any] = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCAmelCase , collate_fn=UpperCAmelCase , batch_size=UpperCAmelCase , drop_last=UpperCAmelCase ) __lowerCamelCase : Optional[int] = DataLoader( tokenized_datasets["""validation"""] , shuffle=UpperCAmelCase , collate_fn=UpperCAmelCase , batch_size=UpperCAmelCase , drop_last=(accelerator.mixed_precision == """fp8""") , ) return train_dataloader, eval_dataloader def _UpperCAmelCase ( UpperCAmelCase : Tuple , UpperCAmelCase : Tuple ): """simple docstring""" __lowerCamelCase : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __lowerCamelCase : List[str] = config["""lr"""] __lowerCamelCase : int = int(config["""num_epochs"""] ) __lowerCamelCase : Optional[Any] = int(config["""seed"""] ) __lowerCamelCase : Optional[int] = int(config["""batch_size"""] ) __lowerCamelCase : List[str] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation __lowerCamelCase : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __lowerCamelCase : int = batch_size // MAX_GPU_BATCH_SIZE __lowerCamelCase : List[str] = MAX_GPU_BATCH_SIZE set_seed(UpperCAmelCase ) __lowerCamelCase , __lowerCamelCase : Union[str, Any] = get_dataloaders(UpperCAmelCase , UpperCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __lowerCamelCase : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __lowerCamelCase : str = model.to(accelerator.device ) # Instantiate optimizer __lowerCamelCase : Tuple = AdamW(params=model.parameters() , lr=UpperCAmelCase ) # Instantiate scheduler __lowerCamelCase : int = get_linear_schedule_with_warmup( optimizer=UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(UpperCAmelCase ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = accelerator.prepare( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # Now we train the model for epoch in range(UpperCAmelCase ): model.train() for step, batch in enumerate(UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __lowerCamelCase : int = model(**UpperCAmelCase ) __lowerCamelCase : Optional[int] = outputs.loss __lowerCamelCase : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(UpperCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __lowerCamelCase : Dict = model(**UpperCAmelCase ) __lowerCamelCase : List[str] = outputs.logits.argmax(dim=-1 ) __lowerCamelCase , __lowerCamelCase : str = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=UpperCAmelCase , references=UpperCAmelCase , ) __lowerCamelCase : List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , UpperCAmelCase ) def _UpperCAmelCase ( ): """simple docstring""" __lowerCamelCase : List[Any] = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=UpperCAmelCase , default=UpperCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) __lowerCamelCase : Dict = parser.parse_args() __lowerCamelCase : Any = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(UpperCAmelCase , UpperCAmelCase ) if __name__ == "__main__": main()
519
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency __UpperCamelCase : Tuple = { 'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36, 'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29, 'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10, 'Z': 0.07, } __UpperCamelCase : Dict = 'ETAOINSHRDLCUMWFGYPBVKJXQZ' __UpperCamelCase : List[Any] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def _UpperCAmelCase ( UpperCAmelCase : str ): """simple docstring""" __lowerCamelCase : str = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def _UpperCAmelCase ( UpperCAmelCase : tuple ): """simple docstring""" return x[0] def _UpperCAmelCase ( UpperCAmelCase : str ): """simple docstring""" __lowerCamelCase : Tuple = get_letter_count(UpperCAmelCase ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(UpperCAmelCase ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=UpperCAmelCase ) __lowerCamelCase : Any = """""".join(freq_to_letter[freq] ) __lowerCamelCase : Optional[Any] = list(freq_to_letter_str.items() ) freq_pairs.sort(key=UpperCAmelCase , reverse=UpperCAmelCase ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(UpperCAmelCase ) def _UpperCAmelCase ( UpperCAmelCase : str ): """simple docstring""" __lowerCamelCase : List[str] = get_frequency_order(UpperCAmelCase ) __lowerCamelCase : Any = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
519
1
'''simple docstring''' def _A ( A__ = 10 ): """simple docstring""" if not isinstance(A__ , A__ ) or n < 0: raise ValueError('''Invalid input''' ) __lowercase = 10**n __lowercase = 28433 * (pow(2 , 7830457 , A__ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f'{solution(10) = }')
624
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase__ = {'''configuration_vit_mae''': ['''VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTMAEConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ViTMAEForPreTraining''', '''ViTMAELayer''', '''ViTMAEModel''', '''ViTMAEPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TFViTMAEForPreTraining''', '''TFViTMAEModel''', '''TFViTMAEPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
624
1
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def lowerCamelCase( a__ ,a__ ,a__=1e-12): _SCREAMING_SNAKE_CASE =jnp.divide(emb_a.T ,jnp.clip(jnp.linalg.norm(a__ ,axis=1) ,a_min=a__)).T _SCREAMING_SNAKE_CASE =jnp.divide(emb_a.T ,jnp.clip(jnp.linalg.norm(a__ ,axis=1) ,a_min=a__)).T return jnp.matmul(a__ ,norm_emb_a.T) class A__ ( nn.Module ): UpperCAmelCase = 42 UpperCAmelCase = jnp.floataa def __UpperCamelCase ( self : List[str] ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =FlaxCLIPVisionModule(self.config.vision_config ) _SCREAMING_SNAKE_CASE =nn.Dense(self.config.projection_dim , use_bias=_a , dtype=self.dtype ) _SCREAMING_SNAKE_CASE =self.param('''concept_embeds''' , jax.nn.initializers.ones , (17, self.config.projection_dim) ) _SCREAMING_SNAKE_CASE =self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim) ) _SCREAMING_SNAKE_CASE =self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (17,) ) _SCREAMING_SNAKE_CASE =self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,) ) def __call__( self : Optional[Any] , _a : Dict ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =self.vision_model(_a )[1] _SCREAMING_SNAKE_CASE =self.visual_projection(_a ) _SCREAMING_SNAKE_CASE =jax_cosine_distance(_a , self.special_care_embeds ) _SCREAMING_SNAKE_CASE =jax_cosine_distance(_a , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs _SCREAMING_SNAKE_CASE =0.0 _SCREAMING_SNAKE_CASE =special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment _SCREAMING_SNAKE_CASE =jnp.round(_a , 3 ) _SCREAMING_SNAKE_CASE =jnp.any(special_scores > 0 , axis=1 , keepdims=_a ) # Use a lower threshold if an image has any special care concept _SCREAMING_SNAKE_CASE =is_special_care * 0.01 _SCREAMING_SNAKE_CASE =cos_dist - self.concept_embeds_weights[None, :] + special_adjustment _SCREAMING_SNAKE_CASE =jnp.round(_a , 3 ) _SCREAMING_SNAKE_CASE =jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class A__ ( UpperCamelCase__ ): UpperCAmelCase = CLIPConfig UpperCAmelCase = "clip_input" UpperCAmelCase = FlaxStableDiffusionSafetyCheckerModule def __init__( self : Tuple , _a : CLIPConfig , _a : Optional[Tuple] = None , _a : int = 0 , _a : jnp.dtype = jnp.floataa , _a : bool = True , **_a : Any , ) -> str: """simple docstring""" if input_shape is None: _SCREAMING_SNAKE_CASE =(1, 224, 224, 3) _SCREAMING_SNAKE_CASE =self.module_class(config=_a , dtype=_a , **_a ) super().__init__(_a , _a , input_shape=_a , seed=_a , dtype=_a , _do_init=_do_init ) def __UpperCamelCase ( self : List[Any] , _a : jax.random.KeyArray , _a : Tuple , _a : FrozenDict = None ) -> FrozenDict: """simple docstring""" _SCREAMING_SNAKE_CASE =jax.random.normal(_a , _a ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =jax.random.split(_a ) _SCREAMING_SNAKE_CASE ={'''params''': params_rng, '''dropout''': dropout_rng} _SCREAMING_SNAKE_CASE =self.module.init(_a , _a )['''params'''] return random_params def __call__( self : str , _a : Union[str, Any] , _a : dict = None , ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =jnp.transpose(_a , (0, 2, 3, 1) ) return self.module.apply( {'''params''': params or self.params} , jnp.array(_a , dtype=jnp.floataa ) , rngs={} , )
691
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class A__ ( unittest.TestCase ): def __UpperCamelCase ( self : int ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =tempfile.mkdtemp() _SCREAMING_SNAKE_CASE =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] _SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _SCREAMING_SNAKE_CASE ={ '''do_resize''': True, '''size''': {'''height''': 224, '''width''': 224}, '''do_center_crop''': True, '''crop_size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], '''image_std''': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], '''do_convert_rgb''': True, } _SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_a , _a ) def __UpperCamelCase ( self : Optional[int] , **_a : str ) -> List[str]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def __UpperCamelCase ( self : List[Any] , **_a : Any ) -> Dict: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def __UpperCamelCase ( self : int , **_a : Optional[Any] ) -> Any: """simple docstring""" return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **_a ) def __UpperCamelCase ( self : str ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __UpperCamelCase ( self : int ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =[np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _SCREAMING_SNAKE_CASE =[Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def __UpperCamelCase ( self : Any ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =self.get_tokenizer() _SCREAMING_SNAKE_CASE =self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE =self.get_image_processor() _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) processor_slow.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_a ) _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) processor_fast.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _a ) self.assertIsInstance(processor_fast.tokenizer , _a ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _a ) self.assertIsInstance(processor_fast.image_processor , _a ) def __UpperCamelCase ( self : str ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE =self.get_tokenizer(cls_token='''(CLS)''' , sep_token='''(SEP)''' ) _SCREAMING_SNAKE_CASE =self.get_image_processor(do_normalize=_a ) _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='''(CLS)''' , sep_token='''(SEP)''' , do_normalize=_a ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def __UpperCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =self.get_image_processor() _SCREAMING_SNAKE_CASE =self.get_tokenizer() _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _SCREAMING_SNAKE_CASE =self.prepare_image_inputs() _SCREAMING_SNAKE_CASE =image_processor(_a , return_tensors='''np''' ) _SCREAMING_SNAKE_CASE =processor(images=_a , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __UpperCamelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =self.get_image_processor() _SCREAMING_SNAKE_CASE =self.get_tokenizer() _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _SCREAMING_SNAKE_CASE ='''Alexandra,T-shirt的价格是15便士。''' _SCREAMING_SNAKE_CASE =processor(text=_a ) _SCREAMING_SNAKE_CASE =tokenizer(_a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =self.get_image_processor() _SCREAMING_SNAKE_CASE =self.get_tokenizer() _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _SCREAMING_SNAKE_CASE ='''Alexandra,T-shirt的价格是15便士。''' _SCREAMING_SNAKE_CASE =self.prepare_image_inputs() _SCREAMING_SNAKE_CASE =processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(_a ): processor() def __UpperCamelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =self.get_image_processor() _SCREAMING_SNAKE_CASE =self.get_tokenizer() _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _SCREAMING_SNAKE_CASE =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _SCREAMING_SNAKE_CASE =processor.batch_decode(_a ) _SCREAMING_SNAKE_CASE =tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =self.get_image_processor() _SCREAMING_SNAKE_CASE =self.get_tokenizer() _SCREAMING_SNAKE_CASE =ChineseCLIPProcessor(tokenizer=_a , image_processor=_a ) _SCREAMING_SNAKE_CASE ='''Alexandra,T-shirt的价格是15便士。''' _SCREAMING_SNAKE_CASE =self.prepare_image_inputs() _SCREAMING_SNAKE_CASE =processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
691
1
'''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 SCREAMING_SNAKE_CASE__ = False class a_ ( unittest.TestCase ): pass @slow @require_torch_gpu class a_ ( unittest.TestCase ): def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = VersatileDiffusionImageVariationPipeline.from_pretrained("""shi-labs/versatile-diffusion""" ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) UpperCamelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg""" ) UpperCamelCase = torch.manual_seed(0 ) UpperCamelCase = pipe( image=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" , ).images UpperCamelCase = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) UpperCamelCase = np.array([0.0_4_4_1, 0.0_4_6_9, 0.0_5_0_7, 0.0_5_7_5, 0.0_6_3_2, 0.0_6_5_0, 0.0_8_6_5, 0.0_9_0_9, 0.0_9_4_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
709
'''simple docstring''' SCREAMING_SNAKE_CASE__ = 8.31_44_62 # Unit - J mol-1 K-1 def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
35
0
class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" snake_case_ = name snake_case_ = val def __str__( self ): """simple docstring""" return f"""{self.__class__.__name__}({self.name}, {self.val})""" def __lt__( self , __UpperCamelCase ): """simple docstring""" return self.val < other.val class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , __UpperCamelCase ): """simple docstring""" snake_case_ = {} snake_case_ = {} snake_case_ = self.build_heap(__UpperCamelCase ) def __getitem__( self , __UpperCamelCase ): """simple docstring""" return self.get_value(__UpperCamelCase ) def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" return (idx - 1) // 2 def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" return idx * 2 + 1 def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" return idx * 2 + 2 def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" return self.heap_dict[key] def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" snake_case_ = len(__UpperCamelCase ) - 1 snake_case_ = self.get_parent_idx(__UpperCamelCase ) for idx, i in enumerate(__UpperCamelCase ): snake_case_ = idx snake_case_ = i.val for i in range(__UpperCamelCase , -1 , -1 ): self.sift_down(__UpperCamelCase , __UpperCamelCase ) return array def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" while True: snake_case_ = self.get_left_child_idx(__UpperCamelCase ) # noqa: E741 snake_case_ = self.get_right_child_idx(__UpperCamelCase ) snake_case_ = idx if l < len(__UpperCamelCase ) and array[l] < array[idx]: snake_case_ = l if r < len(__UpperCamelCase ) and array[r] < array[smallest]: snake_case_ = r if smallest != idx: snake_case_ , snake_case_ = array[smallest], array[idx] ( ( snake_case_ ) , ( snake_case_ ) , ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) snake_case_ = smallest else: break def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" snake_case_ = self.get_parent_idx(__UpperCamelCase ) while p >= 0 and self.heap[p] > self.heap[idx]: snake_case_ , snake_case_ = self.heap[idx], self.heap[p] snake_case_ , snake_case_ = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) snake_case_ = p snake_case_ = self.get_parent_idx(__UpperCamelCase ) def __lowerCAmelCase ( self ): """simple docstring""" return self.heap[0] def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ , snake_case_ = self.heap[-1], self.heap[0] snake_case_ , snake_case_ = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) snake_case_ = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" self.heap.append(__UpperCamelCase ) snake_case_ = len(self.heap ) - 1 snake_case_ = node.val self.sift_up(len(self.heap ) - 1 ) def __lowerCAmelCase ( self ): """simple docstring""" return len(self.heap ) == 0 def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" snake_case_ = new_value snake_case_ = new_value self.sift_up(self.idx_of_element[node] ) A = Node('R', -1) A = Node('B', 6) A = Node('A', 3) A = Node('X', 1) A = Node('E', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array A = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('Min Heap - before decrease key') for i in my_min_heap.heap: print(i) print('Min Heap - After decrease key of node [B -> -17]') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
187
import functools def a(lowercase__ , lowercase__ ): '''simple docstring''' # Validation if not isinstance(lowercase__ , lowercase__ ) or not all(isinstance(lowercase__ , lowercase__ ) for day in days ): raise ValueError('The parameter days should be a list of integers' ) if len(lowercase__ ) != 3 or not all(isinstance(lowercase__ , lowercase__ ) for cost in costs ): raise ValueError('The parameter costs should be a list of three integers' ) if len(lowercase__ ) == 0: return 0 if min(lowercase__ ) <= 0: raise ValueError('All days elements should be greater than 0' ) if max(lowercase__ ) >= 366: raise ValueError('All days elements should be less than 366' ) snake_case_ = set(lowercase__ ) @functools.cache def dynamic_programming(lowercase__ ) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 30 ) , ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
187
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """s-JoL/Open-Llama-V1""": """https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json""", } class lowercase__ ( _UpperCAmelCase ): A__ : Tuple ="""open-llama""" def __init__( self : Tuple , UpperCAmelCase_ : str=100000 , UpperCAmelCase_ : Dict=4096 , UpperCAmelCase_ : Optional[int]=11008 , UpperCAmelCase_ : Optional[int]=32 , UpperCAmelCase_ : Tuple=32 , UpperCAmelCase_ : Optional[int]="silu" , UpperCAmelCase_ : Tuple=2048 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : List[Any]=1e-6 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : int=0 , UpperCAmelCase_ : Optional[int]=1 , UpperCAmelCase_ : Any=2 , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Dict=None , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = rms_norm_eps SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = kwargs.pop( 'use_memorry_efficient_attention' , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_dropout_prob SCREAMING_SNAKE_CASE__ = use_stable_embedding SCREAMING_SNAKE_CASE__ = shared_input_output_embedding SCREAMING_SNAKE_CASE__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , tie_word_embeddings=UpperCAmelCase_ , **UpperCAmelCase_ , ) def A_ ( self : str ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , UpperCAmelCase_ ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' F'got {self.rope_scaling}' ) SCREAMING_SNAKE_CASE__ = self.rope_scaling.get('type' , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = self.rope_scaling.get('factor' , UpperCAmelCase_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or rope_scaling_factor <= 1.0: raise ValueError(F'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
400
from collections.abc import Callable def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> float: '''simple docstring''' SCREAMING_SNAKE_CASE__ = a SCREAMING_SNAKE_CASE__ = b if function(UpperCamelCase_ ) == 0: # one of the a or b is a root for the function return a elif function(UpperCamelCase_ ) == 0: return b elif ( function(UpperCamelCase_ ) * function(UpperCamelCase_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError('could not find root in given interval.' ) else: SCREAMING_SNAKE_CASE__ = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(UpperCamelCase_ ) == 0: return mid elif function(UpperCamelCase_ ) * function(UpperCamelCase_ ) < 0: SCREAMING_SNAKE_CASE__ = mid else: SCREAMING_SNAKE_CASE__ = mid SCREAMING_SNAKE_CASE__ = start + (end - start) / 2.0 return mid def _lowercase ( UpperCamelCase_ ) -> float: '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 10_00)) import doctest doctest.testmod()
400
1
"""simple docstring""" def _lowerCAmelCase(a : int , a : int ) -> str: if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) _SCREAMING_SNAKE_CASE =str(bin(SCREAMING_SNAKE_CASE__ ) )[2:] # remove the leading "0b" _SCREAMING_SNAKE_CASE =str(bin(SCREAMING_SNAKE_CASE__ ) )[2:] # remove the leading "0b" _SCREAMING_SNAKE_CASE =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()
255
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class snake_case ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' snake_case_ : Optional[int] = ["""image_processor""", """tokenizer"""] snake_case_ : Optional[int] = """LayoutLMv2ImageProcessor""" snake_case_ : Dict = ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""") def __init__( self : Optional[int] , lowerCAmelCase : List[str]=None , lowerCAmelCase : List[Any]=None , **lowerCAmelCase : List[str]) -> Optional[Any]: """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowerCAmelCase , ) _snake_case : Tuple = kwargs.pop("""feature_extractor""") _snake_case : List[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""") if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""") super().__init__(lowerCAmelCase , lowerCAmelCase) def __call__( self : List[str] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCAmelCase : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , lowerCAmelCase : Union[List[List[int]], List[List[List[int]]]] = None , lowerCAmelCase : Optional[Union[List[int], List[List[int]]]] = None , lowerCAmelCase : bool = True , lowerCAmelCase : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase : Union[bool, str, TruncationStrategy] = None , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : int = 0 , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : Optional[bool] = None , lowerCAmelCase : Optional[bool] = None , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : bool = True , lowerCAmelCase : Optional[Union[str, TensorType]] = None , **lowerCAmelCase : Optional[int] , ) -> BatchEncoding: """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( """You cannot provide bounding boxes """ """if you initialized the image processor with apply_ocr set to True.""") if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( """You cannot provide word labels if you initialized the image processor with apply_ocr set to True.""") if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("""You cannot return overflowing tokens without returning the offsets mapping.""") # first, apply the image processor _snake_case : str = self.image_processor(images=lowerCAmelCase , return_tensors=lowerCAmelCase) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(lowerCAmelCase , lowerCAmelCase): _snake_case : Optional[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension) _snake_case : Optional[Any] = features["""words"""] _snake_case : Tuple = self.tokenizer( text=text if text is not None else features["""words"""] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["""boxes"""] , word_labels=lowerCAmelCase , add_special_tokens=lowerCAmelCase , padding=lowerCAmelCase , truncation=lowerCAmelCase , max_length=lowerCAmelCase , stride=lowerCAmelCase , pad_to_multiple_of=lowerCAmelCase , return_token_type_ids=lowerCAmelCase , return_attention_mask=lowerCAmelCase , return_overflowing_tokens=lowerCAmelCase , return_special_tokens_mask=lowerCAmelCase , return_offsets_mapping=lowerCAmelCase , return_length=lowerCAmelCase , verbose=lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase , ) # add pixel values _snake_case : Optional[int] = features.pop("""pixel_values""") if return_overflowing_tokens is True: _snake_case : Tuple = self.get_overflowing_images(lowerCAmelCase , encoded_inputs["""overflow_to_sample_mapping"""]) _snake_case : int = images return encoded_inputs def UpperCamelCase_ ( self : Tuple , lowerCAmelCase : str , lowerCAmelCase : Tuple) -> Tuple: """simple docstring""" _snake_case : int = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx]) if len(lowerCAmelCase) != len(lowerCAmelCase): raise ValueError( """Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got""" F''' {len(lowerCAmelCase)} and {len(lowerCAmelCase)}''') return images_with_overflow def UpperCamelCase_ ( self : List[Any] , *lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : Optional[int]) -> int: """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase , **lowerCAmelCase) def UpperCamelCase_ ( self : Dict , *lowerCAmelCase : Any , **lowerCAmelCase : int) -> List[str]: """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase , **lowerCAmelCase) @property def UpperCamelCase_ ( self : Tuple) -> Any: """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCamelCase_ ( self : Any) -> Optional[int]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , lowerCAmelCase , ) return self.image_processor_class @property def UpperCamelCase_ ( self : Optional[int]) -> List[Any]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , lowerCAmelCase , ) return self.image_processor
477
0
class UpperCamelCase__ : """simple docstring""" def __init__( self , _A , _A ) -> int: SCREAMING_SNAKE_CASE_ = name SCREAMING_SNAKE_CASE_ = val def __str__( self ) -> Optional[int]: return F'''{self.__class__.__name__}({self.name}, {self.val})''' def __lt__( self , _A ) -> Tuple: return self.val < other.val class UpperCamelCase__ : """simple docstring""" def __init__( self , _A ) -> List[Any]: SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = self.build_heap(_A ) def __getitem__( self , _A ) -> List[Any]: return self.get_value(_A ) def _UpperCamelCase ( self , _A ) -> Union[str, Any]: return (idx - 1) // 2 def _UpperCamelCase ( self , _A ) -> Dict: return idx * 2 + 1 def _UpperCamelCase ( self , _A ) -> int: return idx * 2 + 2 def _UpperCamelCase ( self , _A ) -> Tuple: return self.heap_dict[key] def _UpperCamelCase ( self , _A ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = len(_A ) - 1 SCREAMING_SNAKE_CASE_ = self.get_parent_idx(_A ) for idx, i in enumerate(_A ): SCREAMING_SNAKE_CASE_ = idx SCREAMING_SNAKE_CASE_ = i.val for i in range(_A , -1 , -1 ): self.sift_down(_A , _A ) return array def _UpperCamelCase ( self , _A , _A ) -> List[str]: while True: SCREAMING_SNAKE_CASE_ = self.get_left_child_idx(_A ) # noqa: E741 SCREAMING_SNAKE_CASE_ = self.get_right_child_idx(_A ) SCREAMING_SNAKE_CASE_ = idx if l < len(_A ) and array[l] < array[idx]: SCREAMING_SNAKE_CASE_ = l if r < len(_A ) and array[r] < array[smallest]: SCREAMING_SNAKE_CASE_ = r if smallest != idx: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = array[smallest], array[idx] ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) SCREAMING_SNAKE_CASE_ = smallest else: break def _UpperCamelCase ( self , _A ) -> Tuple: SCREAMING_SNAKE_CASE_ = self.get_parent_idx(_A ) while p >= 0 and self.heap[p] > self.heap[idx]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.heap[idx], self.heap[p] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) SCREAMING_SNAKE_CASE_ = p SCREAMING_SNAKE_CASE_ = self.get_parent_idx(_A ) def _UpperCamelCase ( self ) -> Union[str, Any]: return self.heap[0] def _UpperCamelCase ( self ) -> Any: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.heap[-1], self.heap[0] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) SCREAMING_SNAKE_CASE_ = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def _UpperCamelCase ( self , _A ) -> Union[str, Any]: self.heap.append(_A ) SCREAMING_SNAKE_CASE_ = len(self.heap ) - 1 SCREAMING_SNAKE_CASE_ = node.val self.sift_up(len(self.heap ) - 1 ) def _UpperCamelCase ( self ) -> Optional[int]: return len(self.heap ) == 0 def _UpperCamelCase ( self , _A , _A ) -> Optional[Any]: assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" SCREAMING_SNAKE_CASE_ = new_value SCREAMING_SNAKE_CASE_ = new_value self.sift_up(self.idx_of_element[node] ) __UpperCAmelCase = Node("R", -1) __UpperCAmelCase = Node("B", 6) __UpperCAmelCase = Node("A", 3) __UpperCAmelCase = Node("X", 1) __UpperCAmelCase = Node("E", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __UpperCAmelCase = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("Min Heap - before decrease key") for i in my_min_heap.heap: print(i) print("Min Heap - After decrease key of node [B -> -17]") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
597
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy __UpperCAmelCase = logging.getLogger(__name__) __UpperCAmelCase = "pytorch_model.bin" @dataclasses.dataclass class UpperCamelCase__ : """simple docstring""" UpperCAmelCase_ =dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) UpperCAmelCase_ =dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."} , ) @dataclasses.dataclass class UpperCamelCase__ : """simple docstring""" UpperCAmelCase_ =dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) UpperCAmelCase_ =dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) UpperCAmelCase_ =dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "A csv or a json file containing the validation data."} ) UpperCAmelCase_ =dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "The name of the task to train on."} , ) UpperCAmelCase_ =dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class UpperCamelCase__ : """simple docstring""" UpperCAmelCase_ =dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) UpperCAmelCase_ =dataclasses.field( default="accuracy" , metadata={"help": "The evaluation metric used for the task."} ) UpperCAmelCase_ =dataclasses.field( default="no" , metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" } , ) UpperCAmelCase_ =dataclasses.field( default=10 , metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."} , ) UpperCAmelCase_ =dataclasses.field( default=0.0 , metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." } , ) UpperCAmelCase_ =dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."} , ) UpperCAmelCase_ =dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."} , ) UpperCAmelCase_ =dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to fine-tune on labeled data after pseudo training."} , ) UpperCAmelCase_ =dataclasses.field( default=0.0 , metadata={"help": "Confidence threshold for pseudo-labeled data filtering."} , ) UpperCAmelCase_ =dataclasses.field( default=100 , metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."} , ) UpperCAmelCase_ =dataclasses.field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Random seed for initialization."} , ) def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = datasets.concatenate_datasets([infer_input, infer_output], axis=1 ) if args.do_filter_by_confidence: SCREAMING_SNAKE_CASE_ = dataset.filter(lambda __lowerCamelCase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 SCREAMING_SNAKE_CASE_ = int(eval_result * len(__lowerCamelCase ) ) print(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = dataset.sort('''probability''', reverse=__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = dataset.select(range(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE_ = dataset.remove_columns(['''label''', '''probability'''] ) SCREAMING_SNAKE_CASE_ = dataset.rename_column('''prediction''', '''label''' ) SCREAMING_SNAKE_CASE_ = dataset.map(lambda __lowerCamelCase : {"label": idalabel[example["label"]]} ) SCREAMING_SNAKE_CASE_ = dataset.shuffle(seed=args.seed ) SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, F'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(__lowerCamelCase, index=__lowerCamelCase ) else: dataset.to_json(__lowerCamelCase ) def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, **__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() SCREAMING_SNAKE_CASE_ = STModelArguments(model_name_or_path=__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = STDataArguments(train_file=__lowerCamelCase, infer_file=__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = STTrainingArguments(output_dir=__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(__lowerCamelCase ).items(): setattr(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) for key, value in kwargs.items(): if hasattr(__lowerCamelCase, __lowerCamelCase ): setattr(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) # Sanity checks SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None SCREAMING_SNAKE_CASE_ = args.train_file SCREAMING_SNAKE_CASE_ = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None SCREAMING_SNAKE_CASE_ = args.eval_file for key in data_files: SCREAMING_SNAKE_CASE_ = data_files[key].split('''.''' )[-1] assert extension in ["csv", "json"], F'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: SCREAMING_SNAKE_CASE_ = extension else: assert extension == args.data_file_extension, F'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), F'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('''Creating the initial data directory for self-training...''' ) SCREAMING_SNAKE_CASE_ = F'''{args.output_dir}/self-train_iter-{{}}'''.format SCREAMING_SNAKE_CASE_ = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir, exist_ok=__lowerCamelCase ) os.makedirs(__lowerCamelCase, exist_ok=__lowerCamelCase ) accelerator.wait_for_everyone() SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = False # Show the progress bar SCREAMING_SNAKE_CASE_ = tqdm(range(args.max_selftrain_iterations ), disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0, int(args.max_selftrain_iterations ) ): SCREAMING_SNAKE_CASE_ = data_dir_format(__lowerCamelCase ) assert os.path.exists(__lowerCamelCase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, '''stage-1''' ) SCREAMING_SNAKE_CASE_ = { '''accelerator''': accelerator, '''model_name_or_path''': args.model_name_or_path, '''cache_dir''': args.cache_dir, '''do_train''': True, '''train_file''': data_files['''train'''] if iteration == 0 else data_files['''train_pseudo'''], '''do_eval''': True if args.eval_file is not None else False, '''eval_file''': data_files['''eval'''], '''do_predict''': True, '''infer_file''': data_files['''infer'''], '''task_name''': args.task_name, '''label_list''': args.label_list, '''output_dir''': current_output_dir, '''eval_metric''': args.eval_metric, '''evaluation_strategy''': args.evaluation_strategy, '''early_stopping_patience''': args.early_stopping_patience, '''early_stopping_threshold''': args.early_stopping_threshold, '''seed''': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(__lowerCamelCase, __lowerCamelCase ): arguments_dict.update({key: value} ) SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, '''best-checkpoint''', __lowerCamelCase ) if os.path.exists(__lowerCamelCase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''', __lowerCamelCase, __lowerCamelCase, ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''', __lowerCamelCase ) finetune(**__lowerCamelCase ) accelerator.wait_for_everyone() assert os.path.exists(__lowerCamelCase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''', __lowerCamelCase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, '''best-checkpoint''' ) SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, '''stage-2''' ) # Update arguments_dict SCREAMING_SNAKE_CASE_ = model_path SCREAMING_SNAKE_CASE_ = data_files['''train'''] SCREAMING_SNAKE_CASE_ = current_output_dir SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, '''best-checkpoint''', __lowerCamelCase ) if os.path.exists(__lowerCamelCase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''', __lowerCamelCase, __lowerCamelCase, ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''', __lowerCamelCase ) finetune(**__lowerCamelCase ) accelerator.wait_for_everyone() assert os.path.exists(__lowerCamelCase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''', __lowerCamelCase ) SCREAMING_SNAKE_CASE_ = iteration SCREAMING_SNAKE_CASE_ = data_dir_format(iteration + 1 ) SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(os.path.join(__lowerCamelCase, '''best-checkpoint''' ) ) SCREAMING_SNAKE_CASE_ = config.idalabel SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, '''eval_results_best-checkpoint.json''' ) SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, '''test_results_best-checkpoint.json''' ) assert os.path.exists(__lowerCamelCase ) with open(__lowerCamelCase, '''r''' ) as f: SCREAMING_SNAKE_CASE_ = float(json.load(__lowerCamelCase )[args.eval_metric] ) SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(__lowerCamelCase ) # Loading the dataset from local csv or json files. SCREAMING_SNAKE_CASE_ = load_dataset(args.data_file_extension, data_files={'''data''': data_files['''infer''']} )['''data'''] SCREAMING_SNAKE_CASE_ = load_dataset('''csv''', data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(__lowerCamelCase, exist_ok=__lowerCamelCase ) shutil.copy(__lowerCamelCase, os.path.join(__lowerCamelCase, F'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(__lowerCamelCase ): shutil.copy(__lowerCamelCase, os.path.join(__lowerCamelCase, F'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) accelerator.wait_for_everyone() SCREAMING_SNAKE_CASE_ = os.path.join(__lowerCamelCase, F'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: SCREAMING_SNAKE_CASE_ = eval_result if best_iteration is None: SCREAMING_SNAKE_CASE_ = new_iteration SCREAMING_SNAKE_CASE_ = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: SCREAMING_SNAKE_CASE_ = new_iteration SCREAMING_SNAKE_CASE_ = new_eval_result SCREAMING_SNAKE_CASE_ = 0 else: if new_eval_result == best_eval_result: SCREAMING_SNAKE_CASE_ = new_iteration SCREAMING_SNAKE_CASE_ = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: SCREAMING_SNAKE_CASE_ = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('''Best iteration: %d''', __lowerCamelCase ) logger.info('''Best evaluation result: %s = %f''', args.eval_metric, __lowerCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(__lowerCamelCase, F'''eval_results_iter-{iteration}.json''' ), os.path.join(__lowerCamelCase, '''eval_results_best-iteration.json''' ), ) else: # Assume that the last iteration is the best logger.info('''Best iteration: %d''', args.max_selftrain_iterations - 1 ) logger.info('''Best evaluation result: %s = %f''', args.eval_metric, __lowerCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(__lowerCamelCase, F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ), os.path.join(__lowerCamelCase, '''eval_results_best-iteration.json''' ), )
597
1
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class __A ( datasets.BuilderConfig ): UpperCAmelCase__ = None class __A ( datasets.ArrowBasedBuilder ): UpperCAmelCase__ = PandasConfig def lowerCamelCase__ ( self : str ) -> List[str]: return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase__ ( self : Union[str, Any] , __snake_case : Optional[Any] ) -> Optional[int]: if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) __magic_name__: Optional[int] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__snake_case , (str, list, tuple) ): __magic_name__: int = data_files if isinstance(__snake_case , __snake_case ): __magic_name__: Optional[Any] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __magic_name__: Dict = [dl_manager.iter_files(__snake_case ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] __magic_name__: Any = [] for split_name, files in data_files.items(): if isinstance(__snake_case , __snake_case ): __magic_name__: str = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __magic_name__: Dict = [dl_manager.iter_files(__snake_case ) for file in files] splits.append(datasets.SplitGenerator(name=__snake_case , gen_kwargs={"""files""": files} ) ) return splits def lowerCamelCase__ ( self : List[str] , __snake_case : Tuple ) -> pa.Table: if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example __magic_name__: int = table_cast(__snake_case , self.config.features.arrow_schema ) return pa_table def lowerCamelCase__ ( self : List[Any] , __snake_case : Any ) -> Any: for i, file in enumerate(itertools.chain.from_iterable(__snake_case ) ): with open(__snake_case , """rb""" ) as f: __magic_name__: Dict = pa.Table.from_pandas(pd.read_pickle(__snake_case ) ) yield i, self._cast_table(__snake_case )
96
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def A_ ( A__ ) -> Dict: a__ : Dict = 384 if "tiny" in model_name: a__ : Any = [3, 3, 9, 3] a__ : List[str] = [96, 192, 384, 768] if "small" in model_name: a__ : List[Any] = [3, 3, 27, 3] a__ : Tuple = [96, 192, 384, 768] if "base" in model_name: a__ : Union[str, Any] = [3, 3, 27, 3] a__ : List[Any] = [128, 256, 512, 1024] a__ : int = 512 if "large" in model_name: a__ : Dict = [3, 3, 27, 3] a__ : Tuple = [192, 384, 768, 1536] a__ : Any = 768 if "xlarge" in model_name: a__ : Union[str, Any] = [3, 3, 27, 3] a__ : Dict = [256, 512, 1024, 2048] a__ : Optional[int] = 1024 # set label information a__ : Optional[int] = 150 a__ : Optional[Any] = 'huggingface/label-files' a__ : Union[str, Any] = 'ade20k-id2label.json' a__ : Dict = json.load(open(hf_hub_download(A__ , A__ , repo_type='dataset' ) , 'r' ) ) a__ : str = {int(A__ ): v for k, v in idalabel.items()} a__ : int = {v: k for k, v in idalabel.items()} a__ : Tuple = ConvNextConfig( depths=A__ , hidden_sizes=A__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) a__ : Dict = UperNetConfig( backbone_config=A__ , auxiliary_in_channels=A__ , num_labels=A__ , idalabel=A__ , labelaid=A__ , ) return config def A_ ( A__ ) -> Union[str, Any]: a__ : int = [] # fmt: off # stem rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight') ) rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias') ) rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight') ) rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.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}.{j}.gamma', F'backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter') ) rename_keys.append((F'backbone.stages.{i}.{j}.depthwise_conv.weight', F'backbone.encoder.stages.{i}.layers.{j}.dwconv.weight') ) rename_keys.append((F'backbone.stages.{i}.{j}.depthwise_conv.bias', F'backbone.encoder.stages.{i}.layers.{j}.dwconv.bias') ) rename_keys.append((F'backbone.stages.{i}.{j}.norm.weight', F'backbone.encoder.stages.{i}.layers.{j}.layernorm.weight') ) rename_keys.append((F'backbone.stages.{i}.{j}.norm.bias', F'backbone.encoder.stages.{i}.layers.{j}.layernorm.bias') ) rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv1.weight', F'backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight') ) rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv1.bias', F'backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias') ) rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv2.weight', F'backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight') ) rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv2.bias', F'backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias') ) if i > 0: rename_keys.append((F'backbone.downsample_layers.{i}.0.weight', F'backbone.encoder.stages.{i}.downsampling_layer.0.weight') ) rename_keys.append((F'backbone.downsample_layers.{i}.0.bias', F'backbone.encoder.stages.{i}.downsampling_layer.0.bias') ) rename_keys.append((F'backbone.downsample_layers.{i}.1.weight', F'backbone.encoder.stages.{i}.downsampling_layer.1.weight') ) rename_keys.append((F'backbone.downsample_layers.{i}.1.bias', F'backbone.encoder.stages.{i}.downsampling_layer.1.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 A_ ( A__ , A__ , A__ ) -> Optional[Any]: a__ : Union[str, Any] = dct.pop(A__ ) a__ : Tuple = val def A_ ( A__ , A__ , A__ ) -> List[Any]: a__ : Dict = { 'upernet-convnext-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth', 'upernet-convnext-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth', 'upernet-convnext-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth', 'upernet-convnext-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth', 'upernet-convnext-xlarge': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth', } a__ : Union[str, Any] = model_name_to_url[model_name] a__ : Optional[int] = torch.hub.load_state_dict_from_url(A__ , map_location='cpu' )['state_dict'] a__ : Dict = get_upernet_config(A__ ) a__ : Dict = UperNetForSemanticSegmentation(A__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): a__ : List[Any] = state_dict.pop(A__ ) if "bn" in key: a__ : Optional[int] = key.replace('bn' , 'batch_norm' ) a__ : Any = val # rename keys a__ : List[Any] = create_rename_keys(A__ ) for src, dest in rename_keys: rename_key(A__ , A__ , A__ ) model.load_state_dict(A__ ) # verify on image a__ : List[Any] = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' a__ : int = Image.open(requests.get(A__ , stream=A__ ).raw ).convert('RGB' ) a__ : str = SegformerImageProcessor() a__ : List[str] = processor(A__ , return_tensors='pt' ).pixel_values with torch.no_grad(): a__ : List[Any] = model(A__ ) if model_name == "upernet-convnext-tiny": a__ : int = torch.tensor( [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]] ) elif model_name == "upernet-convnext-small": a__ : int = torch.tensor( [[-8.82_36, -8.82_36, -8.67_71], [-8.82_36, -8.82_36, -8.67_71], [-8.76_38, -8.76_38, -8.62_40]] ) elif model_name == "upernet-convnext-base": a__ : Tuple = torch.tensor( [[-8.85_58, -8.85_58, -8.69_05], [-8.85_58, -8.85_58, -8.69_05], [-8.76_69, -8.76_69, -8.60_21]] ) elif model_name == "upernet-convnext-large": a__ : str = torch.tensor( [[-8.66_60, -8.66_60, -8.62_10], [-8.66_60, -8.66_60, -8.62_10], [-8.63_10, -8.63_10, -8.59_64]] ) elif model_name == "upernet-convnext-xlarge": a__ : Union[str, Any] = torch.tensor( [[-8.49_80, -8.49_80, -8.39_77], [-8.49_80, -8.49_80, -8.39_77], [-8.43_79, -8.43_79, -8.34_12]] ) print('Logits:' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , A__ , 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(A__ ) print(F'Saving processor to {pytorch_dump_folder_path}' ) processor.save_pretrained(A__ ) 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__": lowercase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-convnext-tiny""", type=str, choices=[F"""upernet-convnext-{size}""" for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]], help="""Name of the ConvNext 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.""" ) lowercase : Dict = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
302
0
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class _SCREAMING_SNAKE_CASE : '''simple docstring''' def A ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase__ = TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) UpperCamelCase__ = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) UpperCamelCase__ = UNetaDConditionModel( sample_size=3_2 , layers_per_block=1 , block_out_channels=[3_2, 6_4] , down_block_types=[ """ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D""", ] , mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" , up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] , in_channels=3 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type="""text""" , addition_embed_type_num_heads=2 , cross_attention_norm="""group_norm""" , resnet_time_scale_shift="""scale_shift""" , act_fn="""gelu""" , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) UpperCamelCase__ = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_0_0_1 , beta_end=0.0_2 , thresholding=lowercase , dynamic_thresholding_ratio=0.9_5 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , ) torch.manual_seed(0 ) UpperCamelCase__ = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def A ( self : List[Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) UpperCamelCase__ = TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) UpperCamelCase__ = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) UpperCamelCase__ = UNetaDConditionModel( sample_size=3_2 , layers_per_block=[1, 2] , block_out_channels=[3_2, 6_4] , down_block_types=[ """ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D""", ] , mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" , up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] , in_channels=6 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type="""text""" , addition_embed_type_num_heads=2 , cross_attention_norm="""group_norm""" , resnet_time_scale_shift="""scale_shift""" , act_fn="""gelu""" , class_embed_type="""timestep""" , mid_block_scale_factor=1.4_1_4 , time_embedding_act_fn="""gelu""" , time_embedding_dim=3_2 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) UpperCamelCase__ = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_0_0_1 , beta_end=0.0_2 , thresholding=lowercase , dynamic_thresholding_ratio=0.9_5 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , ) torch.manual_seed(0 ) UpperCamelCase__ = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_0_0_1 , beta_end=0.0_2 , ) torch.manual_seed(0 ) UpperCamelCase__ = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def A ( self : Any ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ = self.get_dummy_components() UpperCamelCase__ = self.pipeline_class(**lowercase ) pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) UpperCamelCase__ = self.get_dummy_inputs(lowercase ) UpperCamelCase__ = inputs["""prompt"""] UpperCamelCase__ = inputs["""generator"""] UpperCamelCase__ = inputs["""num_inference_steps"""] UpperCamelCase__ = inputs["""output_type"""] if "image" in inputs: UpperCamelCase__ = inputs["""image"""] else: UpperCamelCase__ = None if "mask_image" in inputs: UpperCamelCase__ = inputs["""mask_image"""] else: UpperCamelCase__ = None if "original_image" in inputs: UpperCamelCase__ = inputs["""original_image"""] else: UpperCamelCase__ = None UpperCamelCase__ , UpperCamelCase__ = pipe.encode_prompt(lowercase ) # inputs with prompt converted to embeddings UpperCamelCase__ = { """prompt_embeds""": prompt_embeds, """negative_prompt_embeds""": negative_prompt_embeds, """generator""": generator, """num_inference_steps""": num_inference_steps, """output_type""": output_type, } if image is not None: UpperCamelCase__ = image if mask_image is not None: UpperCamelCase__ = mask_image if original_image is not None: UpperCamelCase__ = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(lowercase , lowercase , lowercase ) UpperCamelCase__ = pipe(**lowercase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowercase ) UpperCamelCase__ = self.pipeline_class.from_pretrained(lowercase ) pipe_loaded.to(lowercase ) pipe_loaded.set_progress_bar_config(disable=lowercase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(lowercase , lowercase ) is None , f"`{optional_component}` did not stay set to None after loading." , ) UpperCamelCase__ = self.get_dummy_inputs(lowercase ) UpperCamelCase__ = inputs["""generator"""] UpperCamelCase__ = inputs["""num_inference_steps"""] UpperCamelCase__ = inputs["""output_type"""] # inputs with prompt converted to embeddings UpperCamelCase__ = { """prompt_embeds""": prompt_embeds, """negative_prompt_embeds""": negative_prompt_embeds, """generator""": generator, """num_inference_steps""": num_inference_steps, """output_type""": output_type, } if image is not None: UpperCamelCase__ = image if mask_image is not None: UpperCamelCase__ = mask_image if original_image is not None: UpperCamelCase__ = original_image UpperCamelCase__ = pipe_loaded(**lowercase )[0] UpperCamelCase__ = np.abs(to_np(lowercase ) - to_np(lowercase ) ).max() self.assertLess(lowercase , 1e-4 ) def A ( self : List[Any] ) -> Any: '''simple docstring''' UpperCamelCase__ = self.get_dummy_components() UpperCamelCase__ = self.pipeline_class(**lowercase ) pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) UpperCamelCase__ = self.get_dummy_inputs(lowercase ) UpperCamelCase__ = pipe(**lowercase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowercase ) UpperCamelCase__ = self.pipeline_class.from_pretrained(lowercase ) pipe_loaded.to(lowercase ) pipe_loaded.set_progress_bar_config(disable=lowercase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests UpperCamelCase__ = self.get_dummy_inputs(lowercase ) UpperCamelCase__ = pipe_loaded(**lowercase )[0] UpperCamelCase__ = np.abs(to_np(lowercase ) - to_np(lowercase ) ).max() self.assertLess(lowercase , 1e-4 )
719
'''simple docstring''' from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCamelCase_ : List[str] = TypeVar('''T''') lowerCamelCase_ : Optional[int] = TypeVar('''U''') class _SCREAMING_SNAKE_CASE ( Generic[T, U] ): '''simple docstring''' def __init__( self : Dict , lowercase : T | None , lowercase : U | None ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = key UpperCamelCase__ = val UpperCamelCase__ = None UpperCamelCase__ = None def __repr__( self : List[Any] ) -> str: '''simple docstring''' return ( f"Node: key: {self.key}, val: {self.val}, " f"has next: {bool(self.next )}, has prev: {bool(self.prev )}" ) class _SCREAMING_SNAKE_CASE ( Generic[T, U] ): '''simple docstring''' def __init__( self : Union[str, Any] ) -> None: '''simple docstring''' UpperCamelCase__ = DoubleLinkedListNode(lowercase , lowercase ) UpperCamelCase__ = DoubleLinkedListNode(lowercase , lowercase ) UpperCamelCase__ , UpperCamelCase__ = self.rear, self.head def __repr__( self : int ) -> str: '''simple docstring''' UpperCamelCase__ = ["""DoubleLinkedList"""] UpperCamelCase__ = self.head while node.next is not None: rep.append(str(lowercase ) ) UpperCamelCase__ = node.next rep.append(str(self.rear ) ) return ",\n ".join(lowercase ) def A ( self : str , lowercase : DoubleLinkedListNode[T, U] ) -> None: '''simple docstring''' UpperCamelCase__ = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None UpperCamelCase__ = node UpperCamelCase__ = previous UpperCamelCase__ = node UpperCamelCase__ = self.rear def A ( self : Any , lowercase : DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: '''simple docstring''' if node.prev is None or node.next is None: return None UpperCamelCase__ = node.next UpperCamelCase__ = node.prev UpperCamelCase__ = None UpperCamelCase__ = None return node class _SCREAMING_SNAKE_CASE ( Generic[T, U] ): '''simple docstring''' __a : dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__( self : int , lowercase : int ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = DoubleLinkedList() UpperCamelCase__ = capacity UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = {} def __repr__( self : Any ) -> str: '''simple docstring''' return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current size={self.num_keys})" ) def __contains__( self : Any , lowercase : T ) -> bool: '''simple docstring''' return key in self.cache def A ( self : Tuple , lowercase : T ) -> U | None: '''simple docstring''' if key in self.cache: self.hits += 1 UpperCamelCase__ = self.cache[key] UpperCamelCase__ = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(lowercase ) return node.val self.miss += 1 return None def A ( self : Dict , lowercase : T , lowercase : U ) -> None: '''simple docstring''' if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity UpperCamelCase__ = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(lowercase ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 UpperCamelCase__ = DoubleLinkedListNode(lowercase , lowercase ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value UpperCamelCase__ = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list UpperCamelCase__ = value self.list.add(lowercase ) @classmethod def A ( cls : Optional[int] , lowercase : int = 1_2_8 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: '''simple docstring''' def cache_decorator_inner(lowercase : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*lowercase : T ) -> U: if func not in cls.decorator_function_to_instance_map: UpperCamelCase__ = LRUCache(lowercase ) UpperCamelCase__ = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: UpperCamelCase__ = func(*lowercase ) cls.decorator_function_to_instance_map[func].put(args[0] , lowercase ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(lowercase , """cache_info""" , lowercase ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
265
0
"""simple docstring""" # Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def __magic_name__ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any]=0 ): # Format the message. if name is None: __a : Dict = None else: __a : List[Any] = "." * max(0 , spaces - 2 ) + "# {:" + str(5_0 - spaces ) + "s}" __a : Optional[Any] = fmt.format(__UpperCamelCase ) # Print and recurse (if needed). if isinstance(__UpperCamelCase , __UpperCamelCase ): if msg is not None: print(__UpperCamelCase ) for k in val.keys(): recursive_print(__UpperCamelCase , val[k] , spaces + 2 ) elif isinstance(__UpperCamelCase , torch.Tensor ): print(__UpperCamelCase , """:""" , val.size() ) else: print(__UpperCamelCase , """:""" , __UpperCamelCase ) def __magic_name__ ( _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : Optional[Any] ): # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. __a : Optional[int] = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] __a : Optional[int] = (num_heads, hidden_size, num_splits) + input_shape[1:] __a : List[Any] = param.view(*__UpperCamelCase ) __a : Tuple = param.transpose(0 , 2 ) __a : List[str] = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] __a : Dict = (num_heads, num_splits, hidden_size) + input_shape[1:] __a : Optional[int] = param.view(*__UpperCamelCase ) __a : Any = param.transpose(0 , 1 ).contiguous() __a : Dict = param.view(*__UpperCamelCase ) return param def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : List[Any] , _lowerCamelCase : Any ): # The converted output model. __a : Dict = {} # old versions did not store training args __a : Union[str, Any] = input_state_dict.get("""args""" , __UpperCamelCase ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) __a : Dict = ds_args.padded_vocab_size __a : Optional[int] = ds_args.max_position_embeddings __a : Any = ds_args.hidden_size __a : int = ds_args.num_layers __a : int = ds_args.num_attention_heads __a : Any = ds_args.ffn_hidden_size # pprint(config) # The number of heads. __a : Tuple = config.n_head # The hidden_size per head. __a : Dict = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): __a : Union[str, Any] = input_state_dict["checkpoint_version"] else: __a : Union[str, Any] = 0.0 # The model. __a : List[Any] = input_state_dict["model"] # The language model. __a : str = model["language_model"] # The embeddings. __a : List[Any] = lm["embedding"] # The word embeddings. __a : int = embeddings["word_embeddings"]["weight"] # Truncate the embedding table to vocab_size rows. __a : List[str] = word_embeddings[: config.vocab_size, :] __a : int = word_embeddings # The position embeddings. __a : Union[str, Any] = embeddings["position_embeddings"]["weight"] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] __a : int = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( F'''pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don\'t match''' ) # Store the position embeddings. __a : Optional[Any] = pos_embeddings # The transformer. __a : Dict = lm["transformer"] if "transformer" in lm.keys() else lm["encoder"] # The regex to extract layer names. __a : Any = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. __a : Any = { "attention.dense": ".attn.c_proj.", "self_attention.dense": ".attn.c_proj.", "mlp.dense_h_to_4h": ".mlp.c_fc.", "mlp.dense_4h_to_h": ".mlp.c_proj.", } # Extract the layers. for key, val in transformer.items(): # Match the name. __a : int = layer_re.match(__UpperCamelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. __a : Any = int(m.group(1 ) ) # The name of the operation. __a : Optional[Any] = m.group(2 ) # Is it a weight or a bias? __a : str = m.group(3 ) # The name of the layer. __a : Optional[Any] = F'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): __a : List[str] = "ln_1" if op_name.startswith("""input""" ) else "ln_2" __a : Any = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. __a : List[str] = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , __UpperCamelCase , __UpperCamelCase ) __a : Optional[Any] = causal_mask # Insert a "dummy" tensor for masked_bias. __a : List[Any] = torch.tensor(-1E4 , dtype=torch.floataa ) __a : Dict = masked_bias __a : Union[str, Any] = fix_query_key_value_ordering(__UpperCamelCase , __UpperCamelCase , 3 , __UpperCamelCase , __UpperCamelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. __a : Optional[int] = out_val.transpose(0 , 1 ).contiguous() # Store. __a : List[str] = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": __a : Dict = fix_query_key_value_ordering(__UpperCamelCase , __UpperCamelCase , 3 , __UpperCamelCase , __UpperCamelCase ) # Store. No change of shape. __a : List[str] = out_val # Transpose the weights. elif weight_or_bias == "weight": __a : Dict = megatron_to_transformers[op_name] __a : Dict = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": __a : str = megatron_to_transformers[op_name] __a : Union[str, Any] = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. __a : str = transformer["final_layernorm.weight"] __a : int = transformer["final_layernorm.bias"] # For LM head, transformers' wants the matrix to weight embeddings. __a : Any = word_embeddings # It should be done! return output_state_dict def __magic_name__ ( ): # Create the argument parser. __a : List[str] = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""" , action="""store_true""" ) parser.add_argument( """path_to_checkpoint""" , type=__UpperCamelCase , help="""Path to the checkpoint file (.zip archive or direct .pt file)""" , ) parser.add_argument( """--config_file""" , default="""""" , type=__UpperCamelCase , help="""An optional config json file describing the pre-trained model.""" , ) __a : Any = parser.parse_args() # Extract the basename. __a : List[str] = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(F'''Extracting PyTorch state dictionary from {args.path_to_checkpoint}''' ) if args.path_to_checkpoint.endswith(""".zip""" ): with zipfile.ZipFile(args.path_to_checkpoint , """r""" ) as checkpoint: with checkpoint.open("""release/mp_rank_00/model_optim_rng.pt""" ) as pytorch_dict: __a : Tuple = torch.load(__UpperCamelCase , map_location="""cpu""" ) else: __a : Tuple = torch.load(args.path_to_checkpoint , map_location="""cpu""" ) __a : int = input_state_dict.get("""args""" , __UpperCamelCase ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: __a : int = "gelu_fast" elif ds_args.openai_gelu: __a : int = "gelu_new" else: __a : Tuple = "gelu" else: # in the very early days this used to be "gelu_new" __a : str = "gelu_new" # Spell out all parameters in case the defaults change. __a : Dict = GPTaConfig( vocab_size=5_0_2_5_7 , n_positions=1_0_2_4 , n_embd=1_0_2_4 , n_layer=2_4 , n_head=1_6 , n_inner=4_0_9_6 , activation_function=__UpperCamelCase , resid_pdrop=0.1 , embd_pdrop=0.1 , attn_pdrop=0.1 , layer_norm_epsilon=1E-5 , initializer_range=0.02 , summary_type="""cls_index""" , summary_use_proj=__UpperCamelCase , summary_activation=__UpperCamelCase , summary_proj_to_labels=__UpperCamelCase , summary_first_dropout=0.1 , scale_attn_weights=__UpperCamelCase , use_cache=__UpperCamelCase , bos_token_id=5_0_2_5_6 , eos_token_id=5_0_2_5_6 , ) else: __a : Optional[Any] = GPTaConfig.from_json_file(args.config_file ) __a : str = ["GPT2LMHeadModel"] # Convert. print("""Converting""" ) __a : Optional[int] = convert_megatron_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(__UpperCamelCase , __UpperCamelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: __a : Tuple = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": __a : Dict = "gpt2" elif tokenizer_type == "PretrainedFromHF": __a : Tuple = ds_args.tokenizer_name_or_path else: raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: __a : str = "gpt2" __a : str = AutoTokenizer.from_pretrained(__UpperCamelCase ) __a : Union[str, Any] = type(__UpperCamelCase ).__name__ __a : Tuple = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(__UpperCamelCase ) # Save tokenizer based on args print(F'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(__UpperCamelCase ) # Store the state_dict to file. __a : Tuple = os.path.join(__UpperCamelCase , """pytorch_model.bin""" ) print(F'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(__UpperCamelCase , __UpperCamelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
581
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { """Salesforce/codegen-350M-nl""": """https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json""", """Salesforce/codegen-350M-multi""": """https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json""", """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json""", """Salesforce/codegen-2B-nl""": """https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json""", """Salesforce/codegen-2B-multi""": """https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json""", """Salesforce/codegen-2B-mono""": """https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json""", """Salesforce/codegen-6B-nl""": """https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json""", """Salesforce/codegen-6B-multi""": """https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json""", """Salesforce/codegen-6B-mono""": """https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json""", """Salesforce/codegen-16B-nl""": """https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json""", """Salesforce/codegen-16B-multi""": """https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json""", """Salesforce/codegen-16B-mono""": """https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json""", } class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A :str = "codegen" A :Tuple = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , __UpperCAmelCase=5_0400 , __UpperCAmelCase=2048 , __UpperCAmelCase=2048 , __UpperCAmelCase=4096 , __UpperCAmelCase=28 , __UpperCAmelCase=16 , __UpperCAmelCase=64 , __UpperCAmelCase=None , __UpperCAmelCase="gelu_new" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=0.0_2 , __UpperCAmelCase=True , __UpperCAmelCase=5_0256 , __UpperCAmelCase=5_0256 , __UpperCAmelCase=False , **__UpperCAmelCase , ): """simple docstring""" a__ : Dict = vocab_size a__ : int = n_ctx a__ : str = n_positions a__ : Union[str, Any] = n_embd a__ : Union[str, Any] = n_layer a__ : Optional[int] = n_head a__ : Dict = n_inner a__ : Optional[Any] = rotary_dim a__ : str = activation_function a__ : List[Any] = resid_pdrop a__ : str = embd_pdrop a__ : List[str] = attn_pdrop a__ : str = layer_norm_epsilon a__ : Any = initializer_range a__ : List[str] = use_cache a__ : Tuple = bos_token_id a__ : List[Any] = eos_token_id super().__init__( bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , tie_word_embeddings=__UpperCAmelCase , **__UpperCAmelCase ) class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __UpperCAmelCase , __UpperCAmelCase = "default" , __UpperCAmelCase = None , __UpperCAmelCase = False , ): """simple docstring""" super().__init__(__UpperCAmelCase , task=__UpperCAmelCase , patching_specs=__UpperCAmelCase , use_past=__UpperCAmelCase ) if not getattr(self._config , "pad_token_id" , __UpperCAmelCase ): # TODO: how to do that better? a__ : Union[str, Any] = 0 @property def _A ( self ): """simple docstring""" a__ : Optional[Any] = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction="inputs" ) a__ : Any = {0: "batch", 1: "past_sequence + sequence"} else: a__ : List[Any] = {0: "batch", 1: "sequence"} return common_inputs @property def _A ( self ): """simple docstring""" return self._config.n_layer @property def _A ( self ): """simple docstring""" return self._config.n_head def _A ( self , __UpperCAmelCase , __UpperCAmelCase = -1 , __UpperCAmelCase = -1 , __UpperCAmelCase = False , __UpperCAmelCase = None , ): """simple docstring""" a__ : Dict = super(__UpperCAmelCase , self ).generate_dummy_inputs( __UpperCAmelCase , batch_size=__UpperCAmelCase , seq_length=__UpperCAmelCase , is_pair=__UpperCAmelCase , framework=__UpperCAmelCase ) # We need to order the input in the way they appears in the forward() a__ : Union[str, Any] = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch a__ , a__ : Union[str, Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values a__ : Any = seqlen + 2 a__ : str = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) a__ : str = [ (torch.zeros(__UpperCAmelCase ), torch.zeros(__UpperCAmelCase )) for _ in range(self.num_layers ) ] a__ : Union[str, Any] = common_inputs["attention_mask"] if self.use_past: a__ : str = ordered_inputs["attention_mask"].dtype a__ : Union[str, Any] = torch.cat( [ordered_inputs["attention_mask"], torch.ones(__UpperCAmelCase , __UpperCAmelCase , dtype=__UpperCAmelCase )] , dim=1 ) return ordered_inputs @property def _A ( self ): """simple docstring""" return 13
191
0
'''simple docstring''' import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( ConditionalDetrConfig, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCAmelCase : List[Any] = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) _lowerCAmelCase : int = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'''transformer.encoder.layers.{i}.self_attn.out_proj.weight''', F'''encoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append( (F'''transformer.encoder.layers.{i}.self_attn.out_proj.bias''', F'''encoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''encoder.layers.{i}.fc1.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''encoder.layers.{i}.fc1.bias''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''encoder.layers.{i}.fc2.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''encoder.layers.{i}.fc2.bias''')) rename_keys.append( (F'''transformer.encoder.layers.{i}.norm1.weight''', F'''encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''encoder.layers.{i}.self_attn_layer_norm.bias''')) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''encoder.layers.{i}.final_layer_norm.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''encoder.layers.{i}.final_layer_norm.bias''')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''decoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append( ( F'''transformer.decoder.layers.{i}.cross_attn.out_proj.weight''', F'''decoder.layers.{i}.encoder_attn.out_proj.weight''', ) ) rename_keys.append( ( F'''transformer.decoder.layers.{i}.cross_attn.out_proj.bias''', F'''decoder.layers.{i}.encoder_attn.out_proj.bias''', ) ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''decoder.layers.{i}.fc1.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''decoder.layers.{i}.fc1.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''decoder.layers.{i}.fc2.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''decoder.layers.{i}.fc2.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm1.weight''', F'''decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''decoder.layers.{i}.self_attn_layer_norm.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm2.weight''', F'''decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm2.bias''', F'''decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''decoder.layers.{i}.final_layer_norm.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''decoder.layers.{i}.final_layer_norm.bias''')) # q, k, v projections in self/cross-attention in decoder for conditional DETR rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qcontent_proj.weight''', F'''decoder.layers.{i}.sa_qcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kcontent_proj.weight''', F'''decoder.layers.{i}.sa_kcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qpos_proj.weight''', F'''decoder.layers.{i}.sa_qpos_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kpos_proj.weight''', F'''decoder.layers.{i}.sa_kpos_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_v_proj.weight''', F'''decoder.layers.{i}.sa_v_proj.weight''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qcontent_proj.weight''', F'''decoder.layers.{i}.ca_qcontent_proj.weight''') ) # rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.weight", f"decoder.layers.{i}.ca_qpos_proj.weight")) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kcontent_proj.weight''', F'''decoder.layers.{i}.ca_kcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kpos_proj.weight''', F'''decoder.layers.{i}.ca_kpos_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_v_proj.weight''', F'''decoder.layers.{i}.ca_v_proj.weight''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qpos_sine_proj.weight''', F'''decoder.layers.{i}.ca_qpos_sine_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qcontent_proj.bias''', F'''decoder.layers.{i}.sa_qcontent_proj.bias''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kcontent_proj.bias''', F'''decoder.layers.{i}.sa_kcontent_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_qpos_proj.bias''', F'''decoder.layers.{i}.sa_qpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_kpos_proj.bias''', F'''decoder.layers.{i}.sa_kpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_v_proj.bias''', F'''decoder.layers.{i}.sa_v_proj.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qcontent_proj.bias''', F'''decoder.layers.{i}.ca_qcontent_proj.bias''') ) # rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.bias", f"decoder.layers.{i}.ca_qpos_proj.bias")) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kcontent_proj.bias''', F'''decoder.layers.{i}.ca_kcontent_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_kpos_proj.bias''', F'''decoder.layers.{i}.ca_kpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_v_proj.bias''', F'''decoder.layers.{i}.ca_v_proj.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qpos_sine_proj.bias''', F'''decoder.layers.{i}.ca_qpos_sine_proj.bias''') ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads # for conditional DETR, also convert reference point head and query scale MLP rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ("transformer.decoder.ref_point_head.layers.0.weight", "decoder.ref_point_head.layers.0.weight"), ("transformer.decoder.ref_point_head.layers.0.bias", "decoder.ref_point_head.layers.0.bias"), ("transformer.decoder.ref_point_head.layers.1.weight", "decoder.ref_point_head.layers.1.weight"), ("transformer.decoder.ref_point_head.layers.1.bias", "decoder.ref_point_head.layers.1.bias"), ("transformer.decoder.query_scale.layers.0.weight", "decoder.query_scale.layers.0.weight"), ("transformer.decoder.query_scale.layers.0.bias", "decoder.query_scale.layers.0.bias"), ("transformer.decoder.query_scale.layers.1.weight", "decoder.query_scale.layers.1.weight"), ("transformer.decoder.query_scale.layers.1.bias", "decoder.query_scale.layers.1.bias"), ("transformer.decoder.layers.0.ca_qpos_proj.weight", "decoder.layers.0.ca_qpos_proj.weight"), ("transformer.decoder.layers.0.ca_qpos_proj.bias", "decoder.layers.0.ca_qpos_proj.bias"), ] ) def _A ( snake_case__ : Union[str, Any] , snake_case__ : List[str] , snake_case__ : int ): snake_case__ : List[Any] = state_dict.pop(snake_case__ ) snake_case__ : List[str] = val def _A ( snake_case__ : List[str] ): snake_case__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: snake_case__ : str = key.replace('''backbone.0.body''' , '''backbone.conv_encoder.model''' ) snake_case__ : List[Any] = value else: snake_case__ : Any = value return new_state_dict def _A ( snake_case__ : int , snake_case__ : Any=False ): snake_case__ : int = '''''' if is_panoptic: snake_case__ : Optional[Any] = '''conditional_detr.''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) snake_case__ : int = state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) snake_case__ : Optional[int] = state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[:2_56, :] snake_case__ : str = in_proj_bias[:2_56] snake_case__ : Dict = in_proj_weight[2_56:5_12, :] snake_case__ : Tuple = in_proj_bias[2_56:5_12] snake_case__ : int = in_proj_weight[-2_56:, :] snake_case__ : Tuple = in_proj_bias[-2_56:] def _A ( ): snake_case__ : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' snake_case__ : int = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def _A ( snake_case__ : Optional[Any] , snake_case__ : Optional[Any] ): snake_case__ : List[Any] = ConditionalDetrConfig() # set backbone and dilation attributes if "resnet101" in model_name: snake_case__ : Optional[int] = '''resnet101''' if "dc5" in model_name: snake_case__ : List[Any] = True snake_case__ : Dict = '''panoptic''' in model_name if is_panoptic: snake_case__ : Union[str, Any] = 2_50 else: snake_case__ : str = 91 snake_case__ : Tuple = '''huggingface/label-files''' snake_case__ : Dict = '''coco-detection-id2label.json''' snake_case__ : Any = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) snake_case__ : Tuple = {int(snake_case__ ): v for k, v in idalabel.items()} snake_case__ : Tuple = idalabel snake_case__ : str = {v: k for k, v in idalabel.items()} # load image processor snake_case__ : Optional[int] = '''coco_panoptic''' if is_panoptic else '''coco_detection''' snake_case__ : int = ConditionalDetrImageProcessor(format=snake_case__ ) # prepare image snake_case__ : Dict = prepare_img() snake_case__ : int = image_processor(images=snake_case__ , return_tensors='''pt''' ) snake_case__ : Any = encoding['''pixel_values'''] logger.info(f'''Converting model {model_name}...''' ) # load original model from torch hub snake_case__ : Union[str, Any] = torch.hub.load('''DeppMeng/ConditionalDETR''' , snake_case__ , pretrained=snake_case__ ).eval() snake_case__ : str = conditional_detr.state_dict() # rename keys for src, dest in rename_keys: if is_panoptic: snake_case__ : Optional[Any] = '''conditional_detr.''' + src rename_key(snake_case__ , snake_case__ , snake_case__ ) snake_case__ : Dict = rename_backbone_keys(snake_case__ ) # query, key and value matrices need special treatment read_in_q_k_v(snake_case__ , is_panoptic=snake_case__ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them snake_case__ : Tuple = '''conditional_detr.model.''' if is_panoptic else '''model.''' for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith('''conditional_detr''' ) and not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ) ): snake_case__ : int = state_dict.pop(snake_case__ ) snake_case__ : str = val elif "class_labels_classifier" in key or "bbox_predictor" in key: snake_case__ : str = state_dict.pop(snake_case__ ) snake_case__ : List[str] = val elif key.startswith('''bbox_attention''' ) or key.startswith('''mask_head''' ): continue else: snake_case__ : Any = state_dict.pop(snake_case__ ) snake_case__ : Union[str, Any] = val else: if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): snake_case__ : Dict = state_dict.pop(snake_case__ ) snake_case__ : Optional[Any] = val # finally, create HuggingFace model and load state dict snake_case__ : int = ConditionalDetrForSegmentation(snake_case__ ) if is_panoptic else ConditionalDetrForObjectDetection(snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() model.push_to_hub(repo_id=snake_case__ , organization='''DepuMeng''' , commit_message='''Add model''' ) # verify our conversion snake_case__ : Optional[Any] = conditional_detr(snake_case__ ) snake_case__ : List[Any] = model(snake_case__ ) assert torch.allclose(outputs.logits , original_outputs['''pred_logits'''] , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes , original_outputs['''pred_boxes'''] , atol=1E-4 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs['''pred_masks'''] , atol=1E-4 ) # Save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) model.save_pretrained(snake_case__ ) image_processor.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowerCAmelCase : int = argparse.ArgumentParser() parser.add_argument( "--model_name", default="conditional_detr_resnet50", type=str, help="Name of the CONDITIONAL_DETR model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) _lowerCAmelCase : List[str] = parser.parse_args() convert_conditional_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path)
712
'''simple docstring''' from __future__ import annotations def _A ( snake_case__ : list[float] , snake_case__ : list[float] ): snake_case__ : Dict = sorted(numsa + numsa ) snake_case__ ,snake_case__ : Tuple = divmod(len(snake_case__ ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCAmelCase : Tuple = [float(x) for x in input("Enter the elements of first array: ").split()] _lowerCAmelCase : List[str] = [float(x) for x in input("Enter the elements of second array: ").split()] print(F'''The median of two arrays is: {median_of_two_arrays(array_a, array_a)}''')
694
0
from math import sqrt def a ( A__ ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(A__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def a ( A__ = 1_0_0_0_1 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 1 while count != nth and number < 3: number += 1 if is_prime(A__ ): count += 1 while count != nth: number += 2 if is_prime(A__ ): count += 1 return number if __name__ == "__main__": print(F'''{solution() = }''')
35
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def UpperCAmelCase_ ( __a : dict ): '''simple docstring''' return (data["data"], data["target"]) def UpperCAmelCase_ ( __a : np.ndarray , __a : np.ndarray ): '''simple docstring''' _lowerCamelCase : Dict = XGBClassifier() classifier.fit(__a , __a ) return classifier def UpperCAmelCase_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = load_iris() _lowerCamelCase , _lowerCamelCase : Optional[Any] = data_handling(__a ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = train_test_split( __a , __a , test_size=0.2_5 ) _lowerCamelCase : Optional[Any] = iris['target_names'] # Create an XGBoost Classifier from the training data _lowerCamelCase : Tuple = xgboost(__a , __a ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( __a , __a , __a , display_labels=__a , cmap='Blues' , normalize='true' , ) plt.title('Normalized Confusion Matrix - IRIS Dataset' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
437
0
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ = 3 ) -> qiskit.result.counts.Counts: if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(SCREAMING_SNAKE_CASE_ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) lowerCAmelCase__ : Any = QuantumRegister(SCREAMING_SNAKE_CASE_ , 'qr' ) lowerCAmelCase__ : List[Any] = ClassicalRegister(SCREAMING_SNAKE_CASE_ , 'cr' ) lowerCAmelCase__ : Optional[int] = QuantumCircuit(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Optional[Any] = number_of_qubits for i in range(SCREAMING_SNAKE_CASE_ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(SCREAMING_SNAKE_CASE_ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(SCREAMING_SNAKE_CASE_ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # simulate with 10000 shots lowerCAmelCase__ : str = Aer.get_backend('qasm_simulator' ) lowerCAmelCase__ : List[Any] = execute(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , shots=10_000 ) return job.result().get_counts(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
713
from numpy import exp, pi, sqrt def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 1.0 ) -> int: return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
69
0
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 __UpperCAmelCase = get_tests_dir("fixtures") class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = mock.Mock() snake_case: List[Any] = 5_00 snake_case: Any = {} snake_case: Optional[Any] = HTTPError snake_case: Tuple = {} # Download this model to make sure it's in the cache. snake_case: List[str] = WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=SCREAMING_SNAKE_CASE__ ) as mock_head: snake_case: int = WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # This check we did call the fake head request mock_head.assert_called() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = WavaVecaFeatureExtractor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json' ) @is_staging_test class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @classmethod def _UpperCamelCase ( cls ): '''simple docstring''' snake_case: List[str] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) @classmethod def _UpperCamelCase ( cls ): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-feature-extractor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-feature-extractor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-feature-extractor' ) except HTTPError: pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = WavaVecaFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE__ ) feature_extractor.push_to_hub('test-feature-extractor' , use_auth_token=self._token ) snake_case: Tuple = WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Reset repo delete_repo(token=self._token , repo_id='test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( SCREAMING_SNAKE_CASE__ , repo_id='test-feature-extractor' , push_to_hub=SCREAMING_SNAKE_CASE__ , use_auth_token=self._token ) snake_case: List[str] = WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = WavaVecaFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE__ ) feature_extractor.push_to_hub('valid_org/test-feature-extractor' , use_auth_token=self._token ) snake_case: List[Any] = WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( SCREAMING_SNAKE_CASE__ , repo_id='valid_org/test-feature-extractor-org' , push_to_hub=SCREAMING_SNAKE_CASE__ , use_auth_token=self._token ) snake_case: str = WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def _UpperCamelCase ( self ): '''simple docstring''' CustomFeatureExtractor.register_for_auto_class() snake_case: Any = CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE__ ) feature_extractor.push_to_hub('test-dynamic-feature-extractor' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor'} , ) snake_case: Optional[int] = AutoFeatureExtractor.from_pretrained( F"""{USER}/test-dynamic-feature-extractor""" , trust_remote_code=SCREAMING_SNAKE_CASE__ ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , 'CustomFeatureExtractor' )
329
'''simple docstring''' import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class SCREAMING_SNAKE_CASE : '''simple docstring''' @property def _UpperCamelCase ( self ): '''simple docstring''' return self.get_dummy_input() @property def _UpperCamelCase ( self ): '''simple docstring''' if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , ): '''simple docstring''' snake_case: List[Any] = 4 snake_case: Any = 32 snake_case: Dict = (32, 32) snake_case: str = torch.manual_seed(0 ) snake_case: List[Any] = torch.device(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = (batch_size, num_channels) + sizes snake_case: Optional[Any] = randn_tensor(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = {'hidden_states': hidden_states} if include_temb: snake_case: List[str] = 1_28 snake_case: str = randn_tensor((batch_size, temb_channels) , generator=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ) if include_res_hidden_states_tuple: snake_case: int = torch.manual_seed(1 ) snake_case: int = (randn_tensor(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ),) if include_encoder_hidden_states: snake_case: List[Any] = floats_tensor((batch_size, 32, 32) ).to(SCREAMING_SNAKE_CASE__ ) if include_skip_sample: snake_case: Dict = randn_tensor(((batch_size, 3) + sizes) , generator=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ) return dummy_input def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = { 'in_channels': 32, 'out_channels': 32, 'temb_channels': 1_28, } if self.block_type == "up": snake_case: int = 32 if self.block_type == "mid": init_dict.pop('out_channels' ) snake_case: Optional[Any] = self.dummy_input return init_dict, inputs_dict def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case , snake_case: Optional[Any] = self.prepare_init_args_and_inputs_for_common() snake_case: str = self.block_class(**SCREAMING_SNAKE_CASE__ ) unet_block.to(SCREAMING_SNAKE_CASE__ ) unet_block.eval() with torch.no_grad(): snake_case: int = unet_block(**SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = output[0] self.assertEqual(output.shape , self.output_shape ) snake_case: List[Any] = output[0, -1, -3:, -3:] snake_case: Any = torch.tensor(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) assert torch_all_close(output_slice.flatten() , SCREAMING_SNAKE_CASE__ , atol=5E-3 ) @unittest.skipIf(torch_device == 'mps' , 'Training is not supported in mps' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case: Dict = self.prepare_init_args_and_inputs_for_common() snake_case: Optional[Any] = self.block_class(**SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.train() snake_case: List[Any] = model(**SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: str = output[0] snake_case: Optional[Any] = torch.device(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = randn_tensor(output.shape , device=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = torch.nn.functional.mse_loss(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) loss.backward()
329
1
"""simple docstring""" import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants __A : List[Any] = Mapping[str, np.ndarray] __A : int = Mapping[str, Any] # Is a nested dict. __A : List[Any] = 0.01 @dataclasses.dataclass(frozen=lowerCAmelCase_ ) class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. __UpperCAmelCase : np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. __UpperCAmelCase : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. __UpperCAmelCase : np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. __UpperCAmelCase : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions __UpperCAmelCase : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files __UpperCAmelCase : Optional[str] = None # Templates used to generate this protein (prediction-only) __UpperCAmelCase : Optional[Sequence[str]] = None # Chain corresponding to each parent __UpperCAmelCase : Optional[Sequence[int]] = None def snake_case__ ( _lowerCamelCase ) ->Protein: """simple docstring""" __lowercase : str = R"(\[[A-Z]+\]\n)" __lowercase : List[str] = [tag.strip() for tag in re.split(_lowerCamelCase, _lowerCamelCase ) if len(_lowerCamelCase ) > 0] __lowercase : Iterator[Tuple[str, List[str]]] = zip(tags[0::2], [l.split("\n" ) for l in tags[1::2]] ) __lowercase : List[str] = ["N", "CA", "C"] __lowercase : Optional[Any] = None __lowercase : Union[str, Any] = None __lowercase : Dict = None for g in groups: if "[PRIMARY]" == g[0]: __lowercase : Tuple = g[1][0].strip() for i in range(len(_lowerCamelCase ) ): if seq[i] not in residue_constants.restypes: __lowercase : Optional[int] = "X" # FIXME: strings are immutable __lowercase : Union[str, Any] = np.array( [residue_constants.restype_order.get(_lowerCamelCase, residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: __lowercase : List[List[float]] = [] for axis in range(3 ): tertiary.append(list(map(_lowerCamelCase, g[1][axis].split() ) ) ) __lowercase : int = np.array(_lowerCamelCase ) __lowercase : Tuple = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(_lowerCamelCase ): __lowercase : Optional[Any] = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: __lowercase : Any = np.array(list(map({"-": 0, "+": 1}.get, g[1][0].strip() ) ) ) __lowercase : Optional[int] = np.zeros( ( len(_lowerCamelCase ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(_lowerCamelCase ): __lowercase : Any = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=_lowerCamelCase, atom_mask=_lowerCamelCase, aatype=_lowerCamelCase, residue_index=np.arange(len(_lowerCamelCase ) ), b_factors=_lowerCamelCase, ) def snake_case__ ( _lowerCamelCase, _lowerCamelCase = 0 ) ->List[str]: """simple docstring""" __lowercase : List[str] = [] __lowercase : Tuple = prot.remark if remark is not None: pdb_headers.append(F'REMARK {remark}' ) __lowercase : str = prot.parents __lowercase : List[str] = prot.parents_chain_index if parents is not None and parents_chain_index is not None: __lowercase : Any = [p for i, p in zip(_lowerCamelCase, _lowerCamelCase ) if i == chain_id] if parents is None or len(_lowerCamelCase ) == 0: __lowercase : Dict = ["N/A"] pdb_headers.append(F'PARENT {" ".join(_lowerCamelCase )}' ) return pdb_headers def snake_case__ ( _lowerCamelCase, _lowerCamelCase ) ->str: """simple docstring""" __lowercase : List[str] = [] __lowercase : List[str] = pdb_str.split("\n" ) __lowercase : Optional[int] = prot.remark if remark is not None: out_pdb_lines.append(F'REMARK {remark}' ) __lowercase : List[List[str]] if prot.parents is not None and len(prot.parents ) > 0: __lowercase : Union[str, Any] = [] if prot.parents_chain_index is not None: __lowercase : Dict[str, List[str]] = {} for p, i in zip(prot.parents, prot.parents_chain_index ): parent_dict.setdefault(str(_lowerCamelCase ), [] ) parent_dict[str(_lowerCamelCase )].append(_lowerCamelCase ) __lowercase : Dict = max([int(_lowerCamelCase ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): __lowercase : int = parent_dict.get(str(_lowerCamelCase ), ["N/A"] ) parents_per_chain.append(_lowerCamelCase ) else: parents_per_chain.append(list(prot.parents ) ) else: __lowercase : Optional[Any] = [["N/A"]] def make_parent_line(_lowerCamelCase ) -> str: return F'PARENT {" ".join(_lowerCamelCase )}' out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) __lowercase : Union[str, Any] = 0 for i, l in enumerate(_lowerCamelCase ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(_lowerCamelCase ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(_lowerCamelCase ): __lowercase : Tuple = parents_per_chain[chain_counter] else: __lowercase : Tuple = ["N/A"] out_pdb_lines.append(make_parent_line(_lowerCamelCase ) ) return "\n".join(_lowerCamelCase ) def snake_case__ ( _lowerCamelCase ) ->str: """simple docstring""" __lowercase : Optional[Any] = residue_constants.restypes + ["X"] def res_atoa(_lowerCamelCase ) -> str: return residue_constants.restype_atoa.get(restypes[r], "UNK" ) __lowercase : int = residue_constants.atom_types __lowercase : List[str] = [] __lowercase : Optional[int] = prot.atom_mask __lowercase : List[Any] = prot.aatype __lowercase : List[str] = prot.atom_positions __lowercase : int = prot.residue_index.astype(np.intaa ) __lowercase : List[Any] = prot.b_factors __lowercase : str = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError("Invalid aatypes." ) __lowercase : int = get_pdb_headers(_lowerCamelCase ) if len(_lowerCamelCase ) > 0: pdb_lines.extend(_lowerCamelCase ) __lowercase : Union[str, Any] = aatype.shape[0] __lowercase : Union[str, Any] = 1 __lowercase : Optional[Any] = 0 __lowercase : Any = string.ascii_uppercase __lowercase : List[str] = None # Add all atom sites. for i in range(_lowerCamelCase ): __lowercase : List[Any] = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(_lowerCamelCase, atom_positions[i], atom_mask[i], b_factors[i] ): if mask < 0.5: continue __lowercase : Tuple = "ATOM" __lowercase : Optional[int] = atom_name if len(_lowerCamelCase ) == 4 else F' {atom_name}' __lowercase : Union[str, Any] = "" __lowercase : Union[str, Any] = "" __lowercase : Optional[Any] = 1.0_0 __lowercase : Optional[int] = atom_name[0] # Protein supports only C, N, O, S, this works. __lowercase : Union[str, Any] = "" __lowercase : Dict = "A" if chain_index is not None: __lowercase : Optional[int] = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! __lowercase : Optional[int] = ( F'{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}' F'{res_name_a:>3} {chain_tag:>1}' F'{residue_index[i]:>4}{insertion_code:>1} ' F'{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}' F'{occupancy:>6.2f}{b_factor:>6.2f} ' F'{element:>2}{charge:>2}' ) pdb_lines.append(_lowerCamelCase ) atom_index += 1 __lowercase : int = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: __lowercase : Dict = True __lowercase : List[Any] = chain_index[i + 1] if should_terminate: # Close the chain. __lowercase : Dict = "TER" __lowercase : List[Any] = ( F'{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}' ) pdb_lines.append(_lowerCamelCase ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(_lowerCamelCase, _lowerCamelCase ) ) pdb_lines.append("END" ) pdb_lines.append("" ) return "\n".join(_lowerCamelCase ) def snake_case__ ( _lowerCamelCase ) ->np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def snake_case__ ( _lowerCamelCase, _lowerCamelCase, _lowerCamelCase = None, _lowerCamelCase = None, _lowerCamelCase = None, _lowerCamelCase = None, _lowerCamelCase = None, ) ->Protein: """simple docstring""" return Protein( aatype=features["aatype"], atom_positions=result["final_atom_positions"], atom_mask=result["final_atom_mask"], residue_index=features["residue_index"] + 1, b_factors=b_factors if b_factors is not None else np.zeros_like(result["final_atom_mask"] ), chain_index=_lowerCamelCase, remark=_lowerCamelCase, parents=_lowerCamelCase, parents_chain_index=_lowerCamelCase, )
281
"""simple docstring""" def snake_case__ ( _lowerCamelCase, _lowerCamelCase ) ->int: """simple docstring""" return abs(_lowerCamelCase ) if a == 0 else greatest_common_divisor(b % a, _lowerCamelCase ) def snake_case__ ( _lowerCamelCase, _lowerCamelCase ) ->int: """simple docstring""" while y: # --> when y=0 then loop will terminate and return x as final GCD. __lowercase ,__lowercase : Any = y, x % y return abs(_lowerCamelCase ) def snake_case__ ( ) ->Optional[int]: """simple docstring""" try: __lowercase : Optional[int] = input("Enter two integers separated by comma (,): " ).split("," ) __lowercase : Optional[Any] = int(nums[0] ) __lowercase : str = int(nums[1] ) print( F'greatest_common_divisor({num_a}, {num_a}) = ' F'{greatest_common_divisor(_lowerCamelCase, _lowerCamelCase )}' ) print(F'By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(_lowerCamelCase, _lowerCamelCase )}' ) except (IndexError, UnboundLocalError, ValueError): print("Wrong input" ) if __name__ == "__main__": main()
281
1
from abc import ABC, abstractmethod from typing import List, Optional class snake_case_ ( __A ): '''simple docstring''' def __init__( self : int ) ->Optional[Any]: # test for the above condition self.test() def snake_case__( self : int ) ->str: snake_case_ = 0 snake_case_ = False while not completed: if counter == 1: self.reset() snake_case_ = self.advance() if not self.does_advance(_UpperCamelCase ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) snake_case_, snake_case_, snake_case_ = self.update(_UpperCamelCase ) counter += 1 if counter > 1_0_0_0_0: raise Exception('''update() does not fulfill the constraint.''' ) if self.remaining() != 0: raise Exception('''Custom Constraint is not defined correctly.''' ) @abstractmethod def snake_case__( self : List[Any] ) ->Union[str, Any]: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case__( self : int , _UpperCamelCase : int ) ->List[str]: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case__( self : Union[str, Any] , _UpperCamelCase : int ) ->int: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case__( self : int ) ->str: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case__( self : int ) ->str: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case__( self : List[str] , _UpperCamelCase : List[Any]=False ) ->List[Any]: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class snake_case_ ( __A ): '''simple docstring''' def __init__( self : Optional[Any] , _UpperCamelCase : List[int] ) ->Dict: super(_UpperCamelCase , self ).__init__() if not isinstance(_UpperCamelCase , _UpperCamelCase ) or len(_UpperCamelCase ) == 0: raise ValueError(f'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(_UpperCamelCase , _UpperCamelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(f'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' ) snake_case_ = token_ids snake_case_ = len(self.token_ids ) snake_case_ = -1 # the index of the currently fulfilled step snake_case_ = False def snake_case__( self : Dict ) ->Dict: if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def snake_case__( self : Union[str, Any] , _UpperCamelCase : int ) ->Optional[Any]: if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(_UpperCamelCase )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def snake_case__( self : Union[str, Any] , _UpperCamelCase : int ) ->int: if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(_UpperCamelCase )}''' ) snake_case_ = False snake_case_ = False snake_case_ = False if self.does_advance(_UpperCamelCase ): self.fulfilled_idx += 1 snake_case_ = True if self.fulfilled_idx == (self.seqlen - 1): snake_case_ = True snake_case_ = completed else: # failed to make progress. snake_case_ = True self.reset() return stepped, completed, reset def snake_case__( self : Any ) ->Union[str, Any]: snake_case_ = False snake_case_ = 0 def snake_case__( self : Union[str, Any] ) ->int: return self.seqlen - (self.fulfilled_idx + 1) def snake_case__( self : str , _UpperCamelCase : Union[str, Any]=False ) ->int: snake_case_ = PhrasalConstraint(self.token_ids ) if stateful: snake_case_ = self.seqlen snake_case_ = self.fulfilled_idx snake_case_ = self.completed return new_constraint class snake_case_ : '''simple docstring''' def __init__( self : List[str] , _UpperCamelCase : List[List[int]] , _UpperCamelCase : List[Any]=True ) ->str: snake_case_ = max([len(_UpperCamelCase ) for one in nested_token_ids] ) snake_case_ = {} for token_ids in nested_token_ids: snake_case_ = root for tidx, token_id in enumerate(_UpperCamelCase ): if token_id not in level: snake_case_ = {} snake_case_ = level[token_id] if no_subsets and self.has_subsets(_UpperCamelCase , _UpperCamelCase ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' f''' {nested_token_ids}.''' ) snake_case_ = root def snake_case__( self : Any , _UpperCamelCase : List[Any] ) ->Optional[Any]: snake_case_ = self.trie for current_token in current_seq: snake_case_ = start[current_token] snake_case_ = list(start.keys() ) return next_tokens def snake_case__( self : Optional[int] , _UpperCamelCase : int ) ->Optional[int]: snake_case_ = self.next_tokens(_UpperCamelCase ) return len(_UpperCamelCase ) == 0 def snake_case__( self : List[Any] , _UpperCamelCase : List[Any] ) ->Dict: snake_case_ = list(root.values() ) if len(_UpperCamelCase ) == 0: return 1 else: return sum([self.count_leaves(_UpperCamelCase ) for nn in next_nodes] ) def snake_case__( self : Union[str, Any] , _UpperCamelCase : Dict , _UpperCamelCase : Union[str, Any] ) ->int: snake_case_ = self.count_leaves(_UpperCamelCase ) return len(_UpperCamelCase ) != leaf_count class snake_case_ ( __A ): '''simple docstring''' def __init__( self : Optional[int] , _UpperCamelCase : List[List[int]] ) ->Any: super(_UpperCamelCase , self ).__init__() if not isinstance(_UpperCamelCase , _UpperCamelCase ) or len(_UpperCamelCase ) == 0: raise ValueError(f'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(_UpperCamelCase , _UpperCamelCase ) for token_ids in nested_token_ids ): raise ValueError(f'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' ) if any( any((not isinstance(_UpperCamelCase , _UpperCamelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( f'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' ) snake_case_ = DisjunctiveTrie(_UpperCamelCase ) snake_case_ = nested_token_ids snake_case_ = self.trie.max_height snake_case_ = [] snake_case_ = False def snake_case__( self : Optional[int] ) ->Optional[int]: snake_case_ = self.trie.next_tokens(self.current_seq ) if len(_UpperCamelCase ) == 0: return None else: return token_list def snake_case__( self : Dict , _UpperCamelCase : int ) ->Dict: if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(_UpperCamelCase )}''' ) snake_case_ = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def snake_case__( self : Tuple , _UpperCamelCase : int ) ->Optional[Any]: if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(_UpperCamelCase )}''' ) snake_case_ = False snake_case_ = False snake_case_ = False if self.does_advance(_UpperCamelCase ): self.current_seq.append(_UpperCamelCase ) snake_case_ = True else: snake_case_ = True self.reset() snake_case_ = self.trie.reached_leaf(self.current_seq ) snake_case_ = completed return stepped, completed, reset def snake_case__( self : List[Any] ) ->str: snake_case_ = False snake_case_ = [] def snake_case__( self : Tuple ) ->Dict: if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def snake_case__( self : Union[str, Any] , _UpperCamelCase : List[Any]=False ) ->Optional[int]: snake_case_ = DisjunctiveConstraint(self.token_ids ) if stateful: snake_case_ = self.seqlen snake_case_ = self.current_seq snake_case_ = self.completed return new_constraint class snake_case_ : '''simple docstring''' def __init__( self : Tuple , _UpperCamelCase : List[Constraint] ) ->str: snake_case_ = constraints # max # of steps required to fulfill a given constraint snake_case_ = max([c.seqlen for c in constraints] ) snake_case_ = len(_UpperCamelCase ) snake_case_ = False self.init_state() def snake_case__( self : Tuple ) ->Dict: snake_case_ = [] snake_case_ = None snake_case_ = [constraint.copy(stateful=_UpperCamelCase ) for constraint in self.constraints] def snake_case__( self : Tuple ) ->int: snake_case_ = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def snake_case__( self : Optional[Any] ) ->Optional[Any]: snake_case_ = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" snake_case_ = constraint.advance() if isinstance(_UpperCamelCase , _UpperCamelCase ): token_list.append(_UpperCamelCase ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): token_list.extend(_UpperCamelCase ) else: snake_case_ = self.inprogress_constraint.advance() if isinstance(_UpperCamelCase , _UpperCamelCase ): token_list.append(_UpperCamelCase ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): token_list.extend(_UpperCamelCase ) if len(_UpperCamelCase ) == 0: return None else: return token_list def snake_case__( self : Dict , _UpperCamelCase : Optional[List[int]] ) ->List[Any]: self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint snake_case_, snake_case_ = self.add(_UpperCamelCase ) # the entire list of constraints are fulfilled if self.completed: break def snake_case__( self : Optional[int] , _UpperCamelCase : int ) ->List[Any]: if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.''' ) snake_case_, snake_case_ = False, False if self.completed: snake_case_ = True snake_case_ = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state snake_case_, snake_case_, snake_case_ = self.inprogress_constraint.update(_UpperCamelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=_UpperCamelCase ) ) snake_case_ = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) snake_case_ = None if len(self.pending_constraints ) == 0: # we're done! snake_case_ = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(_UpperCamelCase ): snake_case_, snake_case_, snake_case_ = pending_constraint.update(_UpperCamelCase ) if not stepped: raise Exception( '''`constraint.update(token_id)` is not yielding incremental progress, ''' '''even though `constraint.does_advance(token_id)` is true.''' ) if complete: self.complete_constraints.append(_UpperCamelCase ) snake_case_ = None if not complete and stepped: snake_case_ = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". snake_case_ = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. snake_case_ = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def snake_case__( self : int , _UpperCamelCase : List[str]=True ) ->Optional[Any]: snake_case_ = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: snake_case_ = [ constraint.copy(stateful=_UpperCamelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: snake_case_ = self.inprogress_constraint.copy(stateful=_UpperCamelCase ) snake_case_ = [constraint.copy() for constraint in self.pending_constraints] return new_state
39
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE = { """configuration_megatron_bert""": ["""MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MegatronBertConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ """MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MegatronBertForCausalLM""", """MegatronBertForMaskedLM""", """MegatronBertForMultipleChoice""", """MegatronBertForNextSentencePrediction""", """MegatronBertForPreTraining""", """MegatronBertForQuestionAnswering""", """MegatronBertForSequenceClassification""", """MegatronBertForTokenClassification""", """MegatronBertModel""", """MegatronBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
388
0
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) a_ = logging.getLogger(__name__) def __SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" __UpperCamelCase = git.Repo(search_parent_directories=lowercase_ ) __UpperCamelCase = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), } with open(os.path.join(lowercase_ , '''git_log.json''' ) , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=4 ) def __SCREAMING_SNAKE_CASE ( lowercase_ ) -> Optional[int]: """simple docstring""" if params.n_gpu <= 0: __UpperCamelCase = 0 __UpperCamelCase = -1 __UpperCamelCase = True __UpperCamelCase = False return assert torch.cuda.is_available() logger.info('''Initializing GPUs''' ) if params.n_gpu > 1: assert params.local_rank != -1 __UpperCamelCase = int(os.environ['''WORLD_SIZE'''] ) __UpperCamelCase = int(os.environ['''N_GPU_NODE'''] ) __UpperCamelCase = int(os.environ['''RANK'''] ) # number of nodes / node ID __UpperCamelCase = params.world_size // params.n_gpu_per_node __UpperCamelCase = params.global_rank // params.n_gpu_per_node __UpperCamelCase = True assert params.n_nodes == int(os.environ['''N_NODES'''] ) assert params.node_id == int(os.environ['''NODE_RANK'''] ) # local job (single GPU) else: assert params.local_rank == -1 __UpperCamelCase = 1 __UpperCamelCase = 0 __UpperCamelCase = 0 __UpperCamelCase = 0 __UpperCamelCase = 1 __UpperCamelCase = 1 __UpperCamelCase = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode __UpperCamelCase = params.node_id == 0 and params.local_rank == 0 __UpperCamelCase = params.n_nodes > 1 # summary __UpperCamelCase = F"--- Global rank: {params.global_rank} - " logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes ) logger.info(PREFIX + '''Node ID : %i''' % params.node_id ) logger.info(PREFIX + '''Local rank : %i''' % params.local_rank ) logger.info(PREFIX + '''World size : %i''' % params.world_size ) logger.info(PREFIX + '''GPUs per node : %i''' % params.n_gpu_per_node ) logger.info(PREFIX + '''Master : %s''' % str(params.is_master ) ) logger.info(PREFIX + '''Multi-node : %s''' % str(params.multi_node ) ) logger.info(PREFIX + '''Multi-GPU : %s''' % str(params.multi_gpu ) ) logger.info(PREFIX + '''Hostname : %s''' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('''Initializing PyTorch distributed''' ) torch.distributed.init_process_group( init_method='''env://''' , backend='''nccl''' , ) def __SCREAMING_SNAKE_CASE ( lowercase_ ) -> Optional[int]: """simple docstring""" np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
375
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class _lowerCamelCase ( _SCREAMING_SNAKE_CASE ): """simple docstring""" lowerCAmelCase__ : Any = "" lowerCAmelCase__ : Any = "hf-legacy" # "hf://"" is reserved for hffs def __init__( self : str , snake_case : Optional[DatasetInfo] = None , snake_case : Optional[str] = None , **snake_case : List[Any] , ): super().__init__(self , **snake_case ) __UpperCamelCase = repo_info __UpperCamelCase = token __UpperCamelCase = None def snake_case ( self : List[Any] ): if self.dir_cache is None: __UpperCamelCase = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes __UpperCamelCase = { '''name''': hf_file.rfilename, '''size''': None, '''type''': '''file''', } self.dir_cache.update( { str(snake_case ): {'''name''': str(snake_case ), '''size''': None, '''type''': '''directory'''} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def snake_case ( self : Dict , snake_case : str , snake_case : str = "rb" , **snake_case : Union[str, Any] , ): if not isinstance(self.repo_info , snake_case ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) __UpperCamelCase = hf_hub_url(self.repo_info.id , snake_case , revision=self.repo_info.sha ) return fsspec.open( snake_case , mode=snake_case , headers=get_authentication_headers_for_url(snake_case , use_auth_token=self.token ) , client_kwargs={'''trust_env''': True} , ).open() def snake_case ( self : Optional[Any] , snake_case : Tuple , **snake_case : List[Any] ): self._get_dirs() __UpperCamelCase = self._strip_protocol(snake_case ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(snake_case ) def snake_case ( self : List[str] , snake_case : int , snake_case : Tuple=False , **snake_case : Dict ): self._get_dirs() __UpperCamelCase = PurePosixPath(path.strip('''/''' ) ) __UpperCamelCase = {} for p, f in self.dir_cache.items(): __UpperCamelCase = PurePosixPath(p.strip('''/''' ) ) __UpperCamelCase = p.parent if root == path: __UpperCamelCase = f __UpperCamelCase = list(paths.values() ) if detail: return out else: return sorted(f['''name'''] for f in out )
375
1
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def _snake_case (__lowercase): UpperCamelCase_ = FileLock(str(tmpdir / 'foo.lock')) UpperCamelCase_ = FileLock(str(tmpdir / 'foo.lock')) UpperCamelCase_ = 0.01 with locka.acquire(): with pytest.raises(__lowercase): UpperCamelCase_ = time.time() locka.acquire(__lowercase) assert time.time() - _start > timeout def _snake_case (__lowercase): UpperCamelCase_ = 'a' * 1000 + '.lock' UpperCamelCase_ = FileLock(str(tmpdir / filename)) assert locka._lock_file.endswith('.lock') assert not locka._lock_file.endswith(__lowercase) assert len(os.path.basename(locka._lock_file)) <= 255 UpperCamelCase_ = FileLock(tmpdir / filename) with locka.acquire(): with pytest.raises(__lowercase): locka.acquire(0)
23
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A : str = 3_84 if "tiny" in model_name: __A : Union[str, Any] = [3, 3, 9, 3] __A : Any = [96, 1_92, 3_84, 7_68] if "small" in model_name: __A : str = [3, 3, 27, 3] __A : Dict = [96, 1_92, 3_84, 7_68] if "base" in model_name: __A : Any = [3, 3, 27, 3] __A : str = [1_28, 2_56, 5_12, 10_24] __A : Optional[Any] = 5_12 if "large" in model_name: __A : Dict = [3, 3, 27, 3] __A : Any = [1_92, 3_84, 7_68, 15_36] __A : str = 7_68 if "xlarge" in model_name: __A : int = [3, 3, 27, 3] __A : Optional[Any] = [2_56, 5_12, 10_24, 20_48] __A : Optional[Any] = 10_24 # set label information __A : int = 1_50 __A : int = 'huggingface/label-files' __A : Any = 'ade20k-id2label.json' __A : int = json.load(open(hf_hub_download(a , a , repo_type='dataset' ) , 'r' ) ) __A : List[Any] = {int(a ): v for k, v in idalabel.items()} __A : List[Any] = {v: k for k, v in idalabel.items()} __A : int = ConvNextConfig( depths=a , hidden_sizes=a , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) __A : Tuple = UperNetConfig( backbone_config=a , auxiliary_in_channels=a , num_labels=a , idalabel=a , labelaid=a , ) return config def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : str = [] # fmt: off # stem rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight') ) rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias') ) rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight') ) rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.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}.{j}.gamma""", F"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.depthwise_conv.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.depthwise_conv.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.norm.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.norm.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""") ) if i > 0: rename_keys.append((F"""backbone.downsample_layers.{i}.0.weight""", F"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.0.bias""", F"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.1.weight""", F"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.1.bias""", F"""backbone.encoder.stages.{i}.downsampling_layer.1.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 _SCREAMING_SNAKE_CASE ( a , a , a ) -> Tuple: __A : int = dct.pop(a ) __A : int = val def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Any: __A : List[Any] = { 'upernet-convnext-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth', 'upernet-convnext-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth', 'upernet-convnext-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth', 'upernet-convnext-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth', 'upernet-convnext-xlarge': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth', } __A : List[str] = model_name_to_url[model_name] __A : Tuple = torch.hub.load_state_dict_from_url(a , map_location='cpu' )['state_dict'] __A : List[str] = get_upernet_config(a ) __A : Dict = UperNetForSemanticSegmentation(a ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __A : str = state_dict.pop(a ) if "bn" in key: __A : str = key.replace('bn' , 'batch_norm' ) __A : Optional[int] = val # rename keys __A : str = create_rename_keys(a ) for src, dest in rename_keys: rename_key(a , a , a ) model.load_state_dict(a ) # verify on image __A : Union[str, Any] = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' __A : str = Image.open(requests.get(a , stream=a ).raw ).convert('RGB' ) __A : List[Any] = SegformerImageProcessor() __A : str = processor(a , return_tensors='pt' ).pixel_values with torch.no_grad(): __A : Tuple = model(a ) if model_name == "upernet-convnext-tiny": __A : Optional[Any] = torch.tensor( [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]] ) elif model_name == "upernet-convnext-small": __A : Dict = torch.tensor( [[-8.8_236, -8.8_236, -8.6_771], [-8.8_236, -8.8_236, -8.6_771], [-8.7_638, -8.7_638, -8.6_240]] ) elif model_name == "upernet-convnext-base": __A : List[Any] = torch.tensor( [[-8.8_558, -8.8_558, -8.6_905], [-8.8_558, -8.8_558, -8.6_905], [-8.7_669, -8.7_669, -8.6_021]] ) elif model_name == "upernet-convnext-large": __A : Union[str, Any] = torch.tensor( [[-8.6_660, -8.6_660, -8.6_210], [-8.6_660, -8.6_660, -8.6_210], [-8.6_310, -8.6_310, -8.5_964]] ) elif model_name == "upernet-convnext-xlarge": __A : List[Any] = torch.tensor( [[-8.4_980, -8.4_980, -8.3_977], [-8.4_980, -8.4_980, -8.3_977], [-8.4_379, -8.4_379, -8.3_412]] ) print('Logits:' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , a , 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(a ) print(F"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(a ) 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__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''upernet-convnext-tiny''', type=str, choices=[F"""upernet-convnext-{size}""" for size in ['''tiny''', '''small''', '''base''', '''large''', '''xlarge''']], help='''Name of the ConvNext 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.''' ) UpperCAmelCase : Optional[int] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
239
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase = {'''configuration_wavlm''': ['''WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WavLMConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ '''WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''WavLMForAudioFrameClassification''', '''WavLMForCTC''', '''WavLMForSequenceClassification''', '''WavLMForXVector''', '''WavLMModel''', '''WavLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
102
def __lowercase ( UpperCAmelCase__ = 10 , UpperCAmelCase__ = 1_000 , UpperCAmelCase__ = True ): """simple docstring""" assert ( isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)' ) return min_val if option else max_val def __lowercase ( UpperCAmelCase__ , UpperCAmelCase__ ): """simple docstring""" return int((number_a + number_a) / 2 ) def __lowercase ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ): """simple docstring""" assert ( isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)' ) if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value' ) def answer(UpperCAmelCase__ ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...' ) __lowerCAmelCase = lower __lowerCAmelCase = higher __lowerCAmelCase = [] while True: __lowerCAmelCase = get_avg(UpperCAmelCase__ , UpperCAmelCase__ ) last_numbers.append(UpperCAmelCase__ ) if answer(UpperCAmelCase__ ) == "low": __lowerCAmelCase = number elif answer(UpperCAmelCase__ ) == "high": __lowerCAmelCase = number else: break print(F"""guess the number : {last_numbers[-1]}""" ) print(F"""details : {last_numbers!s}""" ) def __lowercase ( ): """simple docstring""" __lowerCAmelCase = int(input('Enter lower value : ' ).strip() ) __lowerCAmelCase = int(input('Enter high value : ' ).strip() ) __lowerCAmelCase = int(input('Enter value to guess : ' ).strip() ) guess_the_number(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if __name__ == "__main__": main()
102
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) __UpperCAmelCase : int = { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json", "google/bigbird-roberta-large": "https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json", "google/bigbird-base-trivia-itc": "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class _snake_case ( _A ): _A = 'big_bird' def __init__( self ,UpperCamelCase=50_358 ,UpperCamelCase=768 ,UpperCamelCase=12 ,UpperCamelCase=12 ,UpperCamelCase=3_072 ,UpperCamelCase="gelu_new" ,UpperCamelCase=0.1 ,UpperCamelCase=0.1 ,UpperCamelCase=4_096 ,UpperCamelCase=2 ,UpperCamelCase=0.02 ,UpperCamelCase=1E-12 ,UpperCamelCase=True ,UpperCamelCase=0 ,UpperCamelCase=1 ,UpperCamelCase=2 ,UpperCamelCase=66 ,UpperCamelCase="block_sparse" ,UpperCamelCase=True ,UpperCamelCase=False ,UpperCamelCase=64 ,UpperCamelCase=3 ,UpperCamelCase=None ,**UpperCamelCase ,) -> Tuple: super().__init__( pad_token_id=UpperCamelCase ,bos_token_id=UpperCamelCase ,eos_token_id=UpperCamelCase ,sep_token_id=UpperCamelCase ,**UpperCamelCase ,) snake_case__ :Union[str, Any] = vocab_size snake_case__ :Dict = max_position_embeddings snake_case__ :Tuple = hidden_size snake_case__ :int = num_hidden_layers snake_case__ :Optional[Any] = num_attention_heads snake_case__ :Optional[Any] = intermediate_size snake_case__ :List[str] = hidden_act snake_case__ :List[Any] = hidden_dropout_prob snake_case__ :Union[str, Any] = attention_probs_dropout_prob snake_case__ :Dict = initializer_range snake_case__ :Optional[Any] = type_vocab_size snake_case__ :Any = layer_norm_eps snake_case__ :List[Any] = use_cache snake_case__ :Union[str, Any] = rescale_embeddings snake_case__ :Tuple = attention_type snake_case__ :str = use_bias snake_case__ :Dict = block_size snake_case__ :Optional[Any] = num_random_blocks snake_case__ :str = classifier_dropout class _snake_case ( _A ): @property def lowerCAmelCase_ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": snake_case__ :Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: snake_case__ :Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
241
import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def lowercase_ ( __snake_case : Optional[Any] ) -> List[Any]: '''simple docstring''' if ( (cp >= 0X4_e00 and cp <= 0X9_fff) or (cp >= 0X3_400 and cp <= 0X4_dbf) # or (cp >= 0X20_000 and cp <= 0X2a_6df) # or (cp >= 0X2a_700 and cp <= 0X2b_73f) # or (cp >= 0X2b_740 and cp <= 0X2b_81f) # or (cp >= 0X2b_820 and cp <= 0X2c_eaf) # or (cp >= 0Xf_900 and cp <= 0Xf_aff) or (cp >= 0X2f_800 and cp <= 0X2f_a1f) # ): # return True return False def lowercase_ ( __snake_case : str ) -> Tuple: '''simple docstring''' for char in word: snake_case__ :Dict = ord(__snake_case ) if not _is_chinese_char(__snake_case ): return 0 return 1 def lowercase_ ( __snake_case : List[str] ) -> Any: '''simple docstring''' snake_case__ :Optional[int] = set() for token in tokens: snake_case__ :Dict = len(__snake_case ) > 1 and is_chinese(__snake_case ) if chinese_word: word_set.add(__snake_case ) snake_case__ :Tuple = list(__snake_case ) return word_list def lowercase_ ( __snake_case : List[str] , __snake_case : set() ) -> int: '''simple docstring''' if not chinese_word_set: return bert_tokens snake_case__ :List[str] = max([len(__snake_case ) for w in chinese_word_set] ) snake_case__ :str = bert_tokens snake_case__ , snake_case__ :Dict = 0, len(__snake_case ) while start < end: snake_case__ :Any = True if is_chinese(bert_word[start] ): snake_case__ :Union[str, Any] = min(end - start , __snake_case ) for i in range(__snake_case , 1 , -1 ): snake_case__ :str = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): snake_case__ :int = "##" + bert_word[j] snake_case__ :str = start + i snake_case__ :Union[str, Any] = False break if single_word: start += 1 return bert_word def lowercase_ ( __snake_case : List[str] , __snake_case : LTP , __snake_case : BertTokenizer ) -> List[Any]: '''simple docstring''' snake_case__ :Union[str, Any] = [] for i in range(0 , len(__snake_case ) , 1_00 ): snake_case__ :Any = ltp_tokenizer.pipeline(lines[i : i + 1_00] , tasks=["cws"] ).cws snake_case__ :Optional[Any] = [get_chinese_word(__snake_case ) for r in res] ltp_res.extend(__snake_case ) assert len(__snake_case ) == len(__snake_case ) snake_case__ :int = [] for i in range(0 , len(__snake_case ) , 1_00 ): snake_case__ :str = bert_tokenizer(lines[i : i + 1_00] , add_special_tokens=__snake_case , truncation=__snake_case , max_length=5_12 ) bert_res.extend(res["input_ids"] ) assert len(__snake_case ) == len(__snake_case ) snake_case__ :Union[str, Any] = [] for input_ids, chinese_word in zip(__snake_case , __snake_case ): snake_case__ :Dict = [] for id in input_ids: snake_case__ :Tuple = bert_tokenizer._convert_id_to_token(__snake_case ) input_tokens.append(__snake_case ) snake_case__ :Tuple = add_sub_symbol(__snake_case , __snake_case ) snake_case__ :Dict = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__snake_case ): if token[:2] == "##": snake_case__ :Optional[Any] = token[2:] # save chinese tokens' pos if len(__snake_case ) == 1 and _is_chinese_char(ord(__snake_case ) ): ref_id.append(__snake_case ) ref_ids.append(__snake_case ) assert len(__snake_case ) == len(__snake_case ) return ref_ids def lowercase_ ( __snake_case : List[str] ) -> Optional[Any]: '''simple docstring''' with open(args.file_name , "r" , encoding="utf-8" ) as f: snake_case__ :Optional[int] = f.readlines() snake_case__ :Union[str, Any] = [line.strip() for line in data if len(__snake_case ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' snake_case__ :Optional[int] = LTP(args.ltp ) # faster in GPU device snake_case__ :Optional[int] = BertTokenizer.from_pretrained(args.bert ) snake_case__ :str = prepare_ref(__snake_case , __snake_case , __snake_case ) with open(args.save_path , "w" , encoding="utf-8" ) as f: snake_case__ :List[str] = [json.dumps(__snake_case ) + "\n" for ref in ref_ids] f.writelines(__snake_case ) if __name__ == "__main__": __UpperCAmelCase : Optional[int] = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", required=False, type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", required=False, type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path", ) parser.add_argument( "--bert", required=False, type=str, default="./resources/robert", help="resources for Bert tokenizer", ) parser.add_argument( "--save_path", required=False, type=str, default="./resources/ref.txt", help="path to save res", ) __UpperCAmelCase : str = parser.parse_args() main(args)
241
1
"""simple docstring""" import numpy as np def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = 1E-1_2 ,lowerCAmelCase__ = 100 ,): assert np.shape(lowerCAmelCase__ )[0] == np.shape(lowerCAmelCase__ )[1] # Ensure proper dimensionality. assert np.shape(lowerCAmelCase__ )[0] == np.shape(lowerCAmelCase__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(lowerCAmelCase__ ) == np.iscomplexobj(lowerCAmelCase__ ) A__ = np.iscomplexobj(lowerCAmelCase__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(lowerCAmelCase__ ,input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. A__ = False A__ = 0 A__ = 0 A__ = 1E1_2 while not convergence: # Multiple matrix by the vector. A__ = np.dot(lowerCAmelCase__ ,lowerCAmelCase__ ) # Normalize the resulting output vector. A__ = w / np.linalg.norm(lowerCAmelCase__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) A__ = vector.conj().T if is_complex else vector.T A__ = np.dot(lowerCAmelCase__ ,np.dot(lowerCAmelCase__ ,lowerCAmelCase__ ) ) # Check convergence. A__ = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: A__ = True A__ = lambda_ if is_complex: A__ = np.real(lambda_ ) return lambda_, vector def __lowerCamelCase ( ): A__ = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) A__ = np.array([41, 4, 20] ) A__ = real_input_matrix.astype(np.complexaaa ) A__ = np.triu(1j * complex_input_matrix ,1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T A__ = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": A__ = real_input_matrix A__ = real_vector elif problem_type == "complex": A__ = complex_input_matrix A__ = complex_vector # Our implementation. A__ , A__ = power_iteration(lowerCAmelCase__ ,lowerCAmelCase__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). A__ , A__ = np.linalg.eigh(lowerCAmelCase__ ) # Last eigenvalue is the maximum one. A__ = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. A__ = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(lowerCAmelCase__ ) - np.abs(lowerCAmelCase__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
554
"""simple docstring""" from __future__ import annotations def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ = None ): A__ = word_bank or [] # create a table A__ = len(lowerCAmelCase__ ) + 1 A__ = [] for _ in range(lowerCAmelCase__ ): table.append([] ) # seed value A__ = [[]] # because empty string has empty combination # iterate through the indices for i in range(lowerCAmelCase__ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(lowerCAmelCase__ )] == word: A__ = [ [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(lowerCAmelCase__ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(lowerCAmelCase__ )]: combination.reverse() return table[len(lowerCAmelCase__ )] 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'''], ) )
554
1
def _lowercase( __a : list ): if len(_UpperCAmelCase ) < 2: return collection def circle_sort_util(__a : list , __a : int , __a : int ) -> bool: a__ =False if low == high: return swapped a__ =low a__ =high while left < right: if collection[left] > collection[right]: a__ , a__ =( collection[right], collection[left], ) a__ =True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: a__ , a__ =( collection[right + 1], collection[left], ) a__ =True a__ =low + int((high - low) / 2 ) a__ =circle_sort_util(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) a__ =circle_sort_util(_UpperCAmelCase , mid + 1 , _UpperCAmelCase ) return swapped or left_swap or right_swap a__ =True while is_not_sorted is True: a__ =circle_sort_util(_UpperCAmelCase , 0 , len(_UpperCAmelCase ) - 1 ) return collection if __name__ == "__main__": _lowerCAmelCase: Optional[Any] = input('Enter numbers separated by a comma:\n').strip() _lowerCAmelCase: List[str] = [int(item) for item in user_input.split(',')] print(circle_sort(unsorted))
20
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Any = 16 a__ : str = 32 def UpperCAmelCase_ ( _UpperCAmelCase :Accelerator , _UpperCAmelCase :int = 16 ) -> int: '''simple docstring''' A_ = AutoTokenizer.from_pretrained('''bert-base-cased''' ) A_ = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(_UpperCAmelCase :Optional[Any] ): # max_length=None => use the model max length (it's actually the default) A_ = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): A_ = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A_ = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(_UpperCAmelCase :List[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. A_ = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": A_ = 16 elif accelerator.mixed_precision != "no": A_ = 8 else: A_ = None return tokenizer.pad( _UpperCAmelCase , padding='''longest''' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='''pt''' , ) # Instantiate dataloaders. A_ = DataLoader( tokenized_datasets['''train'''] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) A_ = DataLoader( tokenized_datasets['''validation'''] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a__ : Optional[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase_ ( _UpperCAmelCase :List[str] , _UpperCAmelCase :Dict ) -> Dict: '''simple docstring''' if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , _UpperCAmelCase ) == "1": A_ = 2 # New Code # A_ = int(args.gradient_accumulation_steps ) A_ = int(args.local_sgd_steps ) # Initialize accelerator A_ = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=_UpperCAmelCase ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError('''LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)''' ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A_ = config['''lr'''] A_ = int(config['''num_epochs'''] ) A_ = int(config['''seed'''] ) A_ = int(config['''batch_size'''] ) A_ = evaluate.load('''glue''' , '''mrpc''' ) set_seed(_UpperCAmelCase ) A_ , A_ = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A_ = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=_UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). A_ = model.to(accelerator.device ) # Instantiate optimizer A_ = AdamW(params=model.parameters() , lr=_UpperCAmelCase ) # Instantiate scheduler A_ = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A_ , A_ , A_ , A_ , A_ = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Now we train the model for epoch in range(_UpperCAmelCase ): model.train() with LocalSGD( accelerator=_UpperCAmelCase , model=_UpperCAmelCase , local_sgd_steps=_UpperCAmelCase , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(_UpperCAmelCase ): A_ = model(**_UpperCAmelCase ) A_ = output.loss accelerator.backward(_UpperCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A_ = model(**_UpperCAmelCase ) A_ = outputs.logits.argmax(dim=-1 ) A_ , A_ = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) A_ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' , _UpperCAmelCase ) def UpperCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' A_ = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) # New Code # parser.add_argument( '''--gradient_accumulation_steps''' , type=_UpperCAmelCase , default=1 , help='''The number of minibatches to be ran before gradients are accumulated.''' , ) parser.add_argument( '''--local_sgd_steps''' , type=_UpperCAmelCase , default=8 , help='''Number of local SGD steps or None to disable local SGD''' ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) A_ = parser.parse_args() A_ = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": main()
188
0
def lowercase_ ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" snake_case__ : Dict =[0 for i in range(len(_A ) )] # initialize interval's left pointer and right pointer snake_case__ : List[str] =0, 0 for i in range(1 , len(_A ) ): # case when current index is inside the interval if i <= right_pointer: snake_case__ : Dict =min(right_pointer - i + 1 , z_result[i - left_pointer] ) snake_case__ : Tuple =min_edge while go_next(_A , _A , _A ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: snake_case__ : Any =i, i + z_result[i] - 1 return z_result def lowercase_ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : str ): """simple docstring""" return i + z_result[i] < len(_A ) and s[z_result[i]] == s[i + z_result[i]] def lowercase_ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str ): """simple docstring""" snake_case__ : int =0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string snake_case__ : Optional[int] =z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(_A ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
705
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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { '''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 ( __UpperCamelCase ): """simple docstring""" lowerCAmelCase__ ='''mobilenet_v2''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=224 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=6 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="relu6" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.8 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=0.001 , __SCREAMING_SNAKE_CASE=255 , **__SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) snake_case__ : Optional[int] =num_channels snake_case__ : Optional[int] =image_size snake_case__ : int =depth_multiplier snake_case__ : Optional[Any] =depth_divisible_by snake_case__ : Any =min_depth snake_case__ : Tuple =expand_ratio snake_case__ : int =output_stride snake_case__ : List[Any] =first_layer_is_expansion snake_case__ : Union[str, Any] =finegrained_output snake_case__ : int =hidden_act snake_case__ : Tuple =tf_padding snake_case__ : List[Any] =classifier_dropout_prob snake_case__ : Dict =initializer_range snake_case__ : List[str] =layer_norm_eps snake_case__ : str =semantic_loss_ignore_index class _lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" lowerCAmelCase__ =version.parse('''1.11''' ) @property def UpperCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def UpperCAmelCase ( self ) -> 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 UpperCAmelCase ( self ) -> float: """simple docstring""" return 1e-4
408
0
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 SCREAMING_SNAKE_CASE = logging.get_logger(__name__) @add_end_docstrings(lowercase__ ) class lowerCamelCase ( lowercase__ ): '''simple docstring''' def __init__( self , **lowerCAmelCase ): 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 A__ ( self , **lowerCAmelCase ): UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} # preprocess args if "points_per_batch" in kwargs: UpperCAmelCase_ = kwargs["points_per_batch"] if "points_per_crop" in kwargs: UpperCAmelCase_ = kwargs["points_per_crop"] if "crops_n_layers" in kwargs: UpperCAmelCase_ = kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: UpperCAmelCase_ = kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: UpperCAmelCase_ = kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: UpperCAmelCase_ = kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: UpperCAmelCase_ = kwargs["stability_score_offset"] if "mask_threshold" in kwargs: UpperCAmelCase_ = kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: UpperCAmelCase_ = kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: UpperCAmelCase_ = kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: UpperCAmelCase_ = kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: UpperCAmelCase_ = kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , lowerCAmelCase , *lowerCAmelCase , lowerCAmelCase=None , lowerCAmelCase=None , **lowerCAmelCase ): return super().__call__(lowerCAmelCase , *lowerCAmelCase , num_workers=lowerCAmelCase , batch_size=lowerCAmelCase , **lowerCAmelCase ) def A__ ( self , lowerCAmelCase , lowerCAmelCase=64 , lowerCAmelCase = 0 , lowerCAmelCase = 512 / 1500 , lowerCAmelCase = 32 , lowerCAmelCase = 1 , ): UpperCAmelCase_ = load_image(lowerCAmelCase ) UpperCAmelCase_ = self.image_processor.size["longest_edge"] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.image_processor.generate_crop_boxes( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase_ = self.image_processor(images=lowerCAmelCase , return_tensors="pt" ) with self.device_placement(): if self.framework == "pt": UpperCAmelCase_ = self.get_inference_context() with inference_context(): UpperCAmelCase_ = self._ensure_tensor_on_device(lowerCAmelCase , device=self.device ) UpperCAmelCase_ = self.model.get_image_embeddings(model_inputs.pop("pixel_values" ) ) UpperCAmelCase_ = image_embeddings UpperCAmelCase_ = grid_points.shape[1] UpperCAmelCase_ = 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 ): UpperCAmelCase_ = grid_points[:, i : i + points_per_batch, :, :] UpperCAmelCase_ = input_labels[:, i : i + points_per_batch] UpperCAmelCase_ = 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 A__ ( self , lowerCAmelCase , lowerCAmelCase=0.88 , lowerCAmelCase=0.95 , lowerCAmelCase=0 , lowerCAmelCase=1 , ): UpperCAmelCase_ = model_inputs.pop("input_boxes" ) UpperCAmelCase_ = model_inputs.pop("is_last" ) UpperCAmelCase_ = model_inputs.pop("original_sizes" ).tolist() UpperCAmelCase_ = model_inputs.pop("reshaped_input_sizes" ).tolist() UpperCAmelCase_ = self.model(**lowerCAmelCase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks UpperCAmelCase_ = model_outputs["pred_masks"] UpperCAmelCase_ = self.image_processor.post_process_masks( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , binarize=lowerCAmelCase ) UpperCAmelCase_ = model_outputs["iou_scores"] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = 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 A__ ( self , lowerCAmelCase , lowerCAmelCase=False , lowerCAmelCase=False , lowerCAmelCase=0.7 , ): UpperCAmelCase_ = [] UpperCAmelCase_ = [] UpperCAmelCase_ = [] 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" ) ) UpperCAmelCase_ = torch.cat(lowerCAmelCase ) UpperCAmelCase_ = torch.cat(lowerCAmelCase ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.image_processor.post_process_for_mask_generation( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase_ = defaultdict(lowerCAmelCase ) for output in model_outputs: for k, v in output.items(): extra[k].append(lowerCAmelCase ) UpperCAmelCase_ = {} if output_rle_mask: UpperCAmelCase_ = rle_mask if output_bboxes_mask: UpperCAmelCase_ = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
579
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class lowerCamelCase : '''simple docstring''' def __init__( self , lowerCAmelCase = None , lowerCAmelCase = None , lowerCAmelCase=None , lowerCAmelCase=None ): if not conversation_id: UpperCAmelCase_ = uuid.uuida() if past_user_inputs is None: UpperCAmelCase_ = [] if generated_responses is None: UpperCAmelCase_ = [] UpperCAmelCase_ = conversation_id UpperCAmelCase_ = past_user_inputs UpperCAmelCase_ = generated_responses UpperCAmelCase_ = text def __eq__( self , lowerCAmelCase ): if not isinstance(lowerCAmelCase , lowerCAmelCase ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def A__ ( self , lowerCAmelCase , lowerCAmelCase = False ): if self.new_user_input: if overwrite: logger.warning( f'''User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten ''' f'''with: "{text}".''' ) UpperCAmelCase_ = text else: logger.warning( f'''User input added while unprocessed input was existing: "{self.new_user_input}" new input ''' f'''ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input''' ) else: UpperCAmelCase_ = text def A__ ( self ): if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) UpperCAmelCase_ = None def A__ ( self , lowerCAmelCase ): self.generated_responses.append(lowerCAmelCase ) def A__ ( self ): for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self ): UpperCAmelCase_ = f'''Conversation id: {self.uuid} \n''' for is_user, text in self.iter_texts(): UpperCAmelCase_ = "user" if is_user else "bot" output += f'''{name} >> {text} \n''' return output @add_end_docstrings( lowercase__, r'\n min_length_for_response (`int`, *optional*, defaults to 32):\n The minimum length (in number of tokens) for a response.\n minimum_tokens (`int`, *optional*, defaults to 10):\n The minimum length of tokens to leave for a response.\n ', ) class lowerCamelCase ( lowercase__ ): '''simple docstring''' def __init__( self , *lowerCAmelCase , **lowerCAmelCase ): super().__init__(*lowerCAmelCase , **lowerCAmelCase ) if self.tokenizer.pad_token_id is None: UpperCAmelCase_ = self.tokenizer.eos_token def A__ ( self , lowerCAmelCase=None , lowerCAmelCase=None , lowerCAmelCase=None , **lowerCAmelCase ): UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} if min_length_for_response is not None: UpperCAmelCase_ = min_length_for_response if minimum_tokens is not None: UpperCAmelCase_ = minimum_tokens if "max_length" in generate_kwargs: UpperCAmelCase_ = generate_kwargs["max_length"] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: UpperCAmelCase_ = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(lowerCAmelCase ) return preprocess_params, forward_params, postprocess_params def __call__( self , lowerCAmelCase , lowerCAmelCase=0 , **lowerCAmelCase ): UpperCAmelCase_ = super().__call__(lowerCAmelCase , num_workers=lowerCAmelCase , **lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) and len(lowerCAmelCase ) == 1: return outputs[0] return outputs def A__ ( self , lowerCAmelCase , lowerCAmelCase=32 ): if not isinstance(lowerCAmelCase , lowerCAmelCase ): raise ValueError("ConversationalPipeline, expects Conversation as inputs" ) if conversation.new_user_input is None: raise ValueError( f'''Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. ''' "Add user inputs with the conversation's `add_user_input` method" ) if hasattr(self.tokenizer , "_build_conversation_input_ids" ): UpperCAmelCase_ = self.tokenizer._build_conversation_input_ids(lowerCAmelCase ) else: # If the tokenizer cannot handle conversations, we default to only the old version UpperCAmelCase_ = self._legacy_parse_and_tokenize(lowerCAmelCase ) if self.framework == "pt": UpperCAmelCase_ = torch.LongTensor([input_ids] ) elif self.framework == "tf": UpperCAmelCase_ = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def A__ ( self , lowerCAmelCase , lowerCAmelCase=10 , **lowerCAmelCase ): UpperCAmelCase_ = generate_kwargs.get("max_length" , self.model.config.max_length ) UpperCAmelCase_ = model_inputs["input_ids"].shape[1] if max_length - minimum_tokens < n: logger.warning(f'''Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})''' ) UpperCAmelCase_ = max_length - minimum_tokens UpperCAmelCase_ = model_inputs["input_ids"][:, -trim:] if "attention_mask" in model_inputs: UpperCAmelCase_ = model_inputs["attention_mask"][:, -trim:] UpperCAmelCase_ = model_inputs.pop("conversation" ) UpperCAmelCase_ = max_length UpperCAmelCase_ = self.model.generate(**lowerCAmelCase , **lowerCAmelCase ) if self.model.config.is_encoder_decoder: UpperCAmelCase_ = 1 else: UpperCAmelCase_ = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def A__ ( self , lowerCAmelCase , lowerCAmelCase=True ): UpperCAmelCase_ = model_outputs["output_ids"] UpperCAmelCase_ = self.tokenizer.decode( output_ids[0] , skip_special_tokens=lowerCAmelCase , clean_up_tokenization_spaces=lowerCAmelCase , ) UpperCAmelCase_ = model_outputs["conversation"] conversation.mark_processed() conversation.append_response(lowerCAmelCase ) return conversation def A__ ( self , lowerCAmelCase ): UpperCAmelCase_ = self.tokenizer.eos_token_id UpperCAmelCase_ = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) ) if len(lowerCAmelCase ) > self.tokenizer.model_max_length: UpperCAmelCase_ = input_ids[-self.tokenizer.model_max_length :] return input_ids
579
1
'''simple docstring''' from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : Any , A : int=1e-12 ) -> str: """simple docstring""" __snake_case : int = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(snake_case__ , axis=1 ) , a_min=snake_case__ ) ).T __snake_case : Optional[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(snake_case__ , axis=1 ) , a_min=snake_case__ ) ).T return jnp.matmul(snake_case__ , norm_emb_a.T ) class a_ ( nn.Module ): _snake_case = 42 _snake_case = jnp.floataa def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : List[Any] = FlaxCLIPVisionModule(self.config.vision_config) __snake_case : List[str] = nn.Dense(self.config.projection_dim , use_bias=A_ , dtype=self.dtype) __snake_case : Tuple = self.param('concept_embeds' , jax.nn.initializers.ones , (1_7, self.config.projection_dim)) __snake_case : str = self.param( 'special_care_embeds' , jax.nn.initializers.ones , (3, self.config.projection_dim)) __snake_case : Tuple = self.param('concept_embeds_weights' , jax.nn.initializers.ones , (1_7,)) __snake_case : str = self.param('special_care_embeds_weights' , jax.nn.initializers.ones , (3,)) def __call__(self , __a) -> Optional[Any]: """simple docstring""" __snake_case : Tuple = self.vision_model(A_)[1] __snake_case : Tuple = self.visual_projection(A_) __snake_case : Dict = jax_cosine_distance(A_ , self.special_care_embeds) __snake_case : Optional[Any] = jax_cosine_distance(A_ , self.concept_embeds) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs __snake_case : Optional[int] = 0.0 __snake_case : List[Any] = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment __snake_case : Dict = jnp.round(A_ , 3) __snake_case : str = jnp.any(special_scores > 0 , axis=1 , keepdims=A_) # Use a lower threshold if an image has any special care concept __snake_case : List[str] = is_special_care * 0.01 __snake_case : Optional[Any] = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment __snake_case : Tuple = jnp.round(A_ , 3) __snake_case : Dict = jnp.any(concept_scores > 0 , axis=1) return has_nsfw_concepts class a_ ( _lowercase ): _snake_case = CLIPConfig _snake_case = '''clip_input''' _snake_case = FlaxStableDiffusionSafetyCheckerModule def __init__(self , __a , __a = None , __a = 0 , __a = jnp.floataa , __a = True , **__a , ) -> int: """simple docstring""" if input_shape is None: __snake_case : Any = (1, 2_2_4, 2_2_4, 3) __snake_case : str = self.module_class(config=A_ , dtype=A_ , **A_) super().__init__(A_ , A_ , input_shape=A_ , seed=A_ , dtype=A_ , _do_init=_do_init) def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None) -> FrozenDict: """simple docstring""" __snake_case : Optional[int] = jax.random.normal(A_ , A_) __snake_case ,__snake_case : Union[str, Any] = jax.random.split(A_) __snake_case : List[Any] = {'params': params_rng, 'dropout': dropout_rng} __snake_case : Optional[int] = self.module.init(A_ , A_)['params'] return random_params def __call__(self , __a , __a = None , ) -> List[str]: """simple docstring""" __snake_case : int = jnp.transpose(A_ , (0, 2, 3, 1)) return self.module.apply( {'params': params or self.params} , jnp.array(A_ , dtype=jnp.floataa) , rngs={} , )
700
'''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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class a_ ( unittest.TestCase ): def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]: """simple docstring""" __snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} __snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8} __snake_case : Optional[int] = parent __snake_case : Dict = batch_size __snake_case : str = num_channels __snake_case : Optional[Any] = image_size __snake_case : Optional[int] = min_resolution __snake_case : Tuple = max_resolution __snake_case : Optional[int] = do_resize __snake_case : Optional[int] = size __snake_case : Union[str, Any] = do_center_crop __snake_case : List[Any] = crop_size __snake_case : int = do_normalize __snake_case : Optional[Any] = image_mean __snake_case : str = image_std __snake_case : Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]: """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: __snake_case : Optional[int] = [] for i in range(self.batch_size): image_inputs.append( np.random.randint( 2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta)) else: __snake_case : Dict = [] for i in range(self.batch_size): __snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2) image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta)) if not numpify and not torchify: # PIL expects the channel dimension as last dimension __snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs] if torchify: __snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs] return image_inputs @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a) @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : int = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4}) self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8}) __snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4) self.assertEqual(image_processor.size , {'shortest_edge': 4_2}) self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4}) def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : 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 __snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> List[Any]: """simple docstring""" __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors __snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a) for image in image_inputs: self.assertIsInstance(__a , np.ndarray) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : int = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors __snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor) # Test not batched input __snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): _snake_case = ChineseCLIPImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]: """simple docstring""" __snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a) __snake_case : List[Any] = 3 @property def SCREAMING_SNAKE_CASE__ (self) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ (self) -> Dict: """simple docstring""" __snake_case : Any = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(__a , 'do_resize')) self.assertTrue(hasattr(__a , 'size')) self.assertTrue(hasattr(__a , 'do_center_crop')) self.assertTrue(hasattr(__a , 'center_crop')) self.assertTrue(hasattr(__a , 'do_normalize')) self.assertTrue(hasattr(__a , 'image_mean')) self.assertTrue(hasattr(__a , 'image_std')) self.assertTrue(hasattr(__a , 'do_convert_rgb')) def SCREAMING_SNAKE_CASE__ (self) -> Tuple: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ (self) -> int: """simple docstring""" __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images __snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a) for image in image_inputs: self.assertIsInstance(__a , Image.Image) # Test not batched input __snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
61
0
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def UpperCAmelCase_ ( A ): '''simple docstring''' _a : Optional[int] = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' f'''{test_file} instead.''' ) _a : Tuple = components[-1] if not test_fn.endswith('py' ): raise ValueError(f'''`test_file` should be a python file. Got {test_fn} instead.''' ) if not test_fn.startswith('test_modeling_' ): raise ValueError( f'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' ) _a : Optional[int] = components[:-1] + [test_fn.replace('.py' , '' )] _a : Optional[int] = '.'.join(_snake_case ) return test_module_path def UpperCAmelCase_ ( A ): '''simple docstring''' _a : List[Any] = get_module_path(_snake_case ) _a : str = importlib.import_module(_snake_case ) return test_module def UpperCAmelCase_ ( A ): '''simple docstring''' _a : Any = [] _a : Union[str, Any] = get_test_module(_snake_case ) for attr in dir(_snake_case ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(_snake_case , _snake_case ) ) # sort with class names return sorted(_snake_case , key=lambda A : x.__name__ ) def UpperCAmelCase_ ( A ): '''simple docstring''' _a : Any = [] _a : Union[str, Any] = get_test_module(_snake_case ) for attr in dir(_snake_case ): _a : List[Any] = getattr(_snake_case , _snake_case ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). _a : Tuple = getattr(_snake_case , 'all_model_classes' , [] ) if len(_snake_case ) > 0: test_classes.append(_snake_case ) # sort with class names return sorted(_snake_case , key=lambda A : x.__name__ ) def UpperCAmelCase_ ( A ): '''simple docstring''' _a : List[str] = get_test_classes(_snake_case ) _a : Any = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_snake_case , key=lambda A : x.__name__ ) def UpperCAmelCase_ ( A ): '''simple docstring''' _a : List[str] = test_class() if hasattr(_snake_case , 'setUp' ): test.setUp() _a : Any = None if hasattr(_snake_case , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: _a : Optional[int] = test.model_tester.__class__ return model_tester def UpperCAmelCase_ ( A , A ): '''simple docstring''' _a : Tuple = get_test_classes(_snake_case ) _a : Dict = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_snake_case ) # sort with class names return sorted(_snake_case , key=lambda A : x.__name__ ) def UpperCAmelCase_ ( A , A ): '''simple docstring''' _a : Union[str, Any] = get_test_classes_for_model(_snake_case , _snake_case ) _a : str = [] for test_class in test_classes: _a : int = get_model_tester_from_test_class(_snake_case ) if tester_class is not None: tester_classes.append(_snake_case ) # sort with class names return sorted(_snake_case , key=lambda A : x.__name__ ) def UpperCAmelCase_ ( A ): '''simple docstring''' _a : Optional[int] = get_test_classes(_snake_case ) _a : Optional[int] = {test_class: get_model_tester_from_test_class(_snake_case ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase_ ( A ): '''simple docstring''' _a : Union[str, Any] = get_model_classes(_snake_case ) _a : List[Any] = { model_class: get_test_classes_for_model(_snake_case , _snake_case ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase_ ( A ): '''simple docstring''' _a : Optional[Any] = get_model_classes(_snake_case ) _a : Optional[int] = { model_class: get_tester_classes_for_model(_snake_case , _snake_case ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase_ ( A ): '''simple docstring''' if isinstance(_snake_case , _snake_case ): return o elif isinstance(_snake_case , _snake_case ): return o.__name__ elif isinstance(_snake_case , (list, tuple) ): return [to_json(_snake_case ) for x in o] elif isinstance(_snake_case , _snake_case ): return {to_json(_snake_case ): to_json(_snake_case ) for k, v in o.items()} else: return o
120
"""simple docstring""" import operator as op def _a ( _snake_case ): """simple docstring""" UpperCAmelCase = [] UpperCAmelCase = lambda _snake_case , _snake_case : int(x / y ) # noqa: E731 integer division operation UpperCAmelCase = { """^""": op.pow, """*""": op.mul, """/""": div, """+""": op.add, """-""": op.sub, } # operators & their respective operation # print table header print("""Symbol""".center(8 ) , """Action""".center(12 ) , """Stack""" , sep=""" | """ ) print("""-""" * (30 + len(_snake_case )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(_snake_case ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("""push(""" + x + """)""").ljust(12 ) , """,""".join(_snake_case ) , sep=""" | """ ) else: UpperCAmelCase = stack.pop() # pop stack # output in tabular format print("""""".rjust(8 ) , ("""pop(""" + b + """)""").ljust(12 ) , """,""".join(_snake_case ) , sep=""" | """ ) UpperCAmelCase = stack.pop() # pop stack # output in tabular format print("""""".rjust(8 ) , ("""pop(""" + a + """)""").ljust(12 ) , """,""".join(_snake_case ) , sep=""" | """ ) stack.append( str(opr[x](int(_snake_case ) , int(_snake_case ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("""push(""" + a + x + b + """)""").ljust(12 ) , """,""".join(_snake_case ) , sep=""" | """ , ) return int(stack[0] ) if __name__ == "__main__": _UpperCamelCase = input("""\n\nEnter a Postfix Equation (space separated) = """).split(""" """) print("""\n\tResult = """, solve(Postfix))
341
0
'''simple docstring''' import random def lowerCamelCase ( UpperCAmelCase__ : int , UpperCAmelCase__ : float , UpperCAmelCase__ : bool = False ) -> dict: lowercase_ : dict = {i: [] for i in range(UpperCAmelCase__ )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(UpperCAmelCase__ ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(UpperCAmelCase__ ): for j in range(i + 1 , UpperCAmelCase__ ): if random.random() < probability: graph[i].append(UpperCAmelCase__ ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(UpperCAmelCase__ ) return graph def lowerCamelCase ( UpperCAmelCase__ : int ) -> dict: return { i: [j for j in range(UpperCAmelCase__ ) if i != j] for i in range(UpperCAmelCase__ ) } if __name__ == "__main__": import doctest doctest.testmod()
30
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=_UpperCAmelCase) class __magic_name__ ( _UpperCAmelCase): UpperCamelCase__ = field(default='''image-classification''', metadata={'''include_in_asdict_even_if_is_default''': True}) UpperCamelCase__ = Features({'''image''': Image()}) UpperCamelCase__ = Features({'''labels''': ClassLabel}) UpperCamelCase__ = "image" UpperCamelCase__ = "labels" def SCREAMING_SNAKE_CASE_ ( self : Tuple , lowercase_ : str ): 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] , lowercase_ ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) lowercase_ : List[str] = copy.deepcopy(self ) lowercase_ : List[str] = self.label_schema.copy() lowercase_ : List[Any] = features[self.label_column] lowercase_ : Optional[Any] = label_schema return task_template @property def SCREAMING_SNAKE_CASE_ ( self : int ): return { self.image_column: "image", self.label_column: "labels", }
30
1
'''simple docstring''' from maths.prime_check import is_prime def a__ ( _SCREAMING_SNAKE_CASE : int ) -> int: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCAmelCase_ : Any = F'''Input value of [number={number}] must be an integer''' raise TypeError(_SCREAMING_SNAKE_CASE ) if is_prime(_SCREAMING_SNAKE_CASE ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
71
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} UpperCamelCase__ = { 'vocab_file': { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt' ), } } UpperCamelCase__ = { 'junnyu/roformer_chinese_small': 15_36, 'junnyu/roformer_chinese_base': 15_36, 'junnyu/roformer_chinese_char_small': 5_12, 'junnyu/roformer_chinese_char_base': 5_12, 'junnyu/roformer_small_discriminator': 1_28, 'junnyu/roformer_small_generator': 1_28, } UpperCamelCase__ = { 'junnyu/roformer_chinese_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_base': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_small': {'do_lower_case': True}, 'junnyu/roformer_chinese_char_base': {'do_lower_case': True}, 'junnyu/roformer_small_discriminator': {'do_lower_case': True}, 'junnyu/roformer_small_generator': {'do_lower_case': True}, } class a ( lowercase ): UpperCamelCase : int = VOCAB_FILES_NAMES UpperCamelCase : Dict = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Tuple = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : Optional[int] = RoFormerTokenizer def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=True , UpperCamelCase_="[UNK]" , UpperCamelCase_="[SEP]" , UpperCamelCase_="[PAD]" , UpperCamelCase_="[CLS]" , UpperCamelCase_="[MASK]" , UpperCamelCase_=True , UpperCamelCase_=None , **UpperCamelCase_ , ): super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , ) UpperCAmelCase__ : Union[str, Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get('lowercase' , UpperCamelCase_ ) != do_lower_case or pre_tok_state.get('strip_accents' , UpperCamelCase_ ) != strip_accents ): UpperCAmelCase__ : Any = getattr(UpperCamelCase_ , pre_tok_state.pop('type' ) ) UpperCAmelCase__ : str = do_lower_case UpperCAmelCase__ : Union[str, Any] = strip_accents UpperCAmelCase__ : Dict = pre_tok_class(**UpperCamelCase_ ) UpperCAmelCase__ : Union[str, Any] = do_lower_case def __getstate__( self ): UpperCAmelCase__ : int = self.__dict__.copy() UpperCAmelCase__ : int = BertPreTokenizer() return state def __setstate__( self , UpperCamelCase_ ): UpperCAmelCase__ : Union[str, Any] = d UpperCAmelCase__ : List[str] = self.__dict__['_tokenizer'].get_vocab() UpperCAmelCase__ : List[Any] = PreTokenizer.custom(JiebaPreTokenizer(UpperCamelCase_ ) ) def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_=None ): UpperCAmelCase__ : List[Any] = [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 , UpperCamelCase_ , UpperCamelCase_ = None ): UpperCAmelCase__ : int = [self.sep_token_id] UpperCAmelCase__ : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): UpperCAmelCase__ : Any = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ ) return tuple(UpperCamelCase_ ) def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=False , **UpperCamelCase_ , ): UpperCAmelCase__ : int = BertPreTokenizer() return super().save_pretrained(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ )
110
0
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration _UpperCAmelCase : Tuple = [ # tf -> hf ("/", "."), ("layer_", "layers."), ("kernel", "weight"), ("beta", "bias"), ("gamma", "weight"), ("pegasus", "model"), ] _UpperCAmelCase : Any = [ (".output.dense", ".fc2"), ("intermediate.LayerNorm", "final_layer_norm"), ("intermediate.dense", "fc1"), ] _UpperCAmelCase : str = ( INIT_COMMON + [ ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.out_proj"), ("attention.self", "self_attn"), ("attention.encdec.LayerNorm", "encoder_attn_layer_norm"), ("attention.encdec_output.dense", "encoder_attn.out_proj"), ("attention.encdec", "encoder_attn"), ("key", "k_proj"), ("value", "v_proj"), ("query", "q_proj"), ("decoder.LayerNorm", "decoder.layernorm_embedding"), ] + END_COMMON ) _UpperCAmelCase : Tuple = ( INIT_COMMON + [ ("embeddings.word_embeddings", "shared.weight"), ("embeddings.position_embeddings", "embed_positions.weight"), ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.output"), ("attention.self", "self_attn.self"), ("encoder.LayerNorm", "encoder.layernorm_embedding"), ] + END_COMMON ) _UpperCAmelCase : List[Any] = [ "encdec/key/bias", "encdec/query/bias", "encdec/value/bias", "self/key/bias", "self/query/bias", "self/value/bias", "encdec_output/dense/bias", "attention/output/dense/bias", ] def A ( lowercase , lowercase ) -> Optional[int]: '''simple docstring''' for tf_name, hf_name in patterns: UpperCamelCase = k.replace(lowercase , lowercase ) return k def A ( lowercase , lowercase ) -> BigBirdPegasusForConditionalGeneration: '''simple docstring''' UpperCamelCase = BigBirdPegasusConfig(**lowercase ) UpperCamelCase = BigBirdPegasusForConditionalGeneration(lowercase ) UpperCamelCase = torch_model.state_dict() UpperCamelCase = {} # separating decoder weights UpperCamelCase = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )} UpperCamelCase = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )} for k, v in tqdm(decoder_weights.items() , 'tf -> hf conversion' ): UpperCamelCase = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue UpperCamelCase = DECODER_PATTERNS UpperCamelCase = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict: raise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})''' ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): UpperCamelCase = v.T UpperCamelCase = torch.from_numpy(lowercase ) assert v.shape == state_dict[new_k].shape, f'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}''' for k, v in tqdm(remaining_weights.items() , 'tf -> hf conversion' ): UpperCamelCase = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue UpperCamelCase = REMAINING_PATTERNS UpperCamelCase = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})''' ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): UpperCamelCase = v.T UpperCamelCase = torch.from_numpy(lowercase ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}''' UpperCamelCase = mapping['model.embed_positions.weight'] UpperCamelCase = mapping.pop('model.embed_positions.weight' ) UpperCamelCase , UpperCamelCase = torch_model.load_state_dict(lowercase , strict=lowercase ) UpperCamelCase = [ k for k in missing if k not in [ 'final_logits_bias', 'model.encoder.embed_tokens.weight', 'model.decoder.embed_tokens.weight', 'lm_head.weight', ] ] assert unexpected_missing == [], f'''no matches found for the following torch keys {unexpected_missing}''' assert extra == [], f'''no matches found for the following tf keys {extra}''' return torch_model def A ( lowercase ) -> Dict: '''simple docstring''' UpperCamelCase = tf.train.list_variables(lowercase ) UpperCamelCase = {} UpperCamelCase = ['global_step'] for name, shape in tqdm(lowercase , desc='converting tf checkpoint to dict' ): UpperCamelCase = any(pat in name for pat in ignore_name ) if skip_key: continue UpperCamelCase = tf.train.load_variable(lowercase , lowercase ) UpperCamelCase = array return tf_weights def A ( lowercase , lowercase , lowercase ) -> Optional[Any]: '''simple docstring''' UpperCamelCase = get_tf_weights_as_numpy(lowercase ) UpperCamelCase = convert_bigbird_pegasus(lowercase , lowercase ) torch_model.save_pretrained(lowercase ) if __name__ == "__main__": _UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--tf_ckpt_path", type=str, help="passed to tf.train.list_variables") parser.add_argument("--save_dir", default=None, type=str, help="Path to the output PyTorch model.") _UpperCAmelCase : str = parser.parse_args() _UpperCAmelCase : Optional[Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
3
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _UpperCAmelCase : Tuple = logging.get_logger(__name__) _UpperCAmelCase : Tuple = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.linear_k": "encoder.layers.*.self_attn.linear_k", "self_attn.linear_v": "encoder.layers.*.self_attn.linear_v", "self_attn.linear_q": "encoder.layers.*.self_attn.linear_q", "self_attn.pos_bias_u": "encoder.layers.*.self_attn.pos_bias_u", "self_attn.pos_bias_v": "encoder.layers.*.self_attn.pos_bias_v", "self_attn.linear_out": "encoder.layers.*.self_attn.linear_out", "self_attn.linear_pos": "encoder.layers.*.self_attn.linear_pos", "self_attn.rotary_emb": "encoder.embed_positions", "self_attn_layer_norm": "encoder.layers.*.self_attn_layer_norm", "conv_module.pointwise_conv1": "encoder.layers.*.conv_module.pointwise_conv1", "conv_module.pointwise_conv2": "encoder.layers.*.conv_module.pointwise_conv2", "conv_module.depthwise_conv": "encoder.layers.*.conv_module.depthwise_conv", "conv_module.batch_norm": "encoder.layers.*.conv_module.batch_norm", "conv_module.layer_norm": "encoder.layers.*.conv_module.layer_norm", "ffn1.w_1": "encoder.layers.*.ffn1.intermediate_dense", "ffn1.w_2": "encoder.layers.*.ffn1.output_dense", "ffn1.layer_norm": "encoder.layers.*.ffn1_layer_norm", "ffn2.w_1": "encoder.layers.*.ffn2.intermediate_dense", "ffn2.w_2": "encoder.layers.*.ffn2.output_dense", "ffn2.layer_norm": "encoder.layers.*.ffn2_layer_norm", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } _UpperCAmelCase : Any = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def A ( lowercase , lowercase , lowercase , lowercase , lowercase ) -> Dict: '''simple docstring''' for attribute in key.split('.' ): UpperCamelCase = getattr(lowercase , lowercase ) if weight_type is not None: UpperCamelCase = getattr(lowercase , lowercase ).shape else: UpperCamelCase = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCamelCase = value elif weight_type == "weight_g": UpperCamelCase = value elif weight_type == "weight_v": UpperCamelCase = value elif weight_type == "bias": UpperCamelCase = value elif weight_type == "running_mean": UpperCamelCase = value elif weight_type == "running_var": UpperCamelCase = value elif weight_type == "num_batches_tracked": UpperCamelCase = value elif weight_type == "inv_freq": UpperCamelCase = value else: UpperCamelCase = value logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def A ( lowercase , lowercase , lowercase ) -> Any: '''simple docstring''' UpperCamelCase = [] UpperCamelCase = fairseq_model.state_dict() UpperCamelCase = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase = False if "conv_layers" in name: load_conv_layer( lowercase , lowercase , lowercase , lowercase , hf_model.config.feat_extract_norm == 'group' , ) UpperCamelCase = True else: for key, mapped_key in MAPPING.items(): UpperCamelCase = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: UpperCamelCase = True if "*" in mapped_key: UpperCamelCase = name.split(lowercase )[0].split('.' )[-2] UpperCamelCase = mapped_key.replace('*' , lowercase ) if "pos_bias_u" in name: UpperCamelCase = None elif "pos_bias_v" in name: UpperCamelCase = None elif "weight_g" in name: UpperCamelCase = 'weight_g' elif "weight_v" in name: UpperCamelCase = 'weight_v' elif "bias" in name: UpperCamelCase = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase = 'weight' elif "running_mean" in name: UpperCamelCase = 'running_mean' elif "inv_freq" in name: UpperCamelCase = 'inv_freq' elif "running_var" in name: UpperCamelCase = 'running_var' elif "num_batches_tracked" in name: UpperCamelCase = 'num_batches_tracked' else: UpperCamelCase = None set_recursively(lowercase , lowercase , lowercase , lowercase , lowercase ) continue if not is_used: unused_weights.append(lowercase ) logger.warning(f'''Unused weights: {unused_weights}''' ) def A ( lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' UpperCamelCase = full_name.split('conv_layers.' )[-1] UpperCamelCase = name.split('.' ) UpperCamelCase = int(items[0] ) UpperCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCamelCase = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCamelCase = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) UpperCamelCase = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCamelCase = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowercase ) @torch.no_grad() def A ( lowercase , lowercase , lowercase=None , lowercase=None , lowercase=True ) -> int: '''simple docstring''' if config_path is not None: UpperCamelCase = WavaVecaConformerConfig.from_pretrained(lowercase , hidden_act='swish' ) else: UpperCamelCase = WavaVecaConformerConfig() if "rope" in checkpoint_path: UpperCamelCase = 'rotary' if is_finetuned: if dict_path: UpperCamelCase = Dictionary.load(lowercase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCamelCase = target_dict.pad_index UpperCamelCase = target_dict.bos_index UpperCamelCase = target_dict.eos_index UpperCamelCase = len(target_dict.symbols ) UpperCamelCase = os.path.join(lowercase , 'vocab.json' ) if not os.path.isdir(lowercase ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(lowercase ) ) return os.makedirs(lowercase , exist_ok=lowercase ) UpperCamelCase = target_dict.indices # fairseq has the <pad> and <s> switched UpperCamelCase = 0 UpperCamelCase = 1 with open(lowercase , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(lowercase , lowercase ) UpperCamelCase = WavaVecaCTCTokenizer( lowercase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=lowercase , ) UpperCamelCase = True if config.feat_extract_norm == 'layer' else False UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=lowercase , return_attention_mask=lowercase , ) UpperCamelCase = WavaVecaProcessor(feature_extractor=lowercase , tokenizer=lowercase ) processor.save_pretrained(lowercase ) UpperCamelCase = WavaVecaConformerForCTC(lowercase ) else: UpperCamelCase = WavaVecaConformerForPreTraining(lowercase ) if is_finetuned: UpperCamelCase , UpperCamelCase , UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: UpperCamelCase = argparse.Namespace(task='audio_pretraining' ) UpperCamelCase = fairseq.tasks.setup_task(lowercase ) UpperCamelCase , UpperCamelCase , UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowercase ) UpperCamelCase = model[0].eval() recursively_load_weights(lowercase , lowercase , not is_finetuned ) hf_wavavec.save_pretrained(lowercase ) if __name__ == "__main__": _UpperCAmelCase : Tuple = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) _UpperCAmelCase : Dict = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
3
1
import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = MgpstrTokenizer lowerCAmelCase_ = False lowerCAmelCase_ = {} lowerCAmelCase_ = False def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" super().setUp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''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'''] # fmt: on __SCREAMING_SNAKE_CASE : Optional[int] = dict(zip(_A , range(len(_A ) ) ) ) __SCREAMING_SNAKE_CASE : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_A ) + '''\n''' ) def UpperCAmelCase__ ( self : Tuple , **_A : List[str] ): """simple docstring""" return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase__ ( self : int , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = '''tester''' __SCREAMING_SNAKE_CASE : str = '''tester''' return input_text, output_text @unittest.skip('''MGP-STR always lower cases letters.''' ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" pass def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.get_tokenizers(do_lower_case=_A ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''[SPECIAL_TOKEN]''' tokenizer.add_special_tokens({'''cls_token''': special_token} ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode([special_token] , add_special_tokens=_A ) self.assertEqual(len(_A ) , 1 ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.decode(_A , skip_special_tokens=_A ) self.assertTrue(special_token not in decoded ) def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = self.get_input_output_texts(_A ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_tokens_to_ids(_A ) __SCREAMING_SNAKE_CASE : str = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.convert_ids_to_tokens(_A ) self.assertNotEqual(len(_A ) , 0 ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.decode(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(text_a.replace(''' ''' , '''''' ) , _A ) @unittest.skip('''MGP-STR tokenizer only handles one sequence.''' ) def UpperCAmelCase__ ( self : Dict ): """simple docstring""" pass @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" pass
74
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class a__ ( A__ ): UpperCAmelCase__ = '''''' UpperCAmelCase__ = '''hf-legacy''' # "hf://"" is reserved for hffs def __init__( self :Dict , _lowerCamelCase :Optional[DatasetInfo] = None , _lowerCamelCase :Optional[str] = None , **_lowerCamelCase :Tuple , ): '''simple docstring''' super().__init__(self , **_lowerCamelCase ) UpperCamelCase_ : List[str] =repo_info UpperCamelCase_ : Any =token UpperCamelCase_ : Tuple =None def lowerCamelCase_ ( self :Dict ): '''simple docstring''' if self.dir_cache is None: UpperCamelCase_ : Any ={} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes UpperCamelCase_ : Optional[Any] ={ 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(_lowerCamelCase ): {'name': str(_lowerCamelCase ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def lowerCamelCase_ ( self :Union[str, Any] , _lowerCamelCase :str , _lowerCamelCase :str = "rb" , **_lowerCamelCase :str , ): '''simple docstring''' if not isinstance(self.repo_info , _lowerCamelCase ): raise NotImplementedError(f'''Open is only implemented for dataset repositories, but got {self.repo_info}''' ) UpperCamelCase_ : List[Any] =hf_hub_url(self.repo_info.id , _lowerCamelCase , revision=self.repo_info.sha ) return fsspec.open( _lowerCamelCase , mode=_lowerCamelCase , headers=get_authentication_headers_for_url(_lowerCamelCase , use_auth_token=self.token ) , client_kwargs={'trust_env': True} , ).open() def lowerCamelCase_ ( self :Optional[Any] , _lowerCamelCase :Tuple , **_lowerCamelCase :Any ): '''simple docstring''' self._get_dirs() UpperCamelCase_ : Tuple =self._strip_protocol(_lowerCamelCase ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(_lowerCamelCase ) def lowerCamelCase_ ( self :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :List[Any]=False , **_lowerCamelCase :Any ): '''simple docstring''' self._get_dirs() UpperCamelCase_ : str =PurePosixPath(path.strip('/' ) ) UpperCamelCase_ : List[str] ={} for p, f in self.dir_cache.items(): UpperCamelCase_ : List[Any] =PurePosixPath(p.strip('/' ) ) UpperCamelCase_ : Tuple =p.parent if root == path: UpperCamelCase_ : int =f UpperCamelCase_ : Optional[int] =list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
357
0
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer SCREAMING_SNAKE_CASE_ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ : Tuple = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} SCREAMING_SNAKE_CASE_ : List[str] = { '''vocab_file''': { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json''' ), }, } SCREAMING_SNAKE_CASE_ : Any = { '''vocab_file''': { '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json''' ), }, } SCREAMING_SNAKE_CASE_ : Dict = { '''vocab_file''': { '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json''' ), }, } SCREAMING_SNAKE_CASE_ : Any = { '''facebook/dpr-ctx_encoder-single-nq-base''': 512, '''facebook/dpr-ctx_encoder-multiset-base''': 512, } SCREAMING_SNAKE_CASE_ : int = { '''facebook/dpr-question_encoder-single-nq-base''': 512, '''facebook/dpr-question_encoder-multiset-base''': 512, } SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''facebook/dpr-reader-single-nq-base''': 512, '''facebook/dpr-reader-multiset-base''': 512, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } SCREAMING_SNAKE_CASE_ : List[str] = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } SCREAMING_SNAKE_CASE_ : str = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class _A ( __a ): __a = VOCAB_FILES_NAMES __a = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP __a = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class _A ( __a ): __a = VOCAB_FILES_NAMES __a = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP __a = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE_ : Optional[Any] = collections.namedtuple( '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text'''] ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits''']) SCREAMING_SNAKE_CASE_ : Optional[Any] = r''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: ``` [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> ``` Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Returns: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(__a ) class _A : def __call__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ) -> BatchEncoding: if titles is None and texts is None: return super().__call__( SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) elif titles is None or texts is None: lowerCamelCase__ = titles if texts is None else texts return super().__call__( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCamelCase__ = titles if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else [titles] lowerCamelCase__ = texts if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else [texts] lowerCamelCase__ = len(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ = questions if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else [questions] * n_passages if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise ValueError( f'There should be as many titles than texts but got {len(SCREAMING_SNAKE_CASE__ )} titles and {len(SCREAMING_SNAKE_CASE__ )} texts.' ) lowerCamelCase__ = super().__call__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ )["input_ids"] lowerCamelCase__ = super().__call__(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ )["input_ids"] lowerCamelCase__ = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ] } if return_attention_mask is not False: lowerCamelCase__ = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) lowerCamelCase__ = attention_mask return self.pad(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 16 , SCREAMING_SNAKE_CASE__ = 64 , SCREAMING_SNAKE_CASE__ = 4 , ) -> List[DPRSpanPrediction]: lowerCamelCase__ = reader_input["input_ids"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = reader_output[:3] lowerCamelCase__ = len(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ = sorted(range(SCREAMING_SNAKE_CASE__ ) , reverse=SCREAMING_SNAKE_CASE__ , key=relevance_logits.__getitem__ ) lowerCamelCase__ = [] for doc_id in sorted_docs: lowerCamelCase__ = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence lowerCamelCase__ = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: lowerCamelCase__ = sequence_ids.index(self.pad_token_id ) else: lowerCamelCase__ = len(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=SCREAMING_SNAKE_CASE__ , top_spans=SCREAMING_SNAKE_CASE__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=SCREAMING_SNAKE_CASE__ , start_index=SCREAMING_SNAKE_CASE__ , end_index=SCREAMING_SNAKE_CASE__ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(SCREAMING_SNAKE_CASE__ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) -> List[DPRSpanPrediction]: lowerCamelCase__ = [] for start_index, start_score in enumerate(SCREAMING_SNAKE_CASE__ ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) lowerCamelCase__ = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : x[1] , reverse=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(f'Wrong span indices: [{start_index}:{end_index}]' ) lowerCamelCase__ = end_index - start_index + 1 if length > max_answer_length: raise ValueError(f'Span is too long: {length} > {max_answer_length}' ) if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(SCREAMING_SNAKE_CASE__ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(__a ) class _A ( __a , __a ): __a = VOCAB_FILES_NAMES __a = READER_PRETRAINED_VOCAB_FILES_MAP __a = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a = READER_PRETRAINED_INIT_CONFIGURATION __a = ['input_ids', 'attention_mask']
274
"""simple docstring""" def UpperCAmelCase__ ( A__ ) -> list[int]: """simple docstring""" if num <= 0: raise ValueError("Input must be a positive integer" ) lowerCamelCase__ = [True] * (num + 1) lowerCamelCase__ = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , A__ ): lowerCamelCase__ = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE_ : Optional[Any] = int(input('''Enter a positive integer: ''').strip()) print(prime_sieve_eratosthenes(user_num))
274
1
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin snake_case : List[str] = get_tests_dir('''fixtures/test_sentencepiece.model''') snake_case : Union[str, Any] = get_tests_dir('''fixtures/test_sentencepiece_bpe.model''') snake_case : str = '''pt''' if is_torch_available() else '''tf''' @require_sentencepiece @require_tokenizers class snake_case_ (lowerCamelCase_ , unittest.TestCase ): UpperCAmelCase__ : Union[str, Any] = CamembertTokenizer UpperCAmelCase__ : int = CamembertTokenizerFast UpperCAmelCase__ : str = True UpperCAmelCase__ : Dict = True def lowerCamelCase__( self :Optional[int] ) -> Dict: super().setUp() # We have a SentencePiece fixture for testing a__ = CamembertTokenizer(__snake_case ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__( self :Any ) -> Dict: a__ = '<pad>' a__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__snake_case ) ,__snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__snake_case ) ,__snake_case ) def lowerCamelCase__( self :Any ) -> str: a__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<s>NOTUSED' ) self.assertEqual(vocab_keys[1] ,'<pad>' ) self.assertEqual(vocab_keys[-1] ,'<mask>' ) self.assertEqual(len(__snake_case ) ,10_04 ) def lowerCamelCase__( self :List[Any] ) -> Tuple: self.assertEqual(self.get_tokenizer().vocab_size ,10_05 ) def lowerCamelCase__( self :int ) -> str: a__ = CamembertTokenizer(__snake_case ) tokenizer.save_pretrained(self.tmpdirname ) a__ = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) a__ = 'I was born in 92000, and this is falsé.' a__ = tokenizer.encode(__snake_case ) a__ = rust_tokenizer.encode(__snake_case ) self.assertListEqual(__snake_case ,__snake_case ) a__ = tokenizer.encode(__snake_case ,add_special_tokens=__snake_case ) a__ = rust_tokenizer.encode(__snake_case ,add_special_tokens=__snake_case ) self.assertListEqual(__snake_case ,__snake_case ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) a__ = tokenizer.convert_ids_to_tokens(__snake_case ) a__ = rust_tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case ,__snake_case ) def lowerCamelCase__( self :List[Any] ) -> Any: if not self.test_rust_tokenizer: return a__ = self.get_tokenizer() a__ = self.get_rust_tokenizer() a__ = 'I was born in 92000, and this is falsé.' a__ = tokenizer.tokenize(__snake_case ) a__ = rust_tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case ,__snake_case ) a__ = tokenizer.encode(__snake_case ,add_special_tokens=__snake_case ) a__ = rust_tokenizer.encode(__snake_case ,add_special_tokens=__snake_case ) self.assertListEqual(__snake_case ,__snake_case ) a__ = self.get_rust_tokenizer() a__ = tokenizer.encode(__snake_case ) a__ = rust_tokenizer.encode(__snake_case ) self.assertListEqual(__snake_case ,__snake_case ) @slow def lowerCamelCase__( self :Tuple ) -> Optional[Any]: # fmt: off a__ = {'input_ids': [[5, 54, 71_96, 2_97, 30, 23, 7_76, 18, 11, 32_15, 37_05, 82_52, 22, 31_64, 11_81, 21_16, 29, 16, 8_13, 25, 7_91, 33_14, 20, 34_46, 38, 2_75_75, 1_20, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_68, 17, 11, 90_88, 20, 15_17, 8, 2_28_04, 1_88_18, 10, 38, 6_29, 6_07, 6_07, 1_42, 19, 71_96, 8_67, 56, 1_03_26, 24, 22_67, 20, 4_16, 50_72, 1_56_12, 2_33, 7_34, 7, 23_99, 27, 16, 30_15, 16_49, 7, 24, 20, 43_38, 23_99, 27, 13, 34_00, 14, 13, 61_89, 8, 9_30, 9, 6]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 # camembert is a french model. So we also use french texts. a__ = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=__snake_case ,model_name='camembert-base' ,revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' ,sequences=__snake_case ,)
335
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType snake_case : int = logging.get_logger(__name__) snake_case : List[Any] = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class snake_case_ (lowerCamelCase_ ): UpperCAmelCase__ : Optional[Any] = '''layoutlmv3''' def __init__( self :Optional[Any] ,__snake_case :Dict=5_02_65 ,__snake_case :Union[str, Any]=7_68 ,__snake_case :Dict=12 ,__snake_case :List[str]=12 ,__snake_case :Any=30_72 ,__snake_case :int="gelu" ,__snake_case :List[str]=0.1 ,__snake_case :Optional[Any]=0.1 ,__snake_case :List[Any]=5_12 ,__snake_case :Any=2 ,__snake_case :Dict=0.02 ,__snake_case :Dict=1E-5 ,__snake_case :Tuple=1 ,__snake_case :Optional[int]=0 ,__snake_case :List[Any]=2 ,__snake_case :Optional[Any]=10_24 ,__snake_case :List[str]=1_28 ,__snake_case :List[str]=1_28 ,__snake_case :str=True ,__snake_case :Any=32 ,__snake_case :Union[str, Any]=1_28 ,__snake_case :Optional[Any]=64 ,__snake_case :List[Any]=2_56 ,__snake_case :Any=True ,__snake_case :Optional[int]=True ,__snake_case :List[str]=True ,__snake_case :Any=2_24 ,__snake_case :Union[str, Any]=3 ,__snake_case :int=16 ,__snake_case :Any=None ,**__snake_case :Dict ,) -> Any: super().__init__( vocab_size=__snake_case ,hidden_size=__snake_case ,num_hidden_layers=__snake_case ,num_attention_heads=__snake_case ,intermediate_size=__snake_case ,hidden_act=__snake_case ,hidden_dropout_prob=__snake_case ,attention_probs_dropout_prob=__snake_case ,max_position_embeddings=__snake_case ,type_vocab_size=__snake_case ,initializer_range=__snake_case ,layer_norm_eps=__snake_case ,pad_token_id=__snake_case ,bos_token_id=__snake_case ,eos_token_id=__snake_case ,**__snake_case ,) a__ = max_ad_position_embeddings a__ = coordinate_size a__ = shape_size a__ = has_relative_attention_bias a__ = rel_pos_bins a__ = max_rel_pos a__ = has_spatial_attention_bias a__ = rel_ad_pos_bins a__ = max_rel_ad_pos a__ = text_embed a__ = visual_embed a__ = input_size a__ = num_channels a__ = patch_size a__ = classifier_dropout class snake_case_ (lowerCamelCase_ ): UpperCAmelCase__ : Tuple = version.parse('''1.12''' ) @property def lowerCamelCase__( self :Optional[int] ) -> Mapping[str, Mapping[int, str]]: # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def lowerCamelCase__( self :Tuple ) -> float: return 1E-5 @property def lowerCamelCase__( self :Any ) -> int: return 12 def lowerCamelCase__( self :Tuple ,__snake_case :"ProcessorMixin" ,__snake_case :int = -1 ,__snake_case :int = -1 ,__snake_case :bool = False ,__snake_case :Optional["TensorType"] = None ,__snake_case :int = 3 ,__snake_case :int = 40 ,__snake_case :int = 40 ,) -> Mapping[str, Any]: setattr(processor.image_processor ,'apply_ocr' ,__snake_case ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX a__ = compute_effective_axis_dimension( __snake_case ,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 a__ = processor.tokenizer.num_special_tokens_to_add(__snake_case ) a__ = compute_effective_axis_dimension( __snake_case ,fixed_dimension=OnnxConfig.default_fixed_sequence ,num_token_to_add=__snake_case ) # Generate dummy inputs according to compute batch and sequence a__ = [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes a__ = [[[48, 84, 73, 1_28]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) a__ = self._generate_dummy_images(__snake_case ,__snake_case ,__snake_case ,__snake_case ) a__ = dict( processor( __snake_case ,text=__snake_case ,boxes=__snake_case ,return_tensors=__snake_case ,) ) return inputs
335
1
snake_case_ = frozenset( [ """prompt""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", """cross_attention_kwargs""", ] ) snake_case_ = frozenset(["""prompt""", """negative_prompt"""]) snake_case_ = frozenset([]) snake_case_ = frozenset(["""image"""]) snake_case_ = frozenset( [ """image""", """height""", """width""", """guidance_scale""", ] ) snake_case_ = frozenset(["""image"""]) snake_case_ = frozenset( [ """prompt""", """image""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", ] ) snake_case_ = frozenset(["""prompt""", """image""", """negative_prompt"""]) snake_case_ = frozenset( [ # Text guided image variation with an image mask """prompt""", """image""", """mask_image""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", ] ) snake_case_ = frozenset(["""prompt""", """image""", """mask_image""", """negative_prompt"""]) snake_case_ = frozenset( [ # image variation with an image mask """image""", """mask_image""", """height""", """width""", """guidance_scale""", ] ) snake_case_ = frozenset(["""image""", """mask_image"""]) snake_case_ = frozenset( [ """example_image""", """image""", """mask_image""", """height""", """width""", """guidance_scale""", ] ) snake_case_ = frozenset(["""example_image""", """image""", """mask_image"""]) snake_case_ = frozenset(["""class_labels"""]) snake_case_ = frozenset(["""class_labels"""]) snake_case_ = frozenset(["""batch_size"""]) snake_case_ = frozenset([]) snake_case_ = frozenset(["""batch_size"""]) snake_case_ = frozenset([]) snake_case_ = frozenset( [ """prompt""", """audio_length_in_s""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", """cross_attention_kwargs""", ] ) snake_case_ = frozenset(["""prompt""", """negative_prompt"""]) snake_case_ = frozenset(["""input_tokens"""]) snake_case_ = frozenset(["""input_tokens"""])
703
'''simple docstring''' snake_case_ = [ 9_99, 8_00, 7_99, 6_00, 5_99, 5_00, 4_00, 3_99, 3_77, 3_55, 3_33, 3_11, 2_88, 2_66, 2_44, 2_22, 2_00, 1_99, 1_77, 1_55, 1_33, 1_11, 88, 66, 44, 22, 0, ] snake_case_ = [ 9_99, 9_76, 9_52, 9_28, 9_05, 8_82, 8_58, 8_57, 8_10, 7_62, 7_15, 7_14, 5_72, 4_29, 4_28, 2_86, 2_85, 2_38, 1_90, 1_43, 1_42, 1_18, 95, 71, 47, 24, 0, ] snake_case_ = [ 9_99, 9_88, 9_77, 9_66, 9_55, 9_44, 9_33, 9_22, 9_11, 9_00, 8_99, 8_79, 8_59, 8_40, 8_20, 8_00, 7_99, 7_66, 7_33, 7_00, 6_99, 6_50, 6_00, 5_99, 5_00, 4_99, 4_00, 3_99, 3_50, 3_00, 2_99, 2_66, 2_33, 2_00, 1_99, 1_79, 1_59, 1_40, 1_20, 1_00, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] snake_case_ = [ 9_99, 9_95, 9_92, 9_89, 9_85, 9_81, 9_78, 9_75, 9_71, 9_67, 9_64, 9_61, 9_57, 9_56, 9_51, 9_47, 9_42, 9_37, 9_33, 9_28, 9_23, 9_19, 9_14, 9_13, 9_08, 9_03, 8_97, 8_92, 8_87, 8_81, 8_76, 8_71, 8_70, 8_64, 8_58, 8_52, 8_46, 8_40, 8_34, 8_28, 8_27, 8_20, 8_13, 8_06, 7_99, 7_92, 7_85, 7_84, 7_77, 7_70, 7_63, 7_56, 7_49, 7_42, 7_41, 7_33, 7_24, 7_16, 7_07, 6_99, 6_98, 6_88, 6_77, 6_66, 6_56, 6_55, 6_45, 6_34, 6_23, 6_13, 6_12, 5_98, 5_84, 5_70, 5_69, 5_55, 5_41, 5_27, 5_26, 5_05, 4_84, 4_83, 4_62, 4_40, 4_39, 3_96, 3_95, 3_52, 3_51, 3_08, 3_07, 2_64, 2_63, 2_20, 2_19, 1_76, 1_32, 88, 44, 0, ] snake_case_ = [ 9_99, 9_97, 9_95, 9_92, 9_90, 9_88, 9_86, 9_84, 9_81, 9_79, 9_77, 9_75, 9_72, 9_70, 9_68, 9_66, 9_64, 9_61, 9_59, 9_57, 9_56, 9_54, 9_51, 9_49, 9_46, 9_44, 9_41, 9_39, 9_36, 9_34, 9_31, 9_29, 9_26, 9_24, 9_21, 9_19, 9_16, 9_14, 9_13, 9_10, 9_07, 9_05, 9_02, 8_99, 8_96, 8_93, 8_91, 8_88, 8_85, 8_82, 8_79, 8_77, 8_74, 8_71, 8_70, 8_67, 8_64, 8_61, 8_58, 8_55, 8_52, 8_49, 8_46, 8_43, 8_40, 8_37, 8_34, 8_31, 8_28, 8_27, 8_24, 8_21, 8_17, 8_14, 8_11, 8_08, 8_04, 8_01, 7_98, 7_95, 7_91, 7_88, 7_85, 7_84, 7_80, 7_77, 7_74, 7_70, 7_66, 7_63, 7_60, 7_56, 7_52, 7_49, 7_46, 7_42, 7_41, 7_37, 7_33, 7_30, 7_26, 7_22, 7_18, 7_14, 7_10, 7_07, 7_03, 6_99, 6_98, 6_94, 6_90, 6_85, 6_81, 6_77, 6_73, 6_69, 6_64, 6_60, 6_56, 6_55, 6_50, 6_46, 6_41, 6_36, 6_32, 6_27, 6_22, 6_18, 6_13, 6_12, 6_07, 6_02, 5_96, 5_91, 5_86, 5_80, 5_75, 5_70, 5_69, 5_63, 5_57, 5_51, 5_45, 5_39, 5_33, 5_27, 5_26, 5_19, 5_12, 5_05, 4_98, 4_91, 4_84, 4_83, 4_74, 4_66, 4_57, 4_49, 4_40, 4_39, 4_28, 4_18, 4_07, 3_96, 3_95, 3_81, 3_66, 3_52, 3_51, 3_30, 3_08, 3_07, 2_86, 2_64, 2_63, 2_42, 2_20, 2_19, 1_76, 1_75, 1_32, 1_31, 88, 44, 0, ] snake_case_ = [ 9_99, 9_91, 9_82, 9_74, 9_66, 9_58, 9_50, 9_41, 9_33, 9_25, 9_16, 9_08, 9_00, 8_99, 8_74, 8_50, 8_25, 8_00, 7_99, 7_00, 6_00, 5_00, 4_00, 3_00, 2_00, 1_00, 0, ] snake_case_ = [ 9_99, 9_92, 9_85, 9_78, 9_71, 9_64, 9_57, 9_49, 9_42, 9_35, 9_28, 9_21, 9_14, 9_07, 9_00, 8_99, 8_79, 8_59, 8_40, 8_20, 8_00, 7_99, 7_66, 7_33, 7_00, 6_99, 6_50, 6_00, 5_99, 5_00, 4_99, 4_00, 3_99, 3_00, 2_99, 2_00, 1_99, 1_00, 99, 0, ] snake_case_ = [ 9_99, 9_96, 9_92, 9_89, 9_85, 9_82, 9_79, 9_75, 9_72, 9_68, 9_65, 9_61, 9_58, 9_55, 9_51, 9_48, 9_44, 9_41, 9_38, 9_34, 9_31, 9_27, 9_24, 9_20, 9_17, 9_14, 9_10, 9_07, 9_03, 9_00, 8_99, 8_91, 8_84, 8_76, 8_69, 8_61, 8_53, 8_46, 8_38, 8_30, 8_23, 8_15, 8_08, 8_00, 7_99, 7_88, 7_77, 7_66, 7_55, 7_44, 7_33, 7_22, 7_11, 7_00, 6_99, 6_88, 6_77, 6_66, 6_55, 6_44, 6_33, 6_22, 6_11, 6_00, 5_99, 5_85, 5_71, 5_57, 5_42, 5_28, 5_14, 5_00, 4_99, 4_85, 4_71, 4_57, 4_42, 4_28, 4_14, 4_00, 3_99, 3_79, 3_59, 3_40, 3_20, 3_00, 2_99, 2_79, 2_59, 2_40, 2_20, 2_00, 1_99, 1_66, 1_33, 1_00, 99, 66, 33, 0, ]
537
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ : Tuple = { 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipConfig', 'InstructBlipQFormerConfig', 'InstructBlipVisionConfig', ], 'processing_instructblip': ['InstructBlipProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Tuple = [ 'INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'InstructBlipQFormerModel', 'InstructBlipPreTrainedModel', 'InstructBlipForConditionalGeneration', 'InstructBlipVisionModel', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys snake_case_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
195
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( a): lowerCamelCase__ = (UniPCMultistepScheduler,) lowerCamelCase__ = (('num_inference_steps', 25),) def snake_case__ ( self, **__a): '''simple docstring''' _lowerCAmelCase : List[Any] = { "num_train_timesteps": 1000, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", "solver_order": 2, "solver_type": "bh2", } config.update(**__a) return config def snake_case__ ( self, __a=0, **__a): '''simple docstring''' _lowerCAmelCase : str = dict(self.forward_default_kwargs) _lowerCAmelCase : Union[str, Any] = kwargs.pop("num_inference_steps", __a) _lowerCAmelCase : List[str] = self.dummy_sample _lowerCAmelCase : List[Any] = 0.1 * sample _lowerCAmelCase : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: _lowerCAmelCase : List[str] = self.get_scheduler_config(**__a) _lowerCAmelCase : List[str] = scheduler_class(**__a) scheduler.set_timesteps(__a) # copy over dummy past residuals _lowerCAmelCase : List[str] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a) _lowerCAmelCase : Optional[Any] = scheduler_class.from_pretrained(__a) new_scheduler.set_timesteps(__a) # copy over dummy past residuals _lowerCAmelCase : List[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] _lowerCAmelCase , _lowerCAmelCase : Dict = sample, sample for t in range(__a, time_step + scheduler.config.solver_order + 1): _lowerCAmelCase : Dict = scheduler.step(__a, __a, __a, **__a).prev_sample _lowerCAmelCase : int = new_scheduler.step(__a, __a, __a, **__a).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1E-5, "Scheduler outputs are not identical" def snake_case__ ( self, __a=0, **__a): '''simple docstring''' _lowerCAmelCase : List[Any] = dict(self.forward_default_kwargs) _lowerCAmelCase : List[str] = kwargs.pop("num_inference_steps", __a) _lowerCAmelCase : Dict = self.dummy_sample _lowerCAmelCase : List[str] = 0.1 * sample _lowerCAmelCase : str = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: _lowerCAmelCase : str = self.get_scheduler_config() _lowerCAmelCase : str = scheduler_class(**__a) scheduler.set_timesteps(__a) # copy over dummy past residuals (must be after setting timesteps) _lowerCAmelCase : List[str] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a) _lowerCAmelCase : Tuple = scheduler_class.from_pretrained(__a) # copy over dummy past residuals new_scheduler.set_timesteps(__a) # copy over dummy past residual (must be after setting timesteps) _lowerCAmelCase : Any = dummy_past_residuals[: new_scheduler.config.solver_order] _lowerCAmelCase : List[Any] = scheduler.step(__a, __a, __a, **__a).prev_sample _lowerCAmelCase : Optional[Any] = new_scheduler.step(__a, __a, __a, **__a).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1E-5, "Scheduler outputs are not identical" def snake_case__ ( self, __a=None, **__a): '''simple docstring''' if scheduler is None: _lowerCAmelCase : List[Any] = self.scheduler_classes[0] _lowerCAmelCase : List[Any] = self.get_scheduler_config(**__a) _lowerCAmelCase : str = scheduler_class(**__a) _lowerCAmelCase : str = self.scheduler_classes[0] _lowerCAmelCase : str = self.get_scheduler_config(**__a) _lowerCAmelCase : Optional[Any] = scheduler_class(**__a) _lowerCAmelCase : int = 10 _lowerCAmelCase : str = self.dummy_model() _lowerCAmelCase : List[str] = self.dummy_sample_deter scheduler.set_timesteps(__a) for i, t in enumerate(scheduler.timesteps): _lowerCAmelCase : Tuple = model(__a, __a) _lowerCAmelCase : Union[str, Any] = scheduler.step(__a, __a, __a).prev_sample return sample def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[Any] = dict(self.forward_default_kwargs) _lowerCAmelCase : List[str] = kwargs.pop("num_inference_steps", __a) for scheduler_class in self.scheduler_classes: _lowerCAmelCase : int = self.get_scheduler_config() _lowerCAmelCase : str = scheduler_class(**__a) _lowerCAmelCase : List[str] = self.dummy_sample _lowerCAmelCase : str = 0.1 * sample if num_inference_steps is not None and hasattr(__a, "set_timesteps"): scheduler.set_timesteps(__a) elif num_inference_steps is not None and not hasattr(__a, "set_timesteps"): _lowerCAmelCase : str = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) _lowerCAmelCase : Tuple = [residual + 0.2, residual + 0.15, residual + 0.10] _lowerCAmelCase : Dict = dummy_past_residuals[: scheduler.config.solver_order] _lowerCAmelCase : Optional[int] = scheduler.timesteps[5] _lowerCAmelCase : Tuple = scheduler.timesteps[6] _lowerCAmelCase : int = scheduler.step(__a, __a, __a, **__a).prev_sample _lowerCAmelCase : Optional[Any] = scheduler.step(__a, __a, __a, **__a).prev_sample self.assertEqual(output_a.shape, sample.shape) self.assertEqual(output_a.shape, output_a.shape) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[Any] = UniPCMultistepScheduler(**self.get_scheduler_config()) _lowerCAmelCase : Optional[Any] = self.full_loop(scheduler=__a) _lowerCAmelCase : List[str] = torch.mean(torch.abs(__a)) assert abs(result_mean.item() - 0.2_464) < 1E-3 _lowerCAmelCase : Tuple = DPMSolverSinglestepScheduler.from_config(scheduler.config) _lowerCAmelCase : Any = DEISMultistepScheduler.from_config(scheduler.config) _lowerCAmelCase : Any = DPMSolverMultistepScheduler.from_config(scheduler.config) _lowerCAmelCase : Optional[Any] = UniPCMultistepScheduler.from_config(scheduler.config) _lowerCAmelCase : Any = self.full_loop(scheduler=__a) _lowerCAmelCase : Any = torch.mean(torch.abs(__a)) assert abs(result_mean.item() - 0.2_464) < 1E-3 def snake_case__ ( self): '''simple docstring''' for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=__a) def snake_case__ ( self): '''simple docstring''' self.check_over_configs(thresholding=__a) for order in [1, 2, 3]: for solver_type in ["bh1", "bh2"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=__a, prediction_type=__a, sample_max_value=__a, solver_order=__a, solver_type=__a, ) def snake_case__ ( self): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a) def snake_case__ ( self): '''simple docstring''' for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=__a, solver_type=__a, prediction_type=__a, ) _lowerCAmelCase : Optional[int] = self.full_loop( solver_order=__a, solver_type=__a, prediction_type=__a, ) assert not torch.isnan(__a).any(), "Samples have nan numbers" def snake_case__ ( self): '''simple docstring''' self.check_over_configs(lower_order_final=__a) self.check_over_configs(lower_order_final=__a) def snake_case__ ( self): '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=__a, time_step=0) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : int = self.full_loop() _lowerCAmelCase : str = torch.mean(torch.abs(__a)) assert abs(result_mean.item() - 0.2_464) < 1E-3 def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = self.full_loop(prediction_type="v_prediction") _lowerCAmelCase : Union[str, Any] = torch.mean(torch.abs(__a)) assert abs(result_mean.item() - 0.1_014) < 1E-3 def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = self.scheduler_classes[0] _lowerCAmelCase : Union[str, Any] = self.get_scheduler_config(thresholding=__a, dynamic_thresholding_ratio=0) _lowerCAmelCase : Optional[int] = scheduler_class(**__a) _lowerCAmelCase : str = 10 _lowerCAmelCase : List[str] = self.dummy_model() _lowerCAmelCase : Tuple = self.dummy_sample_deter.half() scheduler.set_timesteps(__a) for i, t in enumerate(scheduler.timesteps): _lowerCAmelCase : Dict = model(__a, __a) _lowerCAmelCase : List[str] = scheduler.step(__a, __a, __a).prev_sample assert sample.dtype == torch.floataa def snake_case__ ( self, **__a): '''simple docstring''' for scheduler_class in self.scheduler_classes: _lowerCAmelCase : Any = self.get_scheduler_config(**__a) _lowerCAmelCase : List[Any] = scheduler_class(**__a) scheduler.set_timesteps(scheduler.config.num_train_timesteps) assert len(scheduler.timesteps.unique()) == scheduler.num_inference_steps
500
0
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel SCREAMING_SNAKE_CASE__ : str = HfApi() SCREAMING_SNAKE_CASE__ : List[str] = {} # fmt: off SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) SCREAMING_SNAKE_CASE__ : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) SCREAMING_SNAKE_CASE__ : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on SCREAMING_SNAKE_CASE__ : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": SCREAMING_SNAKE_CASE__ : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(f"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): SCREAMING_SNAKE_CASE__ : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: SCREAMING_SNAKE_CASE__ : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) SCREAMING_SNAKE_CASE__ : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([1_0] * noise.shape[0]) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :3_0], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1e-3 ) print(f"""{mod.modelId} has passed successfully!!!""")
711
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { '''configuration_transfo_xl''': ['''TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TransfoXLConfig'''], '''tokenization_transfo_xl''': ['''TransfoXLCorpus''', '''TransfoXLTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ '''TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AdaptiveEmbedding''', '''TransfoXLForSequenceClassification''', '''TransfoXLLMHeadModel''', '''TransfoXLModel''', '''TransfoXLPreTrainedModel''', '''load_tf_weights_in_transfo_xl''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ '''TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFAdaptiveEmbedding''', '''TFTransfoXLForSequenceClassification''', '''TFTransfoXLLMHeadModel''', '''TFTransfoXLMainLayer''', '''TFTransfoXLModel''', '''TFTransfoXLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
581
0
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase : """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_=3 , UpperCamelCase_=32 , UpperCamelCase_=3 , UpperCamelCase_=10 , UpperCamelCase_=[10, 20, 30, 40] , UpperCamelCase_=[1, 1, 2, 1] , UpperCamelCase_=True , UpperCamelCase_=True , UpperCamelCase_="relu" , UpperCamelCase_=3 , UpperCamelCase_=None , ): '''simple docstring''' UpperCamelCase__ :Optional[int] = parent UpperCamelCase__ :List[str] = batch_size UpperCamelCase__ :int = image_size UpperCamelCase__ :Any = num_channels UpperCamelCase__ :Optional[int] = embeddings_size UpperCamelCase__ :Dict = hidden_sizes UpperCamelCase__ :Optional[int] = depths UpperCamelCase__ :int = is_training UpperCamelCase__ :List[Any] = use_labels UpperCamelCase__ :Union[str, Any] = hidden_act UpperCamelCase__ :Dict = num_labels UpperCamelCase__ :Union[str, Any] = scope UpperCamelCase__ :Optional[int] = len(UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ :List[Any] = None if self.use_labels: UpperCamelCase__ :Dict = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase__ :Optional[int] = self.get_config() return config, pixel_values, labels def lowerCAmelCase__ ( self ): '''simple docstring''' return RegNetConfig( 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 , ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :int = RegNetModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() UpperCamelCase__ :Tuple = model(UpperCamelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :int = self.num_labels UpperCamelCase__ :Union[str, Any] = RegNetForImageClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() UpperCamelCase__ :Union[str, Any] = model(UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :str = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ :List[str] = config_and_inputs UpperCamelCase__ :Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowercase ( A__ , A__ , unittest.TestCase ): """simple docstring""" _a = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () _a = ( {'feature-extraction': RegNetModel, 'image-classification': RegNetForImageClassification} if is_torch_available() else {} ) _a = False _a = False _a = False _a = False def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = RegNetModelTester(self ) UpperCamelCase__ :Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase_ , has_text_modality=UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase__ ( self ): '''simple docstring''' return @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def lowerCAmelCase__ ( self ): '''simple docstring''' pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def lowerCAmelCase__ ( self ): '''simple docstring''' pass def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ :Tuple = model_class(UpperCamelCase_ ) UpperCamelCase__ :str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ :Optional[Any] = [*signature.parameters.keys()] UpperCamelCase__ :Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ :Optional[Any] = model_class(config=UpperCamelCase_ ) for name, module in model.named_modules(): if isinstance(UpperCamelCase_ , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) def lowerCAmelCase__ ( self ): '''simple docstring''' def check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase__ :Tuple = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() with torch.no_grad(): UpperCamelCase__ :Optional[Any] = model(**self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) ) UpperCamelCase__ :List[str] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase__ :int = self.model_tester.num_stages self.assertEqual(len(UpperCamelCase_ ) , expected_num_stages + 1 ) # RegNet'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 // 2, self.model_tester.image_size // 2] , ) UpperCamelCase__ , UpperCamelCase__ :str = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ :Union[str, Any] = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: UpperCamelCase__ :Optional[int] = layer_type UpperCamelCase__ :Any = True check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase__ :Union[str, Any] = True check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_ ) @slow def lowerCAmelCase__ ( self ): '''simple docstring''' for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ :Union[str, Any] = RegNetModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) def a ( ) -> str: '''simple docstring''' UpperCamelCase__ :int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): """simple docstring""" @cached_property def lowerCAmelCase__ ( self ): '''simple docstring''' return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Tuple = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(UpperCamelCase_ ) UpperCamelCase__ :Tuple = self.default_image_processor UpperCamelCase__ :List[Any] = prepare_img() UpperCamelCase__ :Optional[Any] = image_processor(images=UpperCamelCase_ , return_tensors='''pt''' ).to(UpperCamelCase_ ) # forward pass with torch.no_grad(): UpperCamelCase__ :Tuple = model(**UpperCamelCase_ ) # verify the logits UpperCamelCase__ :Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = torch.tensor([-0.4180, -1.5051, -3.4836] ).to(UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase_ , atol=1e-4 ) )
189
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def a ( __a ) -> list[list[float]]: '''simple docstring''' UpperCamelCase__ :int = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(__a ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix UpperCamelCase__ :str = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements UpperCamelCase__ :List[Any] = [[0.0, 0.0], [0.0, 0.0]] UpperCamelCase__ , UpperCamelCase__ :Union[str, Any] = matrix[1][1], matrix[0][0] UpperCamelCase__ , UpperCamelCase__ :Dict = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(__a ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(__a ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule UpperCamelCase__ :int = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix UpperCamelCase__ :List[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] UpperCamelCase__ :Tuple = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) UpperCamelCase__ :List[str] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) UpperCamelCase__ :Union[str, Any] = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) UpperCamelCase__ :List[Any] = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) UpperCamelCase__ :Optional[int] = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) UpperCamelCase__ :List[Any] = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) UpperCamelCase__ :List[Any] = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) UpperCamelCase__ :List[str] = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) UpperCamelCase__ :Dict = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) UpperCamelCase__ :Optional[Any] = array(__a ) for i in range(3 ): for j in range(3 ): UpperCamelCase__ :Optional[Any] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix UpperCamelCase__ :Any = array(__a ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(__a ) # Calculate the inverse of the matrix return [[float(d(__a ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
189
1
'''simple docstring''' import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
720
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
0
import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def UpperCAmelCase ( UpperCAmelCase=32 ,UpperCAmelCase=10 ,UpperCAmelCase=100 ,UpperCAmelCase=1026 ,UpperCAmelCase=True ,UpperCAmelCase="data/tokenized_stories_train_wikitext103.jbl" ,UpperCAmelCase="igf_context_pairs.jbl" ,)-> List[str]: '''simple docstring''' set_seed(3 ) # generate train_data and objective_set SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = generate_datasets( _UpperCamelCase ,_UpperCamelCase ,number=_UpperCamelCase ,min_len=1026 ,trim=_UpperCamelCase ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? SCREAMING_SNAKE_CASE_ = torch.device('''cuda:0''' if torch.cuda.is_available() else '''cpu''' ) # load pretrained model SCREAMING_SNAKE_CASE_ = load_gpta('''gpt2''' ).to(_UpperCamelCase ) print('''computing perplexity on objective set''' ) SCREAMING_SNAKE_CASE_ = compute_perplexity(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ).item() print('''perplexity on objective set:''' ,_UpperCamelCase ) # collect igf pairs and save to file demo.jbl collect_objective_set(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase=15 ,UpperCAmelCase=128 ,UpperCAmelCase=100 ,UpperCAmelCase="igf_model.pt" ,)-> int: '''simple docstring''' set_seed(42 ) # Load pre-trained model SCREAMING_SNAKE_CASE_ = GPTaLMHeadModel.from_pretrained('''gpt2''' ) # Initialize secondary learner to use embedding weights of model SCREAMING_SNAKE_CASE_ = SecondaryLearner(_UpperCamelCase ) # Train secondary learner SCREAMING_SNAKE_CASE_ = train_secondary_learner( _UpperCamelCase ,_UpperCamelCase ,max_epochs=_UpperCamelCase ,batch_size=_UpperCamelCase ,eval_freq=100 ,igf_model_path=_UpperCamelCase ,) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def UpperCAmelCase ( UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase ,UpperCAmelCase=32 ,UpperCAmelCase=1000 ,UpperCAmelCase=16 ,UpperCAmelCase=1.0 ,UpperCAmelCase=recopy_gpta ,UpperCAmelCase=None ,UpperCAmelCase=10 ,UpperCAmelCase="gpt2_finetuned.pt" ,)-> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ = torch.device('''cuda:0''' if torch.cuda.is_available() else '''cpu''' ) SCREAMING_SNAKE_CASE_ = RandomSampler(_UpperCamelCase ) SCREAMING_SNAKE_CASE_ = DataLoader(_UpperCamelCase ,sampler=_UpperCamelCase ) SCREAMING_SNAKE_CASE_ = max_steps // (len(_UpperCamelCase )) + 1 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = torch.zeros((1, context_len) ,dtype=torch.long ,device=_UpperCamelCase ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = recopy_model(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) model.train() if secondary_learner is not None: secondary_learner.to(_UpperCamelCase ) secondary_learner.eval() SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] # Compute the performance of the transformer model at the beginning SCREAMING_SNAKE_CASE_ = compute_perplexity(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) test_perps.append(_UpperCamelCase ) print('''Test perplexity, step''' ,_UpperCamelCase ,''':''' ,_UpperCamelCase ) for epoch in range(int(_UpperCamelCase ) ): for step, example in enumerate(_UpperCamelCase ): torch.cuda.empty_cache() SCREAMING_SNAKE_CASE_ = random.randint(0 ,example.size(2 ) - context_len - 1 ) SCREAMING_SNAKE_CASE_ = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() SCREAMING_SNAKE_CASE_ = model(_UpperCamelCase ,labels=_UpperCamelCase ) SCREAMING_SNAKE_CASE_ = True if secondary_learner is not None: SCREAMING_SNAKE_CASE_ = secondary_learner.forward( torch.tensor(_UpperCamelCase ,dtype=torch.long ,device=_UpperCamelCase ).unsqueeze(0 ) )[0].item() observed_qs.append(float(_UpperCamelCase ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: SCREAMING_SNAKE_CASE_ = -1 if predicted_q < threshold: SCREAMING_SNAKE_CASE_ = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) SCREAMING_SNAKE_CASE_ = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() SCREAMING_SNAKE_CASE_ = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() ,3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: SCREAMING_SNAKE_CASE_ = compute_perplexity(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) test_perps.append(_UpperCamelCase ) print('''Test perplexity, step''' ,_UpperCamelCase ,''':''' ,_UpperCamelCase ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() ,_UpperCamelCase ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def UpperCAmelCase ( )-> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser(description='''Fine-tune a transformer model with IGF on a language modeling task''' ) # Required parameters parser.add_argument( '''--data_dir''' ,default=_UpperCamelCase ,type=_UpperCamelCase ,required=_UpperCamelCase ,help='''The input data dir. Should contain data files for WikiText.''' ,) parser.add_argument( '''--model_name_or_path''' ,default=_UpperCamelCase ,type=_UpperCamelCase ,required=_UpperCamelCase ,help='''Path to pretrained model or model identifier from huggingface.co/models''' ,) parser.add_argument( '''--data_file''' ,type=_UpperCamelCase ,default=_UpperCamelCase ,help=( '''A jbl file containing tokenized data which can be split as objective dataset, ''' '''train_dataset and test_dataset.''' ) ,) parser.add_argument( '''--igf_data_file''' ,type=_UpperCamelCase ,default=_UpperCamelCase ,help='''A jbl file containing the context and information gain pairs to train secondary learner.''' ,) parser.add_argument( '''--output_dir''' ,default=_UpperCamelCase ,type=_UpperCamelCase ,required=_UpperCamelCase ,help='''The output directory where the final fine-tuned model is stored.''' ,) parser.add_argument( '''--tokenizer_name''' ,default=_UpperCamelCase ,type=_UpperCamelCase ,help='''Pretrained tokenizer name or path if not the same as model_name''' ,) parser.add_argument('''--seed''' ,type=_UpperCamelCase ,default=_UpperCamelCase ,help='''A seed for reproducible training.''' ) parser.add_argument( '''--context_len''' ,default=32 ,type=_UpperCamelCase ,help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) ,) parser.add_argument( '''--size_objective_set''' ,default=100 ,type=_UpperCamelCase ,help='''number of articles that are long enough to be used as our objective set''' ,) parser.add_argument( '''--eval_freq''' ,default=100 ,type=_UpperCamelCase ,help='''secondary model evaluation is triggered at eval_freq''' ) parser.add_argument('''--max_steps''' ,default=1000 ,type=_UpperCamelCase ,help='''To calculate training epochs''' ) parser.add_argument( '''--secondary_learner_batch_size''' ,default=128 ,type=_UpperCamelCase ,help='''batch size of training data for secondary learner''' ,) parser.add_argument( '''--batch_size''' ,default=16 ,type=_UpperCamelCase ,help='''batch size of training data of language model(gpt2) ''' ) parser.add_argument( '''--eval_interval''' ,default=10 ,type=_UpperCamelCase ,help=( '''decay the selectivity of our secondary learner filter from''' '''1 standard deviation above average to 1 below average after 10 batches''' ) ,) parser.add_argument( '''--number''' ,default=100 ,type=_UpperCamelCase ,help='''The number of examples split to be used as objective_set/test_data''' ) parser.add_argument( '''--min_len''' ,default=1026 ,type=_UpperCamelCase ,help='''The minimum length of the article to be used as objective set''' ) parser.add_argument( '''--secondary_learner_max_epochs''' ,default=15 ,type=_UpperCamelCase ,help='''number of epochs to train secondary learner''' ) parser.add_argument('''--trim''' ,default=_UpperCamelCase ,type=_UpperCamelCase ,help='''truncate the example if it exceeds context length''' ) parser.add_argument( '''--threshold''' ,default=1.0 ,type=_UpperCamelCase ,help=( '''The threshold value used by secondary learner to filter the train_data and allow only''' ''' informative data as input to the model''' ) ,) parser.add_argument('''--finetuned_model_name''' ,default='''gpt2_finetuned.pt''' ,type=_UpperCamelCase ,help='''finetuned_model_name''' ) parser.add_argument( '''--recopy_model''' ,default=_UpperCamelCase ,type=_UpperCamelCase ,help='''Reset the model to the original pretrained GPT-2 weights after each iteration''' ,) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 ,max_steps=10 ,size_objective_set=100 ,min_len=1026 ,trim=_UpperCamelCase ,data_file='''data/tokenized_stories_train_wikitext103.jbl''' ,igf_data_file='''igf_context_pairs.jbl''' ,) # Load train data for secondary learner SCREAMING_SNAKE_CASE_ = joblib.load('''data/IGF_values.jbl''' ) # Train secondary learner SCREAMING_SNAKE_CASE_ = training_secondary_learner( _UpperCamelCase ,secondary_learner_max_epochs=15 ,secondary_learner_batch_size=128 ,eval_freq=100 ,igf_model_path='''igf_model.pt''' ,) # load pretrained gpt2 model SCREAMING_SNAKE_CASE_ = GPTaLMHeadModel.from_pretrained('''gpt2''' ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = generate_datasets( context_len=32 ,file='''data/tokenized_stories_train_wikitext103.jbl''' ,number=100 ,min_len=1026 ,trim=_UpperCamelCase ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( _UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,context_len=32 ,max_steps=1000 ,batch_size=16 ,threshold=1.0 ,recopy_model=_UpperCamelCase ,secondary_learner=_UpperCamelCase ,eval_interval=10 ,finetuned_model_name='''gpt2_finetuned.pt''' ,) if __name__ == "__main__": main()
393
from jiwer import compute_measures import datasets lowerCamelCase :Any = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' lowerCamelCase :Any = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' lowerCamelCase :List[Any] = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): def _A ( self: 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''' ), } ) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', ] , ) def _A ( self: Optional[Any] , __UpperCamelCase: Any=None , __UpperCamelCase: Dict=None , __UpperCamelCase: Tuple=False ): if concatenate_texts: return compute_measures(__UpperCamelCase , __UpperCamelCase )["wer"] else: _a = 0 _a = 0 for prediction, reference in zip(__UpperCamelCase , __UpperCamelCase ): _a = compute_measures(__UpperCamelCase , __UpperCamelCase ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
487
0
"""simple docstring""" from __future__ import annotations def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): if not nums: return 0 _lowercase : Optional[int] = nums[0] _lowercase : Any = 0 for num in nums[1:]: _lowercase : Tuple = ( max_excluding + num, max(_lowerCAmelCase , _lowerCAmelCase ), ) return max(_lowerCAmelCase , _lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
716
"""simple docstring""" import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder UpperCAmelCase: str = """base_with_context""" def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ): _lowercase : Dict = nn.Parameter(torch.FloatTensor(weights["""token_embedder"""]["""embedding"""] ) ) _lowercase : Any = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=__UpperCAmelCase ) for lyr_num, lyr in enumerate(model.encoders ): _lowercase : Optional[Any] = weights[F"""layers_{lyr_num}"""] _lowercase : str = nn.Parameter( torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""] ) ) _lowercase : Optional[Any] = ly_weight["""attention"""] _lowercase : Dict = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) _lowercase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) _lowercase : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) _lowercase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) _lowercase : int = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) _lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) _lowercase : Tuple = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) _lowercase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) _lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""] ) ) return model def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ): _lowercase : int = nn.Parameter(torch.FloatTensor(weights["""input_proj"""]["""kernel"""].T ) ) _lowercase : Optional[int] = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=__UpperCAmelCase ) for lyr_num, lyr in enumerate(model.encoders ): _lowercase : int = weights[F"""layers_{lyr_num}"""] _lowercase : Any = ly_weight["""attention"""] _lowercase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) _lowercase : str = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) _lowercase : Any = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) _lowercase : Any = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) _lowercase : Optional[Any] = nn.Parameter( torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""] ) ) _lowercase : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) _lowercase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) _lowercase : str = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) _lowercase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) _lowercase : Union[str, Any] = nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""] ) ) return model def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ): _lowercase : Dict = nn.Parameter(torch.FloatTensor(weights["""time_emb_dense0"""]["""kernel"""].T ) ) _lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["""time_emb_dense1"""]["""kernel"""].T ) ) _lowercase : Optional[int] = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=__UpperCAmelCase ) _lowercase : Optional[Any] = nn.Parameter( torch.FloatTensor(weights["""continuous_inputs_projection"""]["""kernel"""].T ) ) for lyr_num, lyr in enumerate(model.decoders ): _lowercase : List[Any] = weights[F"""layers_{lyr_num}"""] _lowercase : Dict = nn.Parameter( torch.FloatTensor(ly_weight["""pre_self_attention_layer_norm"""]["""scale"""] ) ) _lowercase : int = nn.Parameter( torch.FloatTensor(ly_weight["""FiLMLayer_0"""]["""DenseGeneral_0"""]["""kernel"""].T ) ) _lowercase : List[Any] = ly_weight["""self_attention"""] _lowercase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) _lowercase : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) _lowercase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) _lowercase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) _lowercase : Union[str, Any] = ly_weight["""MultiHeadDotProductAttention_0"""] _lowercase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) _lowercase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) _lowercase : Any = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) _lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) _lowercase : List[str] = nn.Parameter( torch.FloatTensor(ly_weight["""pre_cross_attention_layer_norm"""]["""scale"""] ) ) _lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) _lowercase : Any = nn.Parameter( torch.FloatTensor(ly_weight["""FiLMLayer_1"""]["""DenseGeneral_0"""]["""kernel"""].T ) ) _lowercase : str = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) _lowercase : Dict = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) _lowercase : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) _lowercase : str = nn.Parameter(torch.FloatTensor(weights["""decoder_norm"""]["""scale"""] ) ) _lowercase : Any = nn.Parameter(torch.FloatTensor(weights["""spec_out_dense"""]["""kernel"""].T ) ) return model def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): _lowercase : Tuple = checkpoints.load_tax_checkpoint(args.checkpoint_path ) _lowercase : List[Any] = jnp.tree_util.tree_map(onp.array , __UpperCAmelCase ) _lowercase : int = [ """from __gin__ import dynamic_registration""", """from music_spectrogram_diffusion.models.diffusion import diffusion_utils""", """diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0""", """diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()""", ] _lowercase : List[Any] = os.path.join(args.checkpoint_path , """..""" , """config.gin""" ) _lowercase : Optional[int] = inference.parse_training_gin_file(__UpperCAmelCase , __UpperCAmelCase ) _lowercase : Optional[Any] = inference.InferenceModel(args.checkpoint_path , __UpperCAmelCase ) _lowercase : List[Any] = DDPMScheduler(beta_schedule="""squaredcos_cap_v2""" , variance_type="""fixed_large""" ) _lowercase : List[str] = SpectrogramNotesEncoder( max_length=synth_model.sequence_length["""inputs"""] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="""gated-gelu""" , ) _lowercase : Dict = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length["""targets_context"""] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="""gated-gelu""" , ) _lowercase : int = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length["""targets_context"""] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , ) _lowercase : str = load_notes_encoder(ta_checkpoint["""target"""]["""token_encoder"""] , __UpperCAmelCase ) _lowercase : Dict = load_continuous_encoder(ta_checkpoint["""target"""]["""continuous_encoder"""] , __UpperCAmelCase ) _lowercase : List[str] = load_decoder(ta_checkpoint["""target"""]["""decoder"""] , __UpperCAmelCase ) _lowercase : Any = OnnxRuntimeModel.from_pretrained("""kashif/soundstream_mel_decoder""" ) _lowercase : str = SpectrogramDiffusionPipeline( notes_encoder=__UpperCAmelCase , continuous_encoder=__UpperCAmelCase , decoder=__UpperCAmelCase , scheduler=__UpperCAmelCase , melgan=__UpperCAmelCase , ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": UpperCAmelCase: Any = argparse.ArgumentParser() parser.add_argument("""--output_path""", default=None, type=str, required=True, help="""Path to the converted model.""") parser.add_argument( """--save""", default=True, type=bool, required=False, help="""Whether to save the converted model or not.""" ) parser.add_argument( """--checkpoint_path""", default=F'{MODEL}/checkpoint_500000', type=str, required=False, help="""Path to the original jax model checkpoint.""", ) UpperCAmelCase: Optional[Any] = parser.parse_args() main(args)
600
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 MobileViTImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"shortest_edge": 20} SCREAMING_SNAKE_CASE_ : Dict = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : int = parent SCREAMING_SNAKE_CASE_ : Tuple = batch_size SCREAMING_SNAKE_CASE_ : Any = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : Optional[int] = size SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop SCREAMING_SNAKE_CASE_ : List[Any] = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = do_flip_channel_order def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = MobileViTImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = MobileViTImageProcessingTester(self ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_flip_channel_order" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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} ) SCREAMING_SNAKE_CASE_ : Optional[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 __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[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 SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : str = image_processing(lowercase__ , 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , 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"], ) , )
421
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule snake_case_ = {'tokenization_byt5': ['ByT5Tokenizer']} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
421
1
'''simple docstring''' import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) _snake_case : Any = logging.getLogger() def snake_case_ (UpperCamelCase : Union[str, Any] ): '''simple docstring''' _a = {} _a = os.path.join(UpperCamelCase , '''all_results.json''' ) if os.path.exists(UpperCamelCase ): with open(UpperCamelCase , '''r''' ) as f: _a = json.load(UpperCamelCase ) else: raise ValueError(f'can\'t find {path}' ) return results _snake_case : Optional[int] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class A ( _a ): def __lowerCAmelCase ( self : Any ) -> Dict: """simple docstring""" import xla_spawn _a = self.get_auto_remove_tmp_dir() _a = F'\n ./examples/pytorch/text-classification/run_glue.py\n --num_cores=8\n ./examples/pytorch/text-classification/run_glue.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --do_train\n --do_eval\n --debug tpu_metrics_debug\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --max_steps=10\n --warmup_steps=2\n --seed=42\n --max_seq_length=128\n '.split() with patch.object(lowerCAmelCase_ , '''argv''' , lowerCAmelCase_ ): _a = time() xla_spawn.main() _a = time() _a = get_results(lowerCAmelCase_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.7_5 ) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 5_00 ) def __lowerCAmelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" import xla_spawn _a = ''' ./tests/test_trainer_tpu.py --num_cores=8 ./tests/test_trainer_tpu.py '''.split() with patch.object(lowerCAmelCase_ , '''argv''' , lowerCAmelCase_ ): xla_spawn.main()
377
'''simple docstring''' import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class A ( ctypes.Structure ): # _fields is a specific attr expected by ctypes lowercase_ = [('size', ctypes.c_int), ('visible', ctypes.c_byte)] def snake_case_ (): '''simple docstring''' if os.name == "nt": _a = CursorInfo() _a = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(UpperCamelCase , ctypes.byref(UpperCamelCase ) ) _a = False ctypes.windll.kernelaa.SetConsoleCursorInfo(UpperCamelCase , ctypes.byref(UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def snake_case_ (): '''simple docstring''' if os.name == "nt": _a = CursorInfo() _a = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(UpperCamelCase , ctypes.byref(UpperCamelCase ) ) _a = True ctypes.windll.kernelaa.SetConsoleCursorInfo(UpperCamelCase , ctypes.byref(UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def snake_case_ (): '''simple docstring''' try: hide_cursor() yield finally: show_cursor()
377
1
'''simple docstring''' A__ : List[str] = [0, 2, 4, 6, 8] A__ : Union[str, Any] = [1, 3, 5, 7, 9] def UpperCAmelCase__ ( UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : int ) -> int: if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 , -1 , -1 ): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 __lowerCamelCase : Optional[Any] = 0 for digit in range(10 ): __lowerCamelCase : Optional[int] = digit result += reversible_numbers( 0 , (remainder + 2 * digit) // 10 , UpperCAmelCase_ , UpperCAmelCase_ ) return result __lowerCamelCase : Optional[int] = 0 for digita in range(10 ): __lowerCamelCase : List[Any] = digita if (remainder + digita) % 2 == 0: __lowerCamelCase : int = ODD_DIGITS else: __lowerCamelCase : Union[str, Any] = EVEN_DIGITS for digita in other_parity_digits: __lowerCamelCase : Optional[int] = digita result += reversible_numbers( remaining_length - 2 , (remainder + digita + digita) // 10 , UpperCAmelCase_ , UpperCAmelCase_ , ) return result def UpperCAmelCase__ ( UpperCAmelCase_ : int = 9 ) -> int: __lowerCamelCase : List[Any] = 0 for length in range(1 , max_power + 1 ): result += reversible_numbers(UpperCAmelCase_ , 0 , [0] * length , UpperCAmelCase_ ) return result if __name__ == "__main__": print(f'''{solution() = }''')
13
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['transformers', 'torch', 'note_seq'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] )
42
0
lowerCAmelCase__ = [ [0, 1_6, 1_3, 0, 0, 0], [0, 0, 1_0, 1_2, 0, 0], [0, 4, 0, 0, 1_4, 0], [0, 0, 9, 0, 0, 2_0], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def __lowerCamelCase ( __a : Optional[Any] , __a : List[Any] , __a : Tuple , __a : Tuple ) -> Optional[Any]: # Return True if there is node that has not iterated. _lowercase =[False] * len(__a ) _lowercase =[s] _lowercase =True while queue: _lowercase =queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(__a ) _lowercase =True _lowercase =u return visited[t] def __lowerCamelCase ( __a : Union[str, Any] , __a : Union[str, Any] , __a : Union[str, Any] ) -> int: _lowercase =[-1] * (len(__a )) _lowercase =0 _lowercase =[] _lowercase =[i[:] for i in graph] # Record original cut, copy. while bfs(__a , __a , __a , __a ): _lowercase =float("Inf" ) _lowercase =sink while s != source: # Find the minimum value in select path _lowercase =min(__a , graph[parent[s]][s] ) _lowercase =parent[s] max_flow += path_flow _lowercase =sink while v != source: _lowercase =parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _lowercase =parent[v] for i in range(len(__a ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
709
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType lowerCAmelCase__ = None lowerCAmelCase__ = "<" if sys.byteorder == "little" else ">" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image lowerCAmelCase__ = [ np.dtype("|b1"), np.dtype("|u1"), np.dtype("<u2"), np.dtype(">u2"), np.dtype("<i2"), np.dtype(">i2"), np.dtype("<u4"), np.dtype(">u4"), np.dtype("<i4"), np.dtype(">i4"), np.dtype("<f4"), np.dtype(">f4"), np.dtype("<f8"), np.dtype(">f8"), ] @dataclass class _a : """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = None # Automatically constructed __SCREAMING_SNAKE_CASE = "PIL.Image.Image" __SCREAMING_SNAKE_CASE = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __SCREAMING_SNAKE_CASE = field(default='Image' , init=lowerCamelCase_ , repr=lowerCamelCase_ ) def __call__( self ): return self.pa_type def __lowerCAmelCase ( self , lowerCAmelCase_ ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _lowercase =np.array(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {"path": value, "bytes": None} elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {"path": None, "bytes": value} elif isinstance(lowerCAmelCase_ , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(lowerCAmelCase_ ) elif isinstance(lowerCAmelCase_ , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(lowerCAmelCase_ ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( F'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __lowerCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: _lowercase ={} _lowercase , _lowercase =value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(F'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(lowerCAmelCase_ ): _lowercase =PIL.Image.open(lowerCAmelCase_ ) else: _lowercase =path.split("::" )[-1] try: _lowercase =string_to_dict(lowerCAmelCase_ , config.HUB_DATASETS_URL )["repo_id"] _lowercase =token_per_repo_id.get(lowerCAmelCase_ ) except ValueError: _lowercase =None with xopen(lowerCAmelCase_ , "rb" , use_auth_token=lowerCAmelCase_ ) as f: _lowercase =BytesIO(f.read() ) _lowercase =PIL.Image.open(bytes_ ) else: _lowercase =PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __lowerCAmelCase ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __lowerCAmelCase ( self , lowerCAmelCase_ ): if pa.types.is_string(storage.type ): _lowercase =pa.array([None] * len(lowerCAmelCase_ ) , type=pa.binary() ) _lowercase =pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _lowercase =pa.array([None] * len(lowerCAmelCase_ ) , type=pa.string() ) _lowercase =pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: _lowercase =storage.field("bytes" ) else: _lowercase =pa.array([None] * len(lowerCAmelCase_ ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: _lowercase =storage.field("path" ) else: _lowercase =pa.array([None] * len(lowerCAmelCase_ ) , type=pa.string() ) _lowercase =pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _lowercase =pa.array( [encode_np_array(np.array(lowerCAmelCase_ ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) _lowercase =pa.array([None] * len(lowerCAmelCase_ ) , type=pa.string() ) _lowercase =pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(lowerCAmelCase_ , self.pa_type ) def __lowerCAmelCase ( self , lowerCAmelCase_ ): @no_op_if_value_is_null def path_to_bytes(lowerCAmelCase_ ): with xopen(lowerCAmelCase_ , "rb" ) as f: _lowercase =f.read() return bytes_ _lowercase =pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _lowercase =pa.array( [os.path.basename(lowerCAmelCase_ ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) _lowercase =pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(lowerCAmelCase_ , self.pa_type ) def __lowerCamelCase ( ) -> List[str]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() _lowercase =list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def __lowerCamelCase ( __a : "PIL.Image.Image" ) -> bytes: _lowercase =BytesIO() if image.format in list_image_compression_formats(): _lowercase =image.format else: _lowercase ="PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__a , format=__a ) return buffer.getvalue() def __lowerCamelCase ( __a : "PIL.Image.Image" ) -> dict: if hasattr(__a , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__a )} def __lowerCamelCase ( __a : np.ndarray ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) _lowercase =array.dtype _lowercase =dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER _lowercase =dtype.kind _lowercase =dtype.itemsize _lowercase =None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _lowercase =np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( f'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: _lowercase =dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: _lowercase =dtype_byteorder + dtype_kind + str(__a ) _lowercase =np.dtype(__a ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) _lowercase =PIL.Image.fromarray(array.astype(__a ) ) return {"path": None, "bytes": image_to_bytes(__a )} def __lowerCamelCase ( __a : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ) -> List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: _lowercase , _lowercase =first_non_null_value(__a ) if isinstance(__a , __a ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__a , np.ndarray ): _lowercase =no_op_if_value_is_null(__a ) return [obj_to_image_dict_func(__a ) for obj in objs] elif isinstance(__a , PIL.Image.Image ): _lowercase =no_op_if_value_is_null(__a ) return [obj_to_image_dict_func(__a ) for obj in objs] else: return objs else: return objs
594
0
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() __lowerCamelCase : List[str] = logging.get_logger(__name__) def _snake_case ( lowerCAmelCase : Optional[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = UniSpeechSatForSequenceClassification.from_pretrained(lowerCAmelCase , config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Any = downstream_dict["projector.weight"] SCREAMING_SNAKE_CASE_ : Optional[Any] = downstream_dict["projector.bias"] SCREAMING_SNAKE_CASE_ : str = downstream_dict["model.post_net.linear.weight"] SCREAMING_SNAKE_CASE_ : Union[str, Any] = downstream_dict["model.post_net.linear.bias"] return model def _snake_case ( lowerCAmelCase : Tuple , lowerCAmelCase : Any , lowerCAmelCase : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = UniSpeechSatForAudioFrameClassification.from_pretrained(lowerCAmelCase , config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Optional[Any] = downstream_dict["model.linear.weight"] SCREAMING_SNAKE_CASE_ : Optional[int] = downstream_dict["model.linear.bias"] return model def _snake_case ( lowerCAmelCase : Tuple , lowerCAmelCase : Optional[int] , lowerCAmelCase : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = UniSpeechSatForXVector.from_pretrained(lowerCAmelCase , config=lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = downstream_dict["connector.weight"] SCREAMING_SNAKE_CASE_ : Tuple = downstream_dict["connector.bias"] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): SCREAMING_SNAKE_CASE_ : str = downstream_dict[ f'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] SCREAMING_SNAKE_CASE_ : Union[str, Any] = downstream_dict[f'model.framelevel_feature_extractor.module.{i}.kernel.bias'] SCREAMING_SNAKE_CASE_ : Dict = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"] SCREAMING_SNAKE_CASE_ : Any = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"] SCREAMING_SNAKE_CASE_ : int = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"] SCREAMING_SNAKE_CASE_ : Any = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"] SCREAMING_SNAKE_CASE_ : Optional[int] = downstream_dict["objective.W"] return model @torch.no_grad() def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : Any , lowerCAmelCase : int , lowerCAmelCase : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = torch.load(lowerCAmelCase , map_location="cpu" ) SCREAMING_SNAKE_CASE_ : str = checkpoint["Downstream"] SCREAMING_SNAKE_CASE_ : Optional[int] = UniSpeechSatConfig.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Dict = WavaVecaFeatureExtractor.from_pretrained( lowerCAmelCase , return_attention_mask=lowerCAmelCase , do_normalize=lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : int = hf_config.architectures[0] if arch.endswith("ForSequenceClassification" ): SCREAMING_SNAKE_CASE_ : Optional[int] = convert_classification(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) elif arch.endswith("ForAudioFrameClassification" ): SCREAMING_SNAKE_CASE_ : Any = convert_diarization(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) elif arch.endswith("ForXVector" ): SCREAMING_SNAKE_CASE_ : int = convert_xvector(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) else: raise NotImplementedError(f'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: SCREAMING_SNAKE_CASE_ : int = checkpoint["Featurizer"]["weights"] hf_feature_extractor.save_pretrained(lowerCAmelCase ) hf_model.save_pretrained(lowerCAmelCase ) if __name__ == "__main__": __lowerCamelCase : List[Any] = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') __lowerCamelCase : Optional[int] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
216
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable __lowerCamelCase : Any = {'''configuration_dpt''': ['''DPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DPTConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : str = ['''DPTFeatureExtractor'''] __lowerCamelCase : List[Any] = ['''DPTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : int = [ '''DPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DPTForDepthEstimation''', '''DPTForSemanticSegmentation''', '''DPTModel''', '''DPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys __lowerCamelCase : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
216
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ : Union[str, Any] = { 'configuration_llama': ['LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LlamaConfig'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : int = ['LlamaTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : str = ['LlamaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : Optional[Any] = [ 'LlamaForCausalLM', 'LlamaModel', 'LlamaPreTrainedModel', 'LlamaForSequenceClassification', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys lowerCAmelCase__ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
632
"""simple docstring""" lowerCAmelCase__ : Tuple = range(2, 20 + 1) lowerCAmelCase__ : Optional[Any] = [10**k for k in range(ks[-1] + 1)] lowerCAmelCase__ : dict[int, dict[int, list[list[int]]]] = {} def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = sum(a_i[j] for j in range(lowerCamelCase , len(lowerCamelCase ) ) ) UpperCAmelCase__ = sum(a_i[j] * base[j] for j in range(min(len(lowerCamelCase ) , lowerCamelCase ) ) ) UpperCAmelCase__ , UpperCAmelCase__ = 0, 0 UpperCAmelCase__ = n - i UpperCAmelCase__ = memo.get(lowerCamelCase ) if sub_memo is not None: UpperCAmelCase__ = sub_memo.get(lowerCamelCase ) if jumps is not None and len(lowerCamelCase ) > 0: # find and make the largest jump without going over UpperCAmelCase__ = -1 for _k in range(len(lowerCamelCase ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: UpperCAmelCase__ = _k break if max_jump >= 0: UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = jumps[max_jump] # since the difference between jumps is cached, add c UpperCAmelCase__ = diff + c for j in range(min(lowerCamelCase , len(lowerCamelCase ) ) ): UpperCAmelCase__ , UpperCAmelCase__ = divmod(lowerCamelCase , 1_0 ) if new_c > 0: add(lowerCamelCase , lowerCamelCase , lowerCamelCase ) else: UpperCAmelCase__ = [] else: UpperCAmelCase__ = {c: []} UpperCAmelCase__ = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps UpperCAmelCase__ , UpperCAmelCase__ = next_term(lowerCamelCase , k - 1 , i + dn , lowerCamelCase ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead UpperCAmelCase__ , UpperCAmelCase__ = compute(lowerCamelCase , lowerCamelCase , i + dn , lowerCamelCase ) diff += _diff dn += terms_jumped UpperCAmelCase__ = sub_memo[c] # keep jumps sorted by # of terms skipped UpperCAmelCase__ = 0 while j < len(lowerCamelCase ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(lowerCamelCase , (diff, dn, k) ) return (diff, dn) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): if i >= n: return 0, i if k > len(lowerCamelCase ): a_i.extend([0 for _ in range(k - len(lowerCamelCase ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) UpperCAmelCase__ = i UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = 0, 0, 0 for j in range(len(lowerCamelCase ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 UpperCAmelCase__ = ds_c + ds_b diff += addend UpperCAmelCase__ = 0 for j in range(lowerCamelCase ): UpperCAmelCase__ = a_i[j] + addend UpperCAmelCase__ , UpperCAmelCase__ = divmod(lowerCamelCase , 1_0 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return diff, i - start_i def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): for j in range(lowerCamelCase , len(lowerCamelCase ) ): UpperCAmelCase__ = digits[j] + addend if s >= 1_0: UpperCAmelCase__ , UpperCAmelCase__ = divmod(lowerCamelCase , 1_0 ) UpperCAmelCase__ = addend // 1_0 + quotient else: UpperCAmelCase__ = s UpperCAmelCase__ = addend // 1_0 if addend == 0: break while addend > 0: UpperCAmelCase__ , UpperCAmelCase__ = divmod(lowerCamelCase , 1_0 ) digits.append(lowerCamelCase ) def a_ ( lowerCamelCase = 1_0**1_5 ): UpperCAmelCase__ = [1] UpperCAmelCase__ = 1 UpperCAmelCase__ = 0 while True: UpperCAmelCase__ , UpperCAmelCase__ = next_term(lowerCamelCase , 2_0 , i + dn , lowerCamelCase ) dn += terms_jumped if dn == n - i: break UpperCAmelCase__ = 0 for j in range(len(lowerCamelCase ) ): a_n += digits[j] * 1_0**j return a_n if __name__ == "__main__": print(F"""{solution() = }""")
632
1
"""simple docstring""" __magic_name__ : Optional[Any] = {} def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible 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 UpperCamelCase : List[Any] = (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 UpperCamelCase : int = _calculate(days - 1 , lowercase__ , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 UpperCamelCase : Optional[int] = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter UpperCamelCase : Any = _calculate(days - 1 , lowercase__ , 0 ) UpperCamelCase : int = state_late + state_absent + state_ontime UpperCamelCase : str = prizestrings return prizestrings def UpperCamelCase (SCREAMING_SNAKE_CASE = 30 ): return _calculate(lowercase__ , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
102
"""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 _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { """microsoft/beit-base-patch16-224-pt22k""": ( """https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json""" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __a ( __magic_name__ ): """simple docstring""" __UpperCamelCase : Union[str, Any] = 'beit' def __init__( self , snake_case=8_192 , snake_case=768 , snake_case=12 , snake_case=12 , snake_case=3_072 , snake_case="gelu" , snake_case=0.0 , snake_case=0.0 , snake_case=0.02 , snake_case=1e-12 , snake_case=224 , snake_case=16 , snake_case=3 , snake_case=False , snake_case=False , snake_case=False , snake_case=False , snake_case=0.1 , snake_case=0.1 , snake_case=True , snake_case=[3, 5, 7, 11] , snake_case=[1, 2, 3, 6] , snake_case=True , snake_case=0.4 , snake_case=256 , snake_case=1 , snake_case=False , snake_case=255 , **snake_case , ): """simple docstring""" super().__init__(**snake_case ) lowerCAmelCase__ : Union[str, Any] = vocab_size lowerCAmelCase__ : int = hidden_size lowerCAmelCase__ : str = num_hidden_layers lowerCAmelCase__ : Any = num_attention_heads lowerCAmelCase__ : List[str] = intermediate_size lowerCAmelCase__ : int = hidden_act lowerCAmelCase__ : Optional[Any] = hidden_dropout_prob lowerCAmelCase__ : str = attention_probs_dropout_prob lowerCAmelCase__ : Optional[int] = initializer_range lowerCAmelCase__ : Dict = layer_norm_eps lowerCAmelCase__ : int = image_size lowerCAmelCase__ : Union[str, Any] = patch_size lowerCAmelCase__ : Dict = num_channels lowerCAmelCase__ : Optional[Any] = use_mask_token lowerCAmelCase__ : Dict = use_absolute_position_embeddings lowerCAmelCase__ : Any = use_relative_position_bias lowerCAmelCase__ : List[Any] = use_shared_relative_position_bias lowerCAmelCase__ : Dict = layer_scale_init_value lowerCAmelCase__ : Optional[int] = drop_path_rate lowerCAmelCase__ : Optional[Any] = use_mean_pooling # decode head attributes (semantic segmentation) lowerCAmelCase__ : Optional[int] = out_indices lowerCAmelCase__ : List[Any] = pool_scales # auxiliary head attributes (semantic segmentation) lowerCAmelCase__ : List[Any] = use_auxiliary_head lowerCAmelCase__ : Optional[int] = auxiliary_loss_weight lowerCAmelCase__ : List[str] = auxiliary_channels lowerCAmelCase__ : Optional[Any] = auxiliary_num_convs lowerCAmelCase__ : Union[str, Any] = auxiliary_concat_input lowerCAmelCase__ : List[str] = semantic_loss_ignore_index class __a ( __magic_name__ ): """simple docstring""" __UpperCamelCase : List[str] = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE_ ( self ): """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self ): """simple docstring""" return 1e-4
453
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) A__ : Optional[int] = { 'configuration_perceiver': ['PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PerceiverConfig', 'PerceiverOnnxConfig'], 'tokenization_perceiver': ['PerceiverTokenizer'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[Any] = ['PerceiverFeatureExtractor'] A__ : Optional[int] = ['PerceiverImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[str] = [ 'PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PerceiverForImageClassificationConvProcessing', 'PerceiverForImageClassificationFourier', 'PerceiverForImageClassificationLearned', 'PerceiverForMaskedLM', 'PerceiverForMultimodalAutoencoding', 'PerceiverForOpticalFlow', 'PerceiverForSequenceClassification', 'PerceiverLayer', 'PerceiverModel', 'PerceiverPreTrainedModel', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
671
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class _UpperCAmelCase : """simple docstring""" lowercase__ = 42 lowercase__ = 42 class _UpperCAmelCase : """simple docstring""" def __init__( self : str, lowerCamelCase : int ): '''simple docstring''' lowercase__ = [[] for _ in range(lowerCamelCase )] lowercase__ = size def __getitem__( self : Optional[Any], lowerCamelCase : int ): '''simple docstring''' return iter(self._graph[vertex] ) @property def lowercase__ ( self : str ): '''simple docstring''' return self._size def lowercase__ ( self : Union[str, Any], lowerCamelCase : int, lowerCamelCase : int, lowerCamelCase : int ): '''simple docstring''' if weight not in (0, 1): raise ValueError('''Edge weight must be either 0 or 1.''' ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError('''Vertex indexes must be in [0; size).''' ) self._graph[from_vertex].append(Edge(lowerCamelCase, lowerCamelCase ) ) def lowercase__ ( self : Optional[int], lowerCamelCase : int, lowerCamelCase : int ): '''simple docstring''' lowercase__ = deque([start_vertex] ) lowercase__ = [None] * self.size lowercase__ = 0 while queue: lowercase__ = queue.popleft() lowercase__ = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: lowercase__ = current_distance + edge.weight lowercase__ = distances[edge.destination_vertex] if ( isinstance(lowerCamelCase, lowerCamelCase ) and new_distance >= dest_vertex_distance ): continue lowercase__ = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError('''No path from start_vertex to finish_vertex.''' ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
671
1
"""simple docstring""" import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort A = logging.get_logger(__name__) A = { """tensor(bool)""": np.bool_, """tensor(int8)""": np.inta, """tensor(uint8)""": np.uinta, """tensor(int16)""": np.intaa, """tensor(uint16)""": np.uintaa, """tensor(int32)""": np.intaa, """tensor(uint32)""": np.uintaa, """tensor(int64)""": np.intaa, """tensor(uint64)""": np.uintaa, """tensor(float16)""": np.floataa, """tensor(float)""": np.floataa, """tensor(double)""": np.floataa, } class a__ : def __init__( self : Dict , UpperCamelCase_ : Union[str, Any]=None , **UpperCamelCase_ : Optional[Any]): """simple docstring""" logger.info("`diffusers.OnnxRuntimeModel` is experimental and might change in the future.") __UpperCAmelCase : List[Any] = model __UpperCAmelCase : Optional[Any] = kwargs.get("model_save_dir" , UpperCamelCase_) __UpperCAmelCase : Optional[int] = kwargs.get("latest_model_name" , UpperCamelCase_) def __call__( self : Optional[int] , **UpperCamelCase_ : Any): """simple docstring""" __UpperCAmelCase : List[str] = {k: np.array(UpperCamelCase_) for k, v in kwargs.items()} return self.model.run(UpperCamelCase_ , UpperCamelCase_) @staticmethod def a_ ( UpperCamelCase_ : Union[str, Path] , UpperCamelCase_ : str=None , UpperCamelCase_ : str=None): """simple docstring""" if provider is None: logger.info("No onnxruntime provider specified, using CPUExecutionProvider") __UpperCAmelCase : Any = "CPUExecutionProvider" return ort.InferenceSession(UpperCamelCase_ , providers=[provider] , sess_options=UpperCamelCase_) def a_ ( self : Dict , UpperCamelCase_ : Union[str, Path] , UpperCamelCase_ : Optional[str] = None , **UpperCamelCase_ : int): """simple docstring""" __UpperCAmelCase : List[Any] = file_name if file_name is not None else ONNX_WEIGHTS_NAME __UpperCAmelCase : Dict = self.model_save_dir.joinpath(self.latest_model_name) __UpperCAmelCase : List[str] = Path(UpperCamelCase_).joinpath(UpperCamelCase_) try: shutil.copyfile(UpperCamelCase_ , UpperCamelCase_) except shutil.SameFileError: pass # copy external weights (for models >2GB) __UpperCAmelCase : Tuple = self.model_save_dir.joinpath(UpperCamelCase_) if src_path.exists(): __UpperCAmelCase : int = Path(UpperCamelCase_).joinpath(UpperCamelCase_) try: shutil.copyfile(UpperCamelCase_ , UpperCamelCase_) except shutil.SameFileError: pass def a_ ( self : Tuple , UpperCamelCase_ : Union[str, os.PathLike] , **UpperCamelCase_ : List[str] , ): """simple docstring""" if os.path.isfile(UpperCamelCase_): logger.error(F"Provided path ({save_directory}) should be a directory, not a file") return os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_) # saving model weights/files self._save_pretrained(UpperCamelCase_ , **UpperCamelCase_) @classmethod def a_ ( cls : Tuple , UpperCamelCase_ : Union[str, Path] , UpperCamelCase_ : Optional[Union[bool, str, None]] = None , UpperCamelCase_ : Optional[Union[str, None]] = None , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[str] = None , UpperCamelCase_ : Optional[str] = None , UpperCamelCase_ : Optional[str] = None , UpperCamelCase_ : Optional["ort.SessionOptions"] = None , **UpperCamelCase_ : List[Any] , ): """simple docstring""" __UpperCAmelCase : List[str] = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(UpperCamelCase_): __UpperCAmelCase : int = OnnxRuntimeModel.load_model( os.path.join(UpperCamelCase_ , UpperCamelCase_) , provider=UpperCamelCase_ , sess_options=UpperCamelCase_) __UpperCAmelCase : Dict = Path(UpperCamelCase_) # load model from hub else: # download model __UpperCAmelCase : Any = hf_hub_download( repo_id=UpperCamelCase_ , filename=UpperCamelCase_ , use_auth_token=UpperCamelCase_ , revision=UpperCamelCase_ , cache_dir=UpperCamelCase_ , force_download=UpperCamelCase_ , ) __UpperCAmelCase : Optional[int] = Path(UpperCamelCase_).parent __UpperCAmelCase : List[str] = Path(UpperCamelCase_).name __UpperCAmelCase : Union[str, Any] = OnnxRuntimeModel.load_model(UpperCamelCase_ , provider=UpperCamelCase_ , sess_options=UpperCamelCase_) return cls(model=UpperCamelCase_ , **UpperCamelCase_) @classmethod def a_ ( cls : List[Any] , UpperCamelCase_ : Union[str, Path] , UpperCamelCase_ : bool = True , UpperCamelCase_ : Optional[str] = None , UpperCamelCase_ : Optional[str] = None , **UpperCamelCase_ : Optional[int] , ): """simple docstring""" __UpperCAmelCase : Optional[int] = None if len(str(UpperCamelCase_).split("@")) == 2: __UpperCAmelCase , __UpperCAmelCase : Any = model_id.split("@") return cls._from_pretrained( model_id=UpperCamelCase_ , revision=UpperCamelCase_ , cache_dir=UpperCamelCase_ , force_download=UpperCamelCase_ , use_auth_token=UpperCamelCase_ , **UpperCamelCase_ , )
77
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class lowercase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self , lowerCamelCase__ , lowerCamelCase__=1_3 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=9_9 , lowerCamelCase__=3_2 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=3_7 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=5_1_2 , lowerCamelCase__=1_6 , lowerCamelCase__=2 , lowerCamelCase__=0.02 , lowerCamelCase__=4 , ): '''simple docstring''' UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_attention_mask UpperCamelCase = use_token_type_ids UpperCamelCase = use_labels UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = type_sequence_label_size UpperCamelCase = initializer_range UpperCamelCase = num_choices def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = None if self.use_attention_mask: UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase = None if self.use_token_type_ids: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCamelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = True UpperCamelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class lowercase__ ( snake_case_, unittest.TestCase ): '''simple docstring''' _snake_case = True _snake_case = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def UpperCAmelCase ( self ): '''simple docstring''' UpperCamelCase = FlaxRobertaModelTester(self ) @slow def UpperCAmelCase ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: UpperCamelCase = model_class_name.from_pretrained('''roberta-base''' , from_pt=lowerCamelCase__ ) UpperCamelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase__ )
212
0
"""simple docstring""" def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' return " ".join( """""".join(word[::-1] ) if len(lowerCAmelCase ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('''Hey wollef sroirraw'''))
378
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=13 , snake_case__=2 , snake_case__=24 , snake_case__=16 , snake_case__=True , snake_case__=True , snake_case__=32 , snake_case__=5 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=10 , snake_case__=0.02 , snake_case__=None , snake_case__=2 , snake_case__=2 , ) -> List[Any]: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = patch_size UpperCAmelCase = max_length UpperCAmelCase = num_mel_bins UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = scope UpperCAmelCase = frequency_stride UpperCAmelCase = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) UpperCAmelCase = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 UpperCAmelCase = (self.max_length - self.patch_size) // self.time_stride + 1 UpperCAmelCase = frequency_out_dimension * time_out_dimension UpperCAmelCase = num_patches + 2 def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = self.get_config() return config, input_values, labels def UpperCamelCase_ ( self ) -> int: """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ) -> List[Any]: """simple docstring""" UpperCAmelCase = ASTModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = {"""input_values""": input_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( a_ , a_ , unittest.TestCase ): _A : Any = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) _A : Union[str, Any] = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) _A : Any = False _A : Dict = False _A : Optional[Any] = False _A : List[str] = False def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = ASTModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ , hidden_size=37 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""AST does not use inputs_embeds""" ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" pass def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(snake_case__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case__ , nn.Linear ) ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(snake_case__ ) UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ["""input_values"""] self.assertListEqual(arg_names[:1] , snake_case__ ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) @slow def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = ASTModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" ) UpperCAmelCase , UpperCAmelCase = torchaudio.load(lowerCAmelCase ) return audio, sampling_rate @require_torch @require_torchaudio class UpperCamelCase_ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self ) -> int: """simple docstring""" return ( ASTFeatureExtractor.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593""" ) if is_torchaudio_available() else None ) @slow def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.default_feature_extractor UpperCAmelCase = ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593""" ).to(snake_case__ ) UpperCAmelCase = self.default_feature_extractor UpperCAmelCase , UpperCAmelCase = prepare_audio() UpperCAmelCase = audio.squeeze().numpy() UpperCAmelCase = feature_extractor(snake_case__ , sampling_rate=snake_case__ , return_tensors="""pt""" ).to(snake_case__ ) # forward pass with torch.no_grad(): UpperCAmelCase = model(**snake_case__ ) # verify the logits UpperCAmelCase = torch.Size((1, 5_27) ) self.assertEqual(outputs.logits.shape , snake_case__ ) UpperCAmelCase = torch.tensor([-0.8_760, -7.0_042, -8.6_602] ).to(snake_case__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case__ , atol=1e-4 ) )
378
1
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = ["image_processor", "tokenizer"] __UpperCamelCase = "CLIPImageProcessor" __UpperCamelCase = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : Optional[Any] , A__ : List[str]=None , A__ : Tuple=None , **A__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , A__ , ) a__ : Optional[int] = kwargs.pop('''feature_extractor''' ) a__ : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(A__ , A__ ) def __call__( self : List[str] , A__ : Tuple=None , A__ : Dict=None , A__ : Optional[int]=None , **A__ : int ) -> str: '''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__ : Optional[Any] = self.tokenizer(A__ , return_tensors=A__ , **A__ ) if images is not None: a__ : List[str] = self.image_processor(A__ , return_tensors=A__ , **A__ ) if text is not None and images is not None: a__ : Dict = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**A__ ) , tensor_type=A__ ) def __lowerCAmelCase ( self : Dict , *A__ : Optional[int] , **A__ : Dict ) -> Union[str, Any]: '''simple docstring''' return self.tokenizer.batch_decode(*A__ , **A__ ) def __lowerCAmelCase ( self : Tuple , *A__ : int , **A__ : str ) -> List[str]: '''simple docstring''' return self.tokenizer.decode(*A__ , **A__ ) @property def __lowerCAmelCase ( self : Any ) -> Union[str, Any]: '''simple docstring''' a__ : int = self.tokenizer.model_input_names a__ : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , A__ , ) return self.image_processor_class @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , A__ , ) return self.image_processor
688
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
1
'''simple docstring''' from math import isqrt def _UpperCAmelCase ( __A : int ): a_ : Dict = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __A , __A ): a_ : str = False return [i for i in range(2 , __A ) if is_prime[i]] def _UpperCAmelCase ( __A : int = 10**8 ): a_ : Tuple = calculate_prime_numbers(max_number // 2 ) a_ : Union[str, Any] = 0 a_ : Any = 0 a_ : Optional[Any] = len(__A ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F"""{solution() = }""")
666
'''simple docstring''' import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): snake_case__ = LongformerTokenizer snake_case__ = True snake_case__ = LongformerTokenizerFast snake_case__ = True def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt a_ : Tuple = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] a_ : Optional[Any] = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) a_ : Union[str, Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] a_ : Any = {'''unk_token''': '''<unk>'''} a_ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) a_ : Optional[int] = 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(__SCREAMING_SNAKE_CASE ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) def SCREAMING_SNAKE_CASE ( self : Any , **__SCREAMING_SNAKE_CASE : Any ) -> int: kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **__SCREAMING_SNAKE_CASE : List[Any] ) -> List[str]: kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Any: a_ : Union[str, Any] = '''lower newer''' a_ : List[Any] = '''lower newer''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: a_ : Optional[Any] = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) a_ : List[str] = '''lower newer''' a_ : str = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] a_ : Optional[int] = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) # , add_prefix_space=True) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) a_ : Dict = tokens + [tokenizer.unk_token] a_ : Any = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: a_ : Union[str, Any] = self.get_tokenizer() self.assertListEqual(tokenizer.encode('''Hello world!''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode('''Hello world! cécé herlolip 418''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: a_ : Dict = self.tokenizer_class.from_pretrained('''allenai/longformer-base-4096''' ) a_ : Tuple = tokenizer.encode('''sequence builders''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) a_ : Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) a_ : Any = tokenizer.encode( '''sequence builders''' , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) a_ : Any = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) a_ : List[str] = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE ) a_ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def SCREAMING_SNAKE_CASE ( self : str ) -> int: a_ : str = self.get_tokenizer() a_ : int = '''Encode this sequence.''' a_ : List[str] = tokenizer.byte_encoder[''' '''.encode('''utf-8''' )[0]] # Testing encoder arguments a_ : Dict = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) a_ : Optional[Any] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) a_ : Dict = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) a_ : Any = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) tokenizer.add_special_tokens({'''bos_token''': '''<s>'''} ) a_ : Dict = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) a_ : Dict = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Testing spaces after special tokens a_ : Optional[Any] = '''<mask>''' tokenizer.add_special_tokens( {'''mask_token''': AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE )} ) # mask token has a left space a_ : Optional[int] = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) a_ : List[Any] = '''Encode <mask> sequence''' a_ : List[str] = '''Encode <mask>sequence''' a_ : int = tokenizer.encode(__SCREAMING_SNAKE_CASE ) a_ : Optional[int] = encoded.index(__SCREAMING_SNAKE_CASE ) a_ : Optional[int] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) a_ : Union[str, Any] = tokenizer.encode(__SCREAMING_SNAKE_CASE ) a_ : Optional[int] = encoded.index(__SCREAMING_SNAKE_CASE ) a_ : str = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: pass def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): a_ : Any = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) a_ : Any = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) a_ : str = '''A, <mask> AllenNLP sentence.''' a_ : List[Any] = tokenizer_r.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) a_ : Dict = tokenizer_p.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['''token_type_ids'''] ) , sum(tokens_p['''token_type_ids'''] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) , sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) , ) a_ : str = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) a_ : Tuple = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): a_ : Any = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) a_ : Union[str, Any] = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) a_ : str = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['''add_prefix_space'''] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state['''add_prefix_space'''] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state['''trim_offsets'''] , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): a_ : Dict = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` a_ : Union[str, Any] = f'{text_of_1_token} {text_of_1_token}' a_ : Any = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) a_ : Optional[int] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) a_ : Any = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) a_ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) a_ : int = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) a_ : Union[str, Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) a_ : Tuple = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) a_ : Any = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) a_ : Union[str, Any] = f' {text}' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) a_ : str = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) a_ : int = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ) + 1, 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) a_ : int = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) a_ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) a_ : Optional[int] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) a_ : int = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , )
666
1
'''simple docstring''' # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = None def _lowercase ( __A ,__A=0.999 ,__A="cosine" ,): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(__A ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__A ): return math.exp(t * -12.0 ) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" ) __UpperCamelCase = [] for i in range(__A ): __UpperCamelCase = i / num_diffusion_timesteps __UpperCamelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__A ) / alpha_bar_fn(__A ) ,__A ) ) return torch.tensor(__A ,dtype=torch.floataa ) class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 1 @register_to_config def __init__( self , lowercase = 1_0_0_0 , lowercase = 0.0_001 , lowercase = 0.02 , lowercase = "linear" , lowercase = None , lowercase = True , lowercase = True , lowercase = 0 , lowercase = "epsilon" , lowercase = 1.0 , **lowercase , ) -> Dict: if kwargs.get("""set_alpha_to_one""" , lowercase ) is not None: __UpperCamelCase = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , lowercase , standard_warn=lowercase ) __UpperCamelCase = kwargs["""set_alpha_to_one"""] if trained_betas is not None: __UpperCamelCase = torch.tensor(lowercase , dtype=torch.floataa ) elif beta_schedule == "linear": __UpperCamelCase = torch.linspace(lowercase , lowercase , lowercase , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __UpperCamelCase = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowercase , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __UpperCamelCase = betas_for_alpha_bar(lowercase ) else: raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}" ) __UpperCamelCase = 1.0 - self.betas __UpperCamelCase = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. __UpperCamelCase = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution __UpperCamelCase = 1.0 # setable values __UpperCamelCase = None __UpperCamelCase = torch.from_numpy(np.arange(0 , lowercase ).copy().astype(np.intaa ) ) def __lowerCamelCase ( self , lowercase , lowercase = None ) -> torch.FloatTensor: return sample def __lowerCamelCase ( self , lowercase , lowercase = None ) -> Optional[int]: if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:" f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle" f" maximal {self.config.num_train_timesteps} timesteps." ) __UpperCamelCase = num_inference_steps __UpperCamelCase = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __UpperCamelCase = (np.arange(0 , lowercase ) * step_ratio).round().copy().astype(np.intaa ) __UpperCamelCase = torch.from_numpy(lowercase ).to(lowercase ) self.timesteps += self.config.steps_offset def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase = 0.0 , lowercase = False , lowercase = None , lowercase = True , ) -> Union[DDIMSchedulerOutput, Tuple]: # 1. get previous step value (=t+1) __UpperCamelCase = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process __UpperCamelCase = self.alphas_cumprod[timestep] __UpperCamelCase = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) __UpperCamelCase = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": __UpperCamelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 __UpperCamelCase = model_output elif self.config.prediction_type == "sample": __UpperCamelCase = model_output __UpperCamelCase = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": __UpperCamelCase = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output __UpperCamelCase = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: __UpperCamelCase = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __UpperCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __UpperCamelCase = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=lowercase , pred_original_sample=lowercase ) def __len__( self ) -> int: return self.config.num_train_timesteps
601
'''simple docstring''' from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''image_processor''', '''tokenizer'''] __SCREAMING_SNAKE_CASE = '''Pix2StructImageProcessor''' __SCREAMING_SNAKE_CASE = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , lowercase , lowercase ) -> Any: __UpperCamelCase = False super().__init__(lowercase , lowercase ) def __call__( self , lowercase=None , lowercase = None , lowercase = True , lowercase = False , lowercase = None , lowercase = None , lowercase = 2_0_4_8 , lowercase = 0 , lowercase = None , lowercase = None , lowercase = False , lowercase = False , lowercase = False , lowercase = False , lowercase = False , lowercase = True , lowercase = None , **lowercase , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None and not self.image_processor.is_vqa: __UpperCamelCase = self.tokenizer __UpperCamelCase = self.tokenizer( text=lowercase , add_special_tokens=lowercase , padding=lowercase , truncation=lowercase , max_length=lowercase , stride=lowercase , pad_to_multiple_of=lowercase , return_attention_mask=lowercase , return_overflowing_tokens=lowercase , return_special_tokens_mask=lowercase , return_offsets_mapping=lowercase , return_token_type_ids=lowercase , return_length=lowercase , verbose=lowercase , return_tensors=lowercase , **lowercase , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __UpperCamelCase = self.image_processor( lowercase , return_tensors=lowercase , max_patches=lowercase , **lowercase ) else: # add pixel_values and bbox __UpperCamelCase = self.image_processor( lowercase , return_tensors=lowercase , max_patches=lowercase , header_text=lowercase , **lowercase ) if text is not None and not self.image_processor.is_vqa: __UpperCamelCase = self.tokenizer( text=lowercase , add_special_tokens=lowercase , padding=lowercase , truncation=lowercase , max_length=lowercase , stride=lowercase , pad_to_multiple_of=lowercase , return_attention_mask=lowercase , return_overflowing_tokens=lowercase , return_special_tokens_mask=lowercase , return_offsets_mapping=lowercase , return_token_type_ids=lowercase , return_length=lowercase , verbose=lowercase , return_tensors=lowercase , **lowercase , ) if "attention_mask" in text_encoding: __UpperCamelCase = text_encoding.pop("""attention_mask""" ) if "input_ids" in text_encoding: __UpperCamelCase = text_encoding.pop("""input_ids""" ) else: __UpperCamelCase = None if text_encoding is not None: encoding_image_processor.update(lowercase ) return encoding_image_processor def __lowerCamelCase ( self , *lowercase , **lowercase ) -> Tuple: return self.tokenizer.batch_decode(*lowercase , **lowercase ) def __lowerCamelCase ( self , *lowercase , **lowercase ) -> List[str]: return self.tokenizer.decode(*lowercase , **lowercase ) @property def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.tokenizer.model_input_names __UpperCamelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
601
1
from __future__ import annotations from collections.abc import MutableSequence class A__ : def __init__( self : int , a : int , a : MutableSequence[float] ): '''simple docstring''' if len(a ) != degree + 1: raise ValueError( 'The number of coefficients should be equal to the degree + 1.' ) lowerCAmelCase__ : list[float] = list(a ) lowerCAmelCase__ : Tuple = degree def __add__( self : Optional[int] , a : Polynomial ): '''simple docstring''' if self.degree > polynomial_a.degree: lowerCAmelCase__ : List[str] = self.coefficients[:] for i in range(polynomial_a.degree + 1 ): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree , a ) else: lowerCAmelCase__ : int = polynomial_a.coefficients[:] for i in range(self.degree + 1 ): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree , a ) def __sub__( self : Optional[Any] , a : Polynomial ): '''simple docstring''' return self + polynomial_a * Polynomial(0 , [-1] ) def __neg__( self : List[Any] ): '''simple docstring''' return Polynomial(self.degree , [-c for c in self.coefficients] ) def __mul__( self : Dict , a : Polynomial ): '''simple docstring''' lowerCAmelCase__ : 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 , a ) def _lowerCamelCase ( self : Optional[int] , a : int | float ): '''simple docstring''' lowerCAmelCase__ : int | float = 0 for i in range(self.degree + 1 ): result += self.coefficients[i] * (substitution**i) return result def __str__( self : Any ): '''simple docstring''' lowerCAmelCase__ : str = '' 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(a ) return polynomial def __repr__( self : str ): '''simple docstring''' return self.__str__() def _lowerCamelCase ( self : Any ): '''simple docstring''' lowerCAmelCase__ : list[float] = [0] * self.degree for i in range(self.degree ): lowerCAmelCase__ : Dict = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 , a ) def _lowerCamelCase ( self : Tuple , a : int | float = 0 ): '''simple docstring''' lowerCAmelCase__ : list[float] = [0] * (self.degree + 2) lowerCAmelCase__ : Optional[Any] = constant for i in range(self.degree + 1 ): lowerCAmelCase__ : Tuple = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 , a ) def __eq__( self : Optional[Any] , a : object ): '''simple docstring''' if not isinstance(a , a ): 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 : Optional[int] , a : object ): '''simple docstring''' return not self.__eq__(a )
69
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser lowerCamelCase__ = logging.getLogger(__name__) torch.set_grad_enabled(False) lowerCamelCase__ = """cuda""" if torch.cuda.is_available() else """cpu""" def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=" " ) -> List[str]: lowerCAmelCase__ : Optional[Any] = text.split(SCREAMING_SNAKE_CASE_ ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )] def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> dict: lowerCAmelCase__ , lowerCAmelCase__ : int = [], [] for title, text in zip(documents['title'] , documents['text'] ): if text is not None: for passage in split_text(SCREAMING_SNAKE_CASE_ ): titles.append(title if title is not None else '' ) texts.append(SCREAMING_SNAKE_CASE_ ) return {"title": titles, "text": texts} def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> dict: lowerCAmelCase__ : List[str] = ctx_tokenizer( documents['title'] , documents['text'] , truncation=SCREAMING_SNAKE_CASE_ , padding='longest' , return_tensors='pt' )['input_ids'] lowerCAmelCase__ : Tuple = ctx_encoder(input_ids.to(device=SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: ###################################### logger.info('Step 1 - Create the dataset' ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way lowerCAmelCase__ : str = load_dataset( 'csv' , data_files=[rag_example_args.csv_path] , split='train' , delimiter='\t' , column_names=['title', 'text'] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words lowerCAmelCase__ : Optional[Any] = dataset.map(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , num_proc=processing_args.num_proc ) # And compute the embeddings lowerCAmelCase__ : List[str] = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : str = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) lowerCAmelCase__ : List[Any] = Features( {'text': Value('string' ), 'title': Value('string' ), 'embeddings': Sequence(Value('float32' ) )} ) # optional, save as float32 instead of float64 to save space lowerCAmelCase__ : List[Any] = dataset.map( partial(SCREAMING_SNAKE_CASE_ , ctx_encoder=SCREAMING_SNAKE_CASE_ , ctx_tokenizer=SCREAMING_SNAKE_CASE_ ) , batched=SCREAMING_SNAKE_CASE_ , batch_size=processing_args.batch_size , features=SCREAMING_SNAKE_CASE_ , ) # And finally save your dataset lowerCAmelCase__ : Optional[Any] = os.path.join(rag_example_args.output_dir , 'my_knowledge_dataset' ) dataset.save_to_disk(SCREAMING_SNAKE_CASE_ ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info('Step 2 - Index the dataset' ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search lowerCAmelCase__ : Optional[int] = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index('embeddings' , custom_index=SCREAMING_SNAKE_CASE_ ) # And save the index lowerCAmelCase__ : str = os.path.join(rag_example_args.output_dir , 'my_knowledge_dataset_hnsw_index.faiss' ) dataset.get_index('embeddings' ).save(SCREAMING_SNAKE_CASE_ ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class A__ : lowercase = field( default=str(Path(__magic_name__ ).parent / 'test_run' / 'dummy-kb' / 'my_knowledge_dataset.csv' ) , metadata={'help': 'Path to a tab-separated csv file with columns \'title\' and \'text\''} , ) lowercase = field( default=__magic_name__ , metadata={'help': 'Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'} , ) lowercase = field( default='facebook/rag-sequence-nq' , metadata={'help': 'The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''} , ) lowercase = field( default='facebook/dpr-ctx_encoder-multiset-base' , metadata={ 'help': ( 'The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or' ' \'facebook/dpr-ctx_encoder-multiset-base\'' ) } , ) lowercase = field( default=str(Path(__magic_name__ ).parent / 'test_run' / 'dummy-kb' ) , metadata={'help': 'Path to a directory where the dataset passages and the index will be saved'} , ) @dataclass class A__ : lowercase = field( default=__magic_name__ , metadata={ 'help': 'The number of processes to use to split the documents into passages. Default is single process.' } , ) lowercase = field( default=16 , metadata={ 'help': 'The batch size to use when computing the passages embeddings using the DPR context encoder.' } , ) @dataclass class A__ : lowercase = field( default=768 , metadata={'help': 'The dimension of the embeddings to pass to the HNSW Faiss index.'} , ) lowercase = field( default=128 , metadata={ 'help': ( 'The number of bi-directional links created for every new element during the HNSW index construction.' ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) lowerCamelCase__ = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: lowerCamelCase__ = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
69
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "weiweishi/roc-bert-base-zh": "https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json", } class __UpperCAmelCase ( lowerCAmelCase ): '''simple docstring''' _UpperCamelCase = """roc_bert""" def __init__( self : int , _lowercase : Dict=30_522 , _lowercase : List[str]=768 , _lowercase : Union[str, Any]=12 , _lowercase : Tuple=12 , _lowercase : Union[str, Any]=3_072 , _lowercase : Union[str, Any]="gelu" , _lowercase : List[str]=0.1 , _lowercase : str=0.1 , _lowercase : Tuple=512 , _lowercase : List[Any]=2 , _lowercase : Optional[int]=0.02 , _lowercase : Any=1E-12 , _lowercase : Tuple=True , _lowercase : Optional[Any]=0 , _lowercase : Optional[Any]="absolute" , _lowercase : Any=None , _lowercase : List[str]=True , _lowercase : str=True , _lowercase : List[str]=768 , _lowercase : Tuple=910 , _lowercase : Tuple=512 , _lowercase : str=24_858 , _lowercase : Dict=True , **_lowercase : Union[str, Any] , ) -> Optional[int]: 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=_lowercase , **_lowercase)
366
'''simple docstring''' import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class __UpperCAmelCase ( lowerCAmelCase ,lowerCAmelCase ): '''simple docstring''' _UpperCamelCase = 1 @register_to_config def __init__( self : str , _lowercase : int = 1_000 , _lowercase : Optional[Union[np.ndarray, List[float]]] = None) -> List[str]: # set `betas`, `alphas`, `timesteps` self.set_timesteps(_lowercase) # standard deviation of the initial noise distribution A_ = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. A_ = 4 # running values A_ = [] def __snake_case ( self : int , _lowercase : int , _lowercase : Union[str, torch.device] = None) -> Any: A_ = num_inference_steps A_ = torch.linspace(1 , 0 , num_inference_steps + 1)[:-1] A_ = torch.cat([steps, torch.tensor([0.0])]) if self.config.trained_betas is not None: A_ = torch.tensor(self.config.trained_betas , dtype=torch.floataa) else: A_ = torch.sin(steps * math.pi / 2) ** 2 A_ = (1.0 - self.betas**2) ** 0.5 A_ = (torch.atana(self.betas , self.alphas) / math.pi * 2)[:-1] A_ = timesteps.to(_lowercase) A_ = [] def __snake_case ( self : Dict , _lowercase : torch.FloatTensor , _lowercase : int , _lowercase : torch.FloatTensor , _lowercase : bool = True , ) -> Union[SchedulerOutput, Tuple]: if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler') A_ = (self.timesteps == timestep).nonzero().item() A_ = timestep_index + 1 A_ = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(_lowercase) if len(self.ets) == 1: A_ = self.ets[-1] elif len(self.ets) == 2: A_ = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets) == 3: A_ = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: A_ = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) A_ = self._get_prev_sample(_lowercase , _lowercase , _lowercase , _lowercase) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_lowercase) def __snake_case ( self : Dict , _lowercase : torch.FloatTensor , *_lowercase : Optional[Any] , **_lowercase : int) -> torch.FloatTensor: return sample def __snake_case ( self : Optional[int] , _lowercase : Optional[Any] , _lowercase : Dict , _lowercase : Union[str, Any] , _lowercase : Union[str, Any]) -> Union[str, Any]: A_ = self.alphas[timestep_index] A_ = self.betas[timestep_index] A_ = self.alphas[prev_timestep_index] A_ = self.betas[prev_timestep_index] A_ = (sample - sigma * ets) / max(_lowercase , 1E-8) A_ = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : List[str]) -> Union[str, Any]: return self.config.num_train_timesteps
366
1
def UpperCAmelCase__ ( _A , _A ): """simple docstring""" if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
143
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass UpperCamelCase__ = (3, 9, -11, 0, 7, 5, 1, -1) UpperCamelCase__ = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class __lowercase : _lowerCAmelCase = 42 _lowerCAmelCase = 42 class __lowercase : def __init__( self : int , lowercase__ : Iterable[int] ): a_ = None for i in sorted(lowercase__ , reverse=lowercase__ ): a_ = Node(lowercase__ , self.head ) def __iter__( self : str ): a_ = self.head while node: yield node.data a_ = node.next_node def __len__( self : Optional[int] ): return sum(1 for _ in self ) def __str__( self : Optional[Any] ): return " -> ".join([str(lowercase__ ) for node in self] ) def UpperCAmelCase__ ( _A , _A ): """simple docstring""" return SortedLinkedList(list(_A ) + list(_A ) ) if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase__ = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
143
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase_ : Dict = {'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ : int = ['''PLBartTokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ : Optional[int] = [ '''PLBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PLBartForCausalLM''', '''PLBartForConditionalGeneration''', '''PLBartForSequenceClassification''', '''PLBartModel''', '''PLBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys UpperCamelCase_ : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
115
"""simple docstring""" import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model UpperCamelCase_ : List[Any] = '''0.12''' # assumed parallelism: 8 if is_torch_available(): import torch def A_ (__a , __a , __a=None ): '''simple docstring''' if rng is None: A_ = random.Random() A_ = 1 for dim in shape: total_dims *= dim A_ = [] for _ in range(__a ): values.append(rng.randint(0 , vocab_size - 1 ) ) A_ = np.array(__a , dtype=jnp.intaa ).reshape(__a ) return output def A_ (__a , __a=None ): '''simple docstring''' A_ = ids_tensor(__a , vocab_size=2 , rng=__a ) # make sure that at least one token is attended to for each batch A_ = 1 return attn_mask @require_flax class __lowerCAmelCase : """simple docstring""" snake_case = None snake_case = () def lowerCamelCase__ ( self : Any ) -> Tuple: """simple docstring""" A_ , A_ = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 A_ = 2 A_ = inputs["input_ids"].shape[-1] // 2 A_ = inputs["input_ids"][:max_batch_size, :sequence_length] A_ = jnp.ones_like(_snake_case ) A_ = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens A_ = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` A_ = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() A_ = False A_ = max_length A_ = 0 for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model_class.__name__[4:] # Skip the "Flax" at the beginning A_ = getattr(_snake_case , _snake_case ) A_ = pt_model_class(_snake_case ).eval() A_ = load_flax_weights_in_pytorch_model(_snake_case , flax_model.params ) A_ = flax_model.generate(_snake_case ).sequences A_ = pt_model.generate(torch.tensor(_snake_case , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: A_ = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Any ) -> Optional[Any]: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() A_ = False A_ = max_length for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() A_ = True A_ = max_length for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Tuple ) -> Dict: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() A_ = False A_ = max_length A_ = 2 for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() A_ = False A_ = max_length A_ = 2 A_ = 2 for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() A_ = True A_ = max_length A_ = 0.8 A_ = 10 A_ = 0.3 A_ = 1 A_ = 8 A_ = 9 for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : List[str] ) -> Any: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() A_ = max_length A_ = 1 A_ = 8 A_ = 9 for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() A_ = max_length A_ = 2 A_ = 1 A_ = 8 A_ = 9 for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Tuple ) -> Any: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() # pad attention mask on the left A_ = attention_mask.at[(0, 0)].set(0 ) A_ = False A_ = max_length for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case , attention_mask=_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case , attention_mask=_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : List[str] ) -> int: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() # pad attention mask on the left A_ = attention_mask.at[(0, 0)].set(0 ) A_ = True A_ = max_length for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case , attention_mask=_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case , attention_mask=_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Dict ) -> int: """simple docstring""" A_ , A_ , A_ , A_ = self._get_input_ids_and_config() # pad attention mask on the left A_ = attention_mask.at[(0, 0)].set(0 ) A_ = 2 A_ = max_length for model_class in self.all_generative_model_classes: A_ = model_class(_snake_case ) A_ = model.generate(_snake_case , attention_mask=_snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , _snake_case ) A_ = jit(model.generate ) A_ = jit_generate(_snake_case , attention_mask=_snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCamelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" A_ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-bert" ) A_ = FlaxAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) A_ = "Hello world" A_ = tokenizer(_snake_case , return_tensors="np" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(_snake_case , "do_samples" ): model.generate(_snake_case , do_samples=_snake_case ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(_snake_case , "foo" ): A_ = {"foo": "bar"} model.generate(_snake_case , **_snake_case )
115
1
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __A = HUGGINGFACE_HUB_CACHE __A = """config.json""" __A = """diffusion_pytorch_model.bin""" __A = """diffusion_flax_model.msgpack""" __A = """model.onnx""" __A = """diffusion_pytorch_model.safetensors""" __A = """weights.pb""" __A = """https://huggingface.co""" __A = default_cache_path __A = """diffusers_modules""" __A = os.getenv('''HF_MODULES_CACHE''', os.path.join(hf_cache_home, '''modules''')) __A = ["""fp16""", """non-ema"""] __A = """.self_attn"""
700
"""simple docstring""" import math from datetime import datetime, timedelta def lowercase_ ( _lowerCamelCase: int ) -> datetime: '''simple docstring''' __lowerCamelCase : List[Any] = year % 19 __lowerCamelCase : List[str] = year % 4 __lowerCamelCase : Dict = year % 7 __lowerCamelCase : Optional[Any] = math.floor(year / 100 ) __lowerCamelCase : Tuple = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : List[str] = leap_day_inhibits / 4 __lowerCamelCase : Optional[Any] = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Union[str, Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Union[str, 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 (1994, 2000, 2010, 2021, 2023): __A = '''will be''' if year > datetime.now().year else '''was''' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
366
0
'''simple docstring''' from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( 'pipelines_utils', '0.22.0', 'Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.', standard_warn=False, stacklevel=3, )
596
"""simple docstring""" 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, ) UpperCAmelCase_ : int = logging.get_logger(__name__) UpperCAmelCase_ : Dict = 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"""), ] ) UpperCAmelCase_ : Tuple = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _A (__a ) -> str: """simple docstring""" for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: SCREAMING_SNAKE_CASE_ : List[str] = model_type_to_module_name(__a ) SCREAMING_SNAKE_CASE_ : Dict = importlib.import_module(f'.{module_name}' , '''transformers.models''' ) try: return getattr(__a , __a ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(__a , '''__name__''' , __a ) == 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. SCREAMING_SNAKE_CASE_ : Any = importlib.import_module('''transformers''' ) if hasattr(__a , __a ): return getattr(__a , __a ) return None def _A (__a , __a = None , __a = False , __a = False , __a = None , __a = None , __a = None , __a = False , **__a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = get_file_from_repo( __a , __a , cache_dir=__a , force_download=__a , resume_download=__a , proxies=__a , use_auth_token=__a , revision=__a , local_files_only=__a , ) 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(__a , encoding='''utf-8''' ) as reader: return json.load(__a ) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : int): '''simple docstring''' 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(lowercase_) def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] , lowercase_ : List[Any] , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = kwargs.pop('''config''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''trust_remote_code''' , lowercase_) SCREAMING_SNAKE_CASE_ : Any = True SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = FeatureExtractionMixin.get_feature_extractor_dict(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = config_dict.get('''feature_extractor_type''' , lowercase_) SCREAMING_SNAKE_CASE_ : str = None if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {}): SCREAMING_SNAKE_CASE_ : Optional[int] = 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(lowercase_ , lowercase_): SCREAMING_SNAKE_CASE_ : Any = AutoConfig.from_pretrained(lowercase_ , **lowercase_) # It could be in `config.feature_extractor_type`` SCREAMING_SNAKE_CASE_ : Union[str, Any] = getattr(lowercase_ , '''feature_extractor_type''' , lowercase_) if hasattr(lowercase_ , '''auto_map''') and "AutoFeatureExtractor" in config.auto_map: SCREAMING_SNAKE_CASE_ : Dict = config.auto_map['''AutoFeatureExtractor'''] if feature_extractor_class is not None: SCREAMING_SNAKE_CASE_ : Dict = feature_extractor_class_from_name(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = feature_extractor_auto_map is not None SCREAMING_SNAKE_CASE_ : Dict = feature_extractor_class is not None or type(lowercase_) in FEATURE_EXTRACTOR_MAPPING SCREAMING_SNAKE_CASE_ : Optional[int] = resolve_trust_remote_code( lowercase_ , lowercase_ , lowercase_ , lowercase_) if has_remote_code and trust_remote_code: SCREAMING_SNAKE_CASE_ : Dict = get_class_from_dynamic_module( lowercase_ , lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Any = kwargs.pop('''code_revision''' , lowercase_) if os.path.isdir(lowercase_): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(lowercase_ , **lowercase_) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(lowercase_ , **lowercase_) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(lowercase_) in FEATURE_EXTRACTOR_MAPPING: SCREAMING_SNAKE_CASE_ : Any = FEATURE_EXTRACTOR_MAPPING[type(lowercase_)] return feature_extractor_class.from_dict(lowercase_ , **lowercase_) 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 _SCREAMING_SNAKE_CASE ( lowercase_ : Any , lowercase_ : List[Any]): '''simple docstring''' FEATURE_EXTRACTOR_MAPPING.register(lowercase_ , lowercase_)
512
0
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( "compression_format, is_archive" , [ ("7z", True), ("bz2", False), ("gzip", False), ("lz4", False), ("tar", True), ("xz", False), ("zip", True), ("zstd", False), ] , ) def __lowercase ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : int , ): SCREAMING_SNAKE_CASE__ = { "7z": (seven_zip_file, SevenZipExtractor), "bz2": (bza_file, BzipaExtractor), "gzip": (gz_file, GzipExtractor), "lz4": (lza_file, LzaExtractor), "tar": (tar_file, TarExtractor), "xz": (xz_file, XzExtractor), "zip": (zip_file, ZipExtractor), "zstd": (zstd_file, ZstdExtractor), } SCREAMING_SNAKE_CASE__ = input_paths_and_base_extractors[compression_format] if input_path is None: SCREAMING_SNAKE_CASE__ = F'''for \'{compression_format}\' compression_format, ''' if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_lowercase ) assert base_extractor.is_extractable(_lowercase ) SCREAMING_SNAKE_CASE__ = tmp_path / ("extracted" if is_archive else "extracted.txt") base_extractor.extract(_lowercase , _lowercase ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name SCREAMING_SNAKE_CASE__ = file_path.read_text(encoding="utf-8" ) else: SCREAMING_SNAKE_CASE__ = output_path.read_text(encoding="utf-8" ) SCREAMING_SNAKE_CASE__ = text_file.read_text(encoding="utf-8" ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( "compression_format, is_archive" , [ ("7z", True), ("bz2", False), ("gzip", False), ("lz4", False), ("tar", True), ("xz", False), ("zip", True), ("zstd", False), ] , ) def __lowercase ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : str , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : str , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Any , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[int] , ): SCREAMING_SNAKE_CASE__ = { "7z": seven_zip_file, "bz2": bza_file, "gzip": gz_file, "lz4": lza_file, "tar": tar_file, "xz": xz_file, "zip": zip_file, "zstd": zstd_file, } SCREAMING_SNAKE_CASE__ = input_paths[compression_format] if input_path is None: SCREAMING_SNAKE_CASE__ = F'''for \'{compression_format}\' compression_format, ''' if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_lowercase ) SCREAMING_SNAKE_CASE__ = Extractor.infer_extractor_format(_lowercase ) assert extractor_format is not None SCREAMING_SNAKE_CASE__ = tmp_path / ("extracted" if is_archive else "extracted.txt") Extractor.extract(_lowercase , _lowercase , _lowercase ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name SCREAMING_SNAKE_CASE__ = file_path.read_text(encoding="utf-8" ) else: SCREAMING_SNAKE_CASE__ = output_path.read_text(encoding="utf-8" ) SCREAMING_SNAKE_CASE__ = text_file.read_text(encoding="utf-8" ) assert extracted_file_content == expected_file_content @pytest.fixture def __lowercase ( lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[Any] ): import tarfile SCREAMING_SNAKE_CASE__ = tmp_path / "data_dot_dot" directory.mkdir() SCREAMING_SNAKE_CASE__ = directory / "tar_file_with_dot_dot.tar" with tarfile.TarFile(_lowercase , "w" ) as f: f.add(_lowercase , arcname=os.path.join(".." , text_file.name ) ) return path @pytest.fixture def __lowercase ( lowerCamelCase_ : List[str] ): import tarfile SCREAMING_SNAKE_CASE__ = tmp_path / "data_sym_link" directory.mkdir() SCREAMING_SNAKE_CASE__ = directory / "tar_file_with_sym_link.tar" os.symlink(".." , directory / "subdir" , target_is_directory=_lowercase ) with tarfile.TarFile(_lowercase , "w" ) as f: f.add(str(directory / "subdir" ) , arcname="subdir" ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( "insecure_tar_file, error_log" , [("tar_file_with_dot_dot", "illegal path"), ("tar_file_with_sym_link", "Symlink")] , ) def __lowercase ( lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : str , lowerCamelCase_ : int ): SCREAMING_SNAKE_CASE__ = { "tar_file_with_dot_dot": tar_file_with_dot_dot, "tar_file_with_sym_link": tar_file_with_sym_link, } SCREAMING_SNAKE_CASE__ = insecure_tar_files[insecure_tar_file] SCREAMING_SNAKE_CASE__ = tmp_path / "extracted" TarExtractor.extract(_lowercase , _lowercase ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def __lowercase ( lowerCamelCase_ : Tuple ): SCREAMING_SNAKE_CASE__ = tmpdir / "not_a_zip_file" # From: https://github.com/python/cpython/pull/5053 SCREAMING_SNAKE_CASE__ = ( B"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00" B"\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I" B"DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07" B"\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82" ) with not_a_zip_file.open("wb" ) as f: f.write(_lowercase ) assert zipfile.is_zipfile(str(_lowercase ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(_lowercase ) # but we're right
709
"""simple docstring""" from math import pi def __lowercase ( lowerCamelCase_ : int , lowerCamelCase_ : int ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
112
0