code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a :str = [ "cross_validation.py", "gradient_accumulation.py", "local_sgd.py", "multi_process_metrics.py", "memory.py", "automatic_gradient_accumulation.py", "fsdp_with_peak_mem_tracking.py", "deepspeed_with_config_support.py", "megatron_lm_gpt_pretraining.py", ] class __a (unittest.TestCase): '''simple docstring''' def _a ( self , _a , _a , _a = None , _a = None ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Tuple = os.path.abspath(os.path.join("""examples""" , """by_feature""" ) ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.abspath("""examples""" ) for item in os.listdir(lowerCAmelCase__ ): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE__ : str = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) if os.path.isfile(lowerCAmelCase__ ) and ".py" in item_path: with self.subTest( tested_script=lowerCAmelCase__ , feature_script=lowerCAmelCase__ , tested_section="""main()""" if parser_only else """training_function()""" , ): SCREAMING_SNAKE_CASE__ : int = compare_against_test( os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = """\n""".join(lowerCAmelCase__ ) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE__ : int = diff.replace(lowerCAmelCase__ , """""" ) self.assertEqual(lowerCAmelCase__ , """""" ) def _a ( self ) -> Dict: """simple docstring""" self.one_complete_example("""complete_nlp_example.py""" , lowerCAmelCase__ ) self.one_complete_example("""complete_nlp_example.py""" , lowerCAmelCase__ ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.join("""examples""" , """cv_example.py""" ) ) SCREAMING_SNAKE_CASE__ : Dict = [ """ """ * 16 + """{\n\n""", """ """ * 20 + """\"accuracy\": eval_metric[\"accuracy\"],\n\n""", """ """ * 20 + """\"f1\": eval_metric[\"f1\"],\n\n""", """ """ * 20 + """\"train_loss\": total_loss.item() / len(train_dataloader),\n\n""", """ """ * 20 + """\"epoch\": epoch,\n\n""", """ """ * 16 + """},\n\n""", """ """ * 16 + """step=epoch,\n""", """ """ * 12, """ """ * 8 + """for step, batch in enumerate(active_dataloader):\n""", ] self.one_complete_example("""complete_cv_example.py""" , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) self.one_complete_example("""complete_cv_example.py""" , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) @mock.patch.dict(os.environ , {"""TESTING_MOCKED_DATALOADERS""": """1"""}) class __a (_snake_case): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = False @classmethod def _a ( cls ) -> Optional[Any]: """simple docstring""" super().setUpClass() SCREAMING_SNAKE_CASE__ : Dict = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(cls._tmpdir , """default_config.yml""" ) write_basic_config(save_location=cls.configPath ) SCREAMING_SNAKE_CASE__ : List[str] = ["""accelerate""", """launch""", """--config_file""", cls.configPath] @classmethod def _a ( cls ) -> str: """simple docstring""" super().tearDownClass() shutil.rmtree(cls._tmpdir ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = f'''\n examples/by_feature/checkpointing.py\n --checkpointing_steps epoch\n --output_dir {self.tmpdir}\n '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , """epoch_0""" ) ) ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = f'''\n examples/by_feature/checkpointing.py\n --checkpointing_steps 1\n --output_dir {self.tmpdir}\n '''.split() SCREAMING_SNAKE_CASE__ : Union[str, Any] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , """step_2""" ) ) ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = f'''\n examples/by_feature/checkpointing.py\n --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )}\n '''.split() SCREAMING_SNAKE_CASE__ : Tuple = run_command(self._launch_args + testargs , return_stdout=lowerCAmelCase__ ) self.assertNotIn("""epoch 0:""" , lowerCAmelCase__ ) self.assertIn("""epoch 1:""" , lowerCAmelCase__ ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = f'''\n examples/by_feature/checkpointing.py\n --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )}\n '''.split() SCREAMING_SNAKE_CASE__ : Tuple = run_command(self._launch_args + testargs , return_stdout=lowerCAmelCase__ ) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE__ : int = 1 if num_processes > 1: self.assertNotIn("""epoch 0:""" , lowerCAmelCase__ ) self.assertIn("""epoch 1:""" , lowerCAmelCase__ ) else: self.assertIn("""epoch 0:""" , lowerCAmelCase__ ) self.assertIn("""epoch 1:""" , lowerCAmelCase__ ) @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = """\n examples/by_feature/cross_validation.py\n --num_folds 2\n """.split() with mock.patch.dict(os.environ , {"""TESTING_MOCKED_DATALOADERS""": """0"""} ): SCREAMING_SNAKE_CASE__ : int = run_command(self._launch_args + testargs , return_stdout=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = re.findall("""({.+})""" , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = [r for r in results if """accuracy""" in r][-1] SCREAMING_SNAKE_CASE__ : List[Any] = ast.literal_eval(lowerCAmelCase__ ) self.assertGreaterEqual(results["""accuracy"""] , 0.75 ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = ["""examples/by_feature/multi_process_metrics.py"""] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _a ( self ) -> Union[str, Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE__ : Tuple = f'''\n examples/by_feature/tracking.py\n --with_tracking\n --project_dir {tmpdir}\n '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(lowerCAmelCase__ , """tracking""" ) ) ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = ["""examples/by_feature/gradient_accumulation.py"""] run_command(self._launch_args + testargs ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ["""examples/by_feature/local_sgd.py"""] run_command(self._launch_args + testargs )
701
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = (DDPMScheduler,) def _a ( self , **_a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**_a ) return config def _a ( self ) -> str: """simple docstring""" for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def _a ( self ) -> str: """simple docstring""" for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def _a ( self ) -> Any: """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def _a ( self ) -> int: """simple docstring""" self.check_over_configs(thresholding=_a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , ) def _a ( self ) -> str: """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def _a ( self ) -> str: """simple docstring""" for t in [0, 500, 999]: self.check_over_forward(time_step=_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Any = len(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : str = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : int = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : str = pred_prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.9_606 ) < 1E-2 assert abs(result_mean.item() - 0.3_372 ) < 1E-3 def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Tuple = self.get_scheduler_config(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Dict = len(_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : int = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : Tuple = pred_prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : int = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 202.0_296 ) < 1E-2 assert abs(result_mean.item() - 0.2_631 ) < 1E-3 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = -1 else: SCREAMING_SNAKE_CASE__ : Tuple = timesteps[i + 1] SCREAMING_SNAKE_CASE__ : int = scheduler.previous_timestep(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prev_t.item() self.assertEqual(_a , _a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [100, 87, 50, 51, 0] with self.assertRaises(_a , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : int = [100, 87, 50, 1, 0] SCREAMING_SNAKE_CASE__ : List[str] = len(_a ) with self.assertRaises(_a , msg="""Can only pass one of `num_inference_steps` or `custom_timesteps`.""" ): scheduler.set_timesteps(num_inference_steps=_a , timesteps=_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( _a , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=_a )
12
0
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase = 4 ) -> list[list[int]]: SCREAMING_SNAKE_CASE__ : str = abs(_SCREAMING_SNAKE_CASE ) or 4 return [[1 + x + y * row_size for x in range(_SCREAMING_SNAKE_CASE )] for y in range(_SCREAMING_SNAKE_CASE )] def _lowercase ( __lowerCAmelCase ) -> list[list[int]]: return reverse_row(transpose(_SCREAMING_SNAKE_CASE ) ) # OR.. transpose(reverse_column(matrix)) def _lowercase ( __lowerCAmelCase ) -> list[list[int]]: return reverse_row(reverse_column(_SCREAMING_SNAKE_CASE ) ) # OR.. reverse_column(reverse_row(matrix)) def _lowercase ( __lowerCAmelCase ) -> list[list[int]]: return reverse_column(transpose(_SCREAMING_SNAKE_CASE ) ) # OR.. transpose(reverse_row(matrix)) def _lowercase ( __lowerCAmelCase ) -> list[list[int]]: SCREAMING_SNAKE_CASE__ : int = [list(_SCREAMING_SNAKE_CASE ) for x in zip(*_SCREAMING_SNAKE_CASE )] return matrix def _lowercase ( __lowerCAmelCase ) -> list[list[int]]: SCREAMING_SNAKE_CASE__ : str = matrix[::-1] return matrix def _lowercase ( __lowerCAmelCase ) -> list[list[int]]: SCREAMING_SNAKE_CASE__ : Tuple = [x[::-1] for x in matrix] return matrix def _lowercase ( __lowerCAmelCase ) -> None: for i in matrix: print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": a :int = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_aa(matrix)) a :Tuple = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_aaa(matrix)) a :Optional[int] = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_aaa(matrix))
702
"""simple docstring""" import os a :List[str] = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1_000} def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 while index < len(__lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE__ : List[Any] = SYMBOLS[numerals[index]] SCREAMING_SNAKE_CASE__ : Dict = 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 _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = """""" SCREAMING_SNAKE_CASE__ : int = num // 1000 numerals += m_count * "M" num %= 1000 SCREAMING_SNAKE_CASE__ : List[str] = 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 SCREAMING_SNAKE_CASE__ : List[Any] = 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 _lowercase ( __lowerCAmelCase = "/p089_roman.txt" ) -> int: SCREAMING_SNAKE_CASE__ : int = 0 with open(os.path.dirname(__lowerCAmelCase ) + roman_numerals_filename ) as filea: SCREAMING_SNAKE_CASE__ : str = filea.readlines() for line in lines: SCREAMING_SNAKE_CASE__ : Union[str, Any] = line.strip() SCREAMING_SNAKE_CASE__ : Dict = parse_roman_numerals(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = generate_roman_numerals(__lowerCAmelCase ) savings += len(__lowerCAmelCase ) - len(__lowerCAmelCase ) return savings if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup a :Any = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def _lowercase ( __lowerCAmelCase = "dhaka" , __lowerCAmelCase = 5 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = min(__lowerCAmelCase , 50 ) # Prevent abuse! SCREAMING_SNAKE_CASE__ : Any = { """q""": query, """tbm""": """isch""", """hl""": """en""", """ijn""": """0""", } SCREAMING_SNAKE_CASE__ : Dict = requests.get("""https://www.google.com/search""" , params=__lowerCAmelCase , headers=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = BeautifulSoup(html.text , """html.parser""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """""".join( re.findall(r"""AF_initDataCallback\(([^<]+)\);""" , str(soup.select("""script""" ) ) ) ) SCREAMING_SNAKE_CASE__ : List[Any] = json.dumps(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.loads(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.findall( r"""\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",""" , __lowerCAmelCase , ) if not matched_google_image_data: return 0 SCREAMING_SNAKE_CASE__ : Any = re.sub( r"""\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]""" , """""" , str(__lowerCAmelCase ) , ) SCREAMING_SNAKE_CASE__ : Dict = re.findall( r"""(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]""" , __lowerCAmelCase , ) for index, fixed_full_res_image in enumerate(__lowerCAmelCase ): if index >= max_images: return index SCREAMING_SNAKE_CASE__ : Optional[int] = bytes(__lowerCAmelCase , """ascii""" ).decode( """unicode-escape""" ) SCREAMING_SNAKE_CASE__ : List[Any] = bytes(__lowerCAmelCase , """ascii""" ).decode( """unicode-escape""" ) SCREAMING_SNAKE_CASE__ : Dict = urllib.request.build_opener() SCREAMING_SNAKE_CASE__ : Optional[Any] = [ ( """User-Agent""", """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36""" """ (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582""", ) ] urllib.request.install_opener(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = F'''query_{query.replace(' ' , '_' )}''' if not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) urllib.request.urlretrieve( # noqa: S310 __lowerCAmelCase , F'''{path_name}/original_size_img_{index}.jpg''' ) return index if __name__ == "__main__": try: a :str = download_images_from_google_query(sys.argv[1]) print(f'{image_count} images were downloaded to disk.') except IndexError: print("Please provide a search term.") raise
703
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) SCREAMING_SNAKE_CASE__ : Any = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 25_543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : List[str] = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , _a ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Optional[int] = tf.convert_to_tensor( [[[-0.0_254, 0.0_235, 0.1_027], [0.0_606, -0.1_811, -0.0_418], [-0.1_561, -0.1_127, 0.2_687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
12
0
"""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) a :Union[str, Any] = logging.getLogger() def _lowercase ( __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict = {} SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(_lowercase , """all_results.json""" ) if os.path.exists(_lowercase ): with open(_lowercase , """r""" ) as f: SCREAMING_SNAKE_CASE__ : int = json.load(_lowercase ) else: raise ValueError(F'''can\'t find {path}''' ) return results a :Optional[int] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class __a (UpperCamelCase_): '''simple docstring''' def _a ( self ) -> Tuple: """simple docstring""" import xla_spawn SCREAMING_SNAKE_CASE__ : List[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE__ : List[str] = f''' ./examples/pytorch/text-classification/run_glue.py --num_cores=8 ./examples/pytorch/text-classification/run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --overwrite_output_dir --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --do_train --do_eval --debug tpu_metrics_debug --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --max_steps=10 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(UpperCamelCase_ , """argv""" , UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = time() xla_spawn.main() SCREAMING_SNAKE_CASE__ : Tuple = time() SCREAMING_SNAKE_CASE__ : Optional[Any] = get_results(UpperCamelCase_ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 500 ) def _a ( self ) -> List[str]: """simple docstring""" import xla_spawn SCREAMING_SNAKE_CASE__ : List[str] = '\n ./tests/test_trainer_tpu.py\n --num_cores=8\n ./tests/test_trainer_tpu.py\n '.split() with patch.object(UpperCamelCase_ , """argv""" , UpperCamelCase_ ): xla_spawn.main()
704
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a :List[Any] = logging.get_logger(__name__) a :Optional[int] = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """focalnet""" def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=False , _a=[192, 384, 768, 768] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1E-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1E-5 , _a=32 , _a=None , _a=None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : str = patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = embed_dim SCREAMING_SNAKE_CASE__ : List[str] = use_conv_embed SCREAMING_SNAKE_CASE__ : List[str] = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Any = focal_levels SCREAMING_SNAKE_CASE__ : Optional[Any] = focal_windows SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : str = use_layerscale SCREAMING_SNAKE_CASE__ : int = layerscale_value SCREAMING_SNAKE_CASE__ : Optional[int] = use_post_layernorm SCREAMING_SNAKE_CASE__ : Any = use_post_layernorm_in_modulation SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize_modulator SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = encoder_stride SCREAMING_SNAKE_CASE__ : Optional[int] = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
12
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, ) a :int = {"configuration_mbart": ["MBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "MBartConfig", "MBartOnnxConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Dict = ["MBartTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Dict = ["MBartTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[int] = [ "MBART_PRETRAINED_MODEL_ARCHIVE_LIST", "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Union[str, Any] = [ "TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Union[str, Any] = [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a :Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
705
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __a (unittest.TestCase): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_attention_mask SCREAMING_SNAKE_CASE__ : Tuple = use_token_type_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = num_choices def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE__ : int = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = True _SCREAMING_SNAKE_CASE :Optional[Any] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerModelTester(self ) @slow def _a ( self ) -> int: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a ) @require_flax class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.array([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ : str = model(_a )[0] SCREAMING_SNAKE_CASE__ : List[Any] = 50_000 SCREAMING_SNAKE_CASE__ : Optional[Any] = (1, 6, vocab_size) self.assertEqual(output.shape , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
12
0
"""simple docstring""" import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=64 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = parent SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE__ : Tuple = seq_length SCREAMING_SNAKE_CASE__ : Tuple = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[int] = use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : Any = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_size SCREAMING_SNAKE_CASE__ : Dict = embedding_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : str = intermediate_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : str = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : List[str] = num_choices SCREAMING_SNAKE_CASE__ : List[str] = scope def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ) -> str: """simple docstring""" return MegatronBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MegatronBertModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Any = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Dict = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = MegatronBertForMaskedLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = MegatronBertForCausalLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = MegatronBertForNextSentencePrediction(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : int = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = MegatronBertForPreTraining(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , next_sentence_label=UpperCAmelCase_ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = MegatronBertForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE__ : Optional[int] = MegatronBertForSequenceClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.num_labels SCREAMING_SNAKE_CASE__ : Any = MegatronBertForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_choices SCREAMING_SNAKE_CASE__ : str = MegatronBertForMultipleChoice(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Union[str, Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : List[str] = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE__ ) : Dict = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __a (__lowerCamelCase , __lowerCamelCase , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Dict = ( { """feature-extraction""": MegatronBertModel, """fill-mask""": MegatronBertForMaskedLM, """question-answering""": MegatronBertForQuestionAnswering, """text-classification""": MegatronBertForSequenceClassification, """text-generation""": MegatronBertForCausalLM, """token-classification""": MegatronBertForTokenClassification, """zero-shot""": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :int = True # test_resize_embeddings = False _SCREAMING_SNAKE_CASE :Any = False def _a ( self , _a , _a , _a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = super()._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) if return_labels: if model_class in get_values(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE__ : int = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_ ) return inputs_dict def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = MegatronBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def _a ( self ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*UpperCAmelCase_ ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*UpperCAmelCase_ ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*UpperCAmelCase_ ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*UpperCAmelCase_ ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*UpperCAmelCase_ ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*UpperCAmelCase_ ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*UpperCAmelCase_ ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*UpperCAmelCase_ ) def _lowercase ( __lowerCAmelCase ) -> Optional[int]: return torch.tensor( lowerCamelCase_ , dtype=torch.long , device=lowerCamelCase_ , ) a :Optional[int] = 1e-4 @require_torch @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow @unittest.skip("""Model is not available.""" ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'nvidia/megatron-bert-uncased-345m' if "MYDIR" in os.environ: SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(os.environ["""MYDIR"""] , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = MegatronBertModel.from_pretrained(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.half() SCREAMING_SNAKE_CASE__ : Optional[int] = _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[str] = model(UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Size((1, 9, 1_024) ) self.assertEqual(output.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ : Any = [-0.6_040, -0.2_517, -0.1_025, 0.3_420, -0.6_758, -0.0_017, -0.1_089, -0.1_990, 0.5_728] for ii in range(3 ): for jj in range(3 ): SCREAMING_SNAKE_CASE__ : Tuple = output[0, ii, jj] SCREAMING_SNAKE_CASE__ : Optional[Any] = expected[3 * ii + jj] SCREAMING_SNAKE_CASE__ : Optional[Any] = 'ii={} jj={} a={} b={}'.format(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertTrue(math.isclose(UpperCAmelCase_ , UpperCAmelCase_ , rel_tol=UpperCAmelCase_ , abs_tol=UpperCAmelCase_ ) , msg=UpperCAmelCase_ )
706
"""simple docstring""" a :List[str] = [ (1_000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1000} SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 while place < len(__lowerCAmelCase ): if (place + 1 < len(__lowerCAmelCase )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = [] for arabic, roman in ROMAN: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : List[str] = divmod(__lowerCAmelCase , __lowerCAmelCase ) result.append(roman * factor ) if number == 0: break return "".join(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" import baseaa def _lowercase ( __lowerCAmelCase ) -> bytes: return baseaa.aaaencode(string.encode("""utf-8""" ) ) def _lowercase ( __lowerCAmelCase ) -> str: return baseaa.aaadecode(__lowerCAmelCase ).decode("""utf-8""" ) if __name__ == "__main__": import doctest doctest.testmod()
707
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a :Any = { "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig", "RobertaPreLayerNormOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Union[str, Any] = [ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[Any] = [ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = [ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
12
0
"""simple docstring""" import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class __a (__A , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = FlaxAutoencoderKL @property def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 SCREAMING_SNAKE_CASE__ : Dict = (32, 32) SCREAMING_SNAKE_CASE__ : int = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = jax.random.uniform(_a , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } SCREAMING_SNAKE_CASE__ : Tuple = self.dummy_input return init_dict, inputs_dict
708
"""simple docstring""" 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 IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : Dict = 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__ : Optional[Any] = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073], """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711], } SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_a , _a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> Any: """simple docstring""" return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **_a ) def _a ( self ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Optional[int] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=_a ) SCREAMING_SNAKE_CASE__ : int = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = AlignProcessor.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 _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[str] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(images=_a , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Any = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(text=_a ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(_a , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = 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 _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.batch_decode(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[str] = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
12
0
"""simple docstring""" import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() a :Optional[Any] = logging.get_logger(__name__) def _lowercase ( __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[str] = SwinConfig.from_pretrained( """microsoft/swin-tiny-patch4-window7-224""" , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) SCREAMING_SNAKE_CASE__ : str = MaskFormerConfig(backbone_config=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = """huggingface/label-files""" if "ade20k-full" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ : List[str] = 847 SCREAMING_SNAKE_CASE__ : Optional[Any] = """maskformer-ade20k-full-id2label.json""" elif "ade" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ : Dict = 150 SCREAMING_SNAKE_CASE__ : Tuple = """ade20k-id2label.json""" elif "coco-stuff" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ : int = 171 SCREAMING_SNAKE_CASE__ : Union[str, Any] = """maskformer-coco-stuff-id2label.json""" elif "coco" in model_name: # TODO SCREAMING_SNAKE_CASE__ : int = 133 SCREAMING_SNAKE_CASE__ : Any = """coco-panoptic-id2label.json""" elif "cityscapes" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ : Any = 19 SCREAMING_SNAKE_CASE__ : List[Any] = """cityscapes-id2label.json""" elif "vistas" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ : int = 65 SCREAMING_SNAKE_CASE__ : int = """mapillary-vistas-id2label.json""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.load(open(hf_hub_download(__lowerCAmelCase , __lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} return config def _lowercase ( __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Any = [] # stem # fmt: off rename_keys.append(("""backbone.patch_embed.proj.weight""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.proj.bias""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """model.pixel_level_module.encoder.model.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """model.pixel_level_module.encoder.model.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((F'''backbone.layers.{i}.downsample.reduction.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((F'''backbone.layers.{i}.downsample.norm.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((F'''backbone.layers.{i}.downsample.norm.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((F'''backbone.norm{i}.weight''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''') ) rename_keys.append((F'''backbone.norm{i}.bias''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''') ) # FPN rename_keys.append(("""sem_seg_head.layer_4.weight""", """model.pixel_level_module.decoder.fpn.stem.0.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.weight""", """model.pixel_level_module.decoder.fpn.stem.1.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.bias""", """model.pixel_level_module.decoder.fpn.stem.1.bias""") ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((F'''sem_seg_head.adapter_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''') ) rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''') ) rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''') ) rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''') ) rename_keys.append(("""sem_seg_head.mask_features.weight""", """model.pixel_level_module.decoder.mask_projection.weight""") ) rename_keys.append(("""sem_seg_head.mask_features.bias""", """model.pixel_level_module.decoder.mask_projection.bias""") ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''') ) # cross-attention out projection rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''') ) # MLP 1 rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc1.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc1.bias''') ) # MLP 2 rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc2.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc2.bias''') ) # layernorm 1 (self-attention layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''') ) # layernorm 3 (final layernorm) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''') ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.weight""", """model.transformer_module.decoder.layernorm.weight""") ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.bias""", """model.transformer_module.decoder.layernorm.bias""") ) # heads on top rename_keys.append(("""sem_seg_head.predictor.query_embed.weight""", """model.transformer_module.queries_embedder.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.weight""", """model.transformer_module.input_projection.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.bias""", """model.transformer_module.input_projection.bias""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.weight""", """class_predictor.weight""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.bias""", """class_predictor.bias""") ) for i in range(3 ): rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', F'''mask_embedder.{i}.0.weight''') ) rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', F'''mask_embedder.{i}.0.bias''') ) # fmt: on return rename_keys def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : int = dct.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = val def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : int = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): SCREAMING_SNAKE_CASE__ : Tuple = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[:dim, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: dim] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_bias[ dim : dim * 2 ] SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[ -dim :, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[-dim :] # fmt: on def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Union[str, Any] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Tuple = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : str = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ : int = in_proj_bias[-hidden_size :] # fmt: on def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ) return im @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> str: SCREAMING_SNAKE_CASE__ : Dict = get_maskformer_config(__lowerCAmelCase ) # load original state_dict with open(__lowerCAmelCase , """rb""" ) as f: SCREAMING_SNAKE_CASE__ : Tuple = pickle.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = data["""model"""] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys SCREAMING_SNAKE_CASE__ : List[str] = create_rename_keys(__lowerCAmelCase ) for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) read_in_swin_q_k_v(__lowerCAmelCase , config.backbone_config ) read_in_decoder_q_k_v(__lowerCAmelCase , __lowerCAmelCase ) # update to torch tensors for key, value in state_dict.items(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.from_numpy(__lowerCAmelCase ) # load 🤗 model SCREAMING_SNAKE_CASE__ : List[str] = MaskFormerForInstanceSegmentation(__lowerCAmelCase ) model.eval() for name, param in model.named_parameters(): print(__lowerCAmelCase , param.shape ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = model.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(__lowerCAmelCase ) == 0, F'''Unexpected keys: {unexpected_keys}''' # verify results SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() if "vistas" in model_name: SCREAMING_SNAKE_CASE__ : str = 65 elif "cityscapes" in model_name: SCREAMING_SNAKE_CASE__ : Optional[int] = 6_5535 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 255 SCREAMING_SNAKE_CASE__ : Dict = True if """ade""" in model_name else False SCREAMING_SNAKE_CASE__ : List[str] = MaskFormerImageProcessor(ignore_index=__lowerCAmelCase , reduce_labels=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_processor(__lowerCAmelCase , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : int = model(**__lowerCAmelCase ) print("""Logits:""" , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [[3.6_353, -4.4_770, -2.6_065], [0.5_081, -4.2_394, -3.5_343], [2.1_909, -5.0_353, -1.9_323]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(F'''Saving model and image processor to {pytorch_dump_folder_path}''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: print("""Pushing model and image processor to the hub...""" ) model.push_to_hub(F'''nielsr/{model_name}''' ) image_processor.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": a :Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="maskformer-swin-tiny-ade", type=str, help=("Name of the MaskFormer model you\'d like to convert",), ) parser.add_argument( "--checkpoint_path", default="/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl", type=str, help="Path to the original state dict (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :Optional[Any] = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
709
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging a :Optional[Any] = logging.get_logger(__name__) a :Union[str, Any] = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """t5""" _SCREAMING_SNAKE_CASE :List[str] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Any = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self , _a=32_128 , _a=512 , _a=64 , _a=2_048 , _a=6 , _a=None , _a=8 , _a=32 , _a=128 , _a=0.1 , _a=1E-6 , _a=1.0 , _a="relu" , _a=True , _a=True , _a=0 , _a=1 , **_a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = d_model SCREAMING_SNAKE_CASE__ : int = d_kv SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_ff SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_layers SCREAMING_SNAKE_CASE__ : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry SCREAMING_SNAKE_CASE__ : Tuple = num_heads SCREAMING_SNAKE_CASE__ : Dict = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : str = relative_attention_max_distance SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_factor SCREAMING_SNAKE_CASE__ : Tuple = feed_forward_proj SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : List[str] = self.feed_forward_proj.split("""-""" ) SCREAMING_SNAKE_CASE__ : Dict = act_info[-1] SCREAMING_SNAKE_CASE__ : str = act_info[0] == """gated""" if len(_a ) > 1 and act_info[0] != "gated" or len(_a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": SCREAMING_SNAKE_CASE__ : List[Any] = """gelu_new""" super().__init__( pad_token_id=_a , eos_token_id=_a , is_encoder_decoder=_a , **_a , ) class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: SCREAMING_SNAKE_CASE__ : Tuple = """past_encoder_sequence + sequence""" SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch"""} SCREAMING_SNAKE_CASE__ : Tuple = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : str = {0: """batch""", 1: """decoder_sequence"""} SCREAMING_SNAKE_CASE__ : Dict = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_a , direction="""inputs""" ) return common_inputs @property def _a ( self ) -> int: """simple docstring""" return 13
12
0
"""simple docstring""" from __future__ import annotations import math a :List[Any] = "2020.9.26" a :int = "xcodz-dot, cclaus, dhruvmanila" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> tuple[float, float]: if not all(isinstance(lowerCamelCase__ , (float, int) ) for val in locals().values() ): SCREAMING_SNAKE_CASE__ : Dict = F'''Input values must either be float or int: {list(locals().values() )}''' raise TypeError(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = ((x * distance) / (z + distance)) * scale SCREAMING_SNAKE_CASE__ : Dict = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> tuple[float, float, float]: if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError("""Axis must be a str""" ) SCREAMING_SNAKE_CASE__ : int = locals() del input_variables["axis"] if not all(isinstance(lowerCamelCase__ , (float, int) ) for val in input_variables.values() ): SCREAMING_SNAKE_CASE__ : int = ( "Input values except axis must either be float or int: " F'''{list(input_variables.values() )}''' ) raise TypeError(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = (angle % 360) / 450 * 180 / math.pi if axis == "z": SCREAMING_SNAKE_CASE__ : Any = x * math.cos(lowerCamelCase__ ) - y * math.sin(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = y * math.cos(lowerCamelCase__ ) + x * math.sin(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = z elif axis == "x": SCREAMING_SNAKE_CASE__ : Union[str, Any] = y * math.cos(lowerCamelCase__ ) - z * math.sin(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = z * math.cos(lowerCamelCase__ ) + y * math.sin(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = x elif axis == "y": SCREAMING_SNAKE_CASE__ : Optional[int] = x * math.cos(lowerCamelCase__ ) - z * math.sin(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = z * math.cos(lowerCamelCase__ ) + x * math.sin(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple = y else: raise ValueError("""not a valid axis, choose one of 'x', 'y', 'z'""" ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(f'{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }') print(f'{rotate(1.0, 2.0, 3.0, "y", 90.0) = }')
710
"""simple docstring""" from __future__ import annotations import time import numpy as np a :Optional[Any] = [8, 5, 9, 7] a :List[Any] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] a :int = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class __a : '''simple docstring''' def __init__( self , _a , _a , _a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = claim_vector SCREAMING_SNAKE_CASE__ : Any = allocated_resources_table SCREAMING_SNAKE_CASE__ : Any = maximum_claim_table def _a ( self ) -> list[int]: """simple docstring""" return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def _a ( self ) -> list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def _a ( self ) -> list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(_a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def _a ( self ) -> dict[int, list[int]]: """simple docstring""" return {self.__need().index(_a ): i for i in self.__need()} def _a ( self , **_a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.__need() SCREAMING_SNAKE_CASE__ : Any = self.__allocated_resources_table SCREAMING_SNAKE_CASE__ : Dict = self.__available_resources() SCREAMING_SNAKE_CASE__ : Dict = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 50 + """\n""" ) while need_list: SCREAMING_SNAKE_CASE__ : List[str] = False for each_need in need_list: SCREAMING_SNAKE_CASE__ : Dict = True for index, need in enumerate(_a ): if need > available_resources[index]: SCREAMING_SNAKE_CASE__ : Optional[int] = False break if execution: SCREAMING_SNAKE_CASE__ : Any = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: SCREAMING_SNAKE_CASE__ : Tuple = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(_a ) # update available/freed resources stack SCREAMING_SNAKE_CASE__ : Dict = np.array(_a ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(_a ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def _a ( self ) -> Any: """simple docstring""" print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(_a ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(_a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets a :Optional[Any] = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' a :List[Any] = '\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n' a :int = '\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n "raw_values" : Returns a full set of errors in case of multioutput input.\n\n "uniform_average" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric("mse")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {\'mse\': 0.6123724356957945}\n\n If you\'re using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric("mse", "multilist")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mse\': array([0.41666667, 1. ])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __a (datasets.Metric): '''simple docstring''' def _a ( self ) -> Optional[Any]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] , ) def _a ( self ) -> Optional[Any]: """simple docstring""" if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def _a ( self , _a , _a , _a=None , _a="uniform_average" , _a=True ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = mean_squared_error( __A , __A , sample_weight=__A , multioutput=__A , squared=__A ) return {"mse": mse}
711
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: a :List[Any] = None a :Optional[int] = logging.get_logger(__name__) a :Union[str, Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} a :Optional[int] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } a :Dict = { "xlnet-base-cased": None, "xlnet-large-cased": None, } a :int = "▁" # Segments (not really needed) a :Dict = 0 a :Optional[int] = 1 a :Tuple = 2 a :List[str] = 3 a :Optional[Any] = 4 class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = """left""" _SCREAMING_SNAKE_CASE :Optional[Any] = XLNetTokenizer def __init__( self , _a=None , _a=None , _a=False , _a=True , _a=False , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<sep>" , _a="<pad>" , _a="<cls>" , _a="<mask>" , _a=["<eop>", "<eod>"] , **_a , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , additional_special_tokens=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE__ : List[str] = remove_space SCREAMING_SNAKE_CASE__ : int = keep_accents SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_file SCREAMING_SNAKE_CASE__ : Tuple = False if not self.vocab_file else True def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Tuple = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a :Optional[int] = { "configuration_nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[int] = [ "NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST", "NezhaForNextSentencePrediction", "NezhaForMaskedLM", "NezhaForPreTraining", "NezhaForMultipleChoice", "NezhaForQuestionAnswering", "NezhaForSequenceClassification", "NezhaForTokenClassification", "NezhaModel", "NezhaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
712
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) + 1 SCREAMING_SNAKE_CASE__ : int = len(__lowerCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. SCREAMING_SNAKE_CASE__ : Dict = [[0 for i in range(__lowerCAmelCase )] for j in range(__lowerCAmelCase )] # since string of zero length match pattern of zero length SCREAMING_SNAKE_CASE__ : Dict = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : int = dp[0][j - 2] if pattern[j - 1] == """*""" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __lowerCAmelCase ): for j in range(1 , __lowerCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": SCREAMING_SNAKE_CASE__ : Any = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: SCREAMING_SNAKE_CASE__ : List[str] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): SCREAMING_SNAKE_CASE__ : List[Any] = dp[i - 1][j] else: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 else: SCREAMING_SNAKE_CASE__ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") a :Any = "aab" a :Optional[Any] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f'{input_string} matches the given pattern {pattern}') else: print(f'{input_string} does not match with the given pattern {pattern}')
12
0
"""simple docstring""" import heapq import sys import numpy as np a :str = tuple[int, int] class __a : '''simple docstring''' def __init__( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : str = set() def _a ( self ) -> Optional[int]: """simple docstring""" if not self.empty(): return self.elements[0][0] else: return float("""inf""" ) def _a ( self ) -> List[Any]: """simple docstring""" return len(self.elements ) == 0 def _a ( self , _a , _a ) -> Union[str, Any]: """simple docstring""" if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(_UpperCAmelCase ) else: # update # print("update", item) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Optional[Any] = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Optional[Any] = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def _a ( self , _a ) -> Optional[Any]: """simple docstring""" if item in self.set: self.set.remove(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = [] ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Tuple = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : str = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def _a ( self ) -> Optional[Any]: """simple docstring""" return self.elements[0][1] def _a ( self ) -> Union[str, Any]: """simple docstring""" ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Tuple = heapq.heappop(self.elements ) self.set.remove(_UpperCAmelCase ) return (priority, item) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # euclidean distance SCREAMING_SNAKE_CASE__ : Optional[int] = np.array(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array(lowerCAmelCase__ ) return np.linalg.norm(a - b ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: # integer division by time variable return consistent_heuristic(lowerCAmelCase__ , lowerCAmelCase__ ) // t def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = g_function[start] + Wa * heuristics[i](lowerCAmelCase__ , lowerCAmelCase__ ) return ans def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Tuple = np.chararray((n, n) ) for i in range(lowerCAmelCase__ ): for j in range(lowerCAmelCase__ ): SCREAMING_SNAKE_CASE__ : Any = """*""" for i in range(lowerCAmelCase__ ): for j in range(lowerCAmelCase__ ): if (j, (n - 1) - i) in blocks: SCREAMING_SNAKE_CASE__ : Optional[Any] = """#""" SCREAMING_SNAKE_CASE__ : Any = """-""" SCREAMING_SNAKE_CASE__ : int = back_pointer[goal] while x != start: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : List[str] = x # print(x) SCREAMING_SNAKE_CASE__ : List[Any] = """-""" SCREAMING_SNAKE_CASE__ : Any = back_pointer[x] SCREAMING_SNAKE_CASE__ : str = """-""" for i in range(lowerCAmelCase__ ): for j in range(lowerCAmelCase__ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=""" """ ) print("""<-- End position""" , end=""" """ ) else: print(grid[i][j] , end=""" """ ) print() print("""^""" ) print("""Start position""" ) print() print("""# is an obstacle""" ) print("""- is the path taken by algorithm""" ) print("""PATH TAKEN BY THE ALGORITHM IS:-""" ) SCREAMING_SNAKE_CASE__ : str = back_pointer[goal] while x != start: print(lowerCAmelCase__ , end=""" """ ) SCREAMING_SNAKE_CASE__ : int = back_pointer[x] print(lowerCAmelCase__ ) sys.exit() def _lowercase ( __lowerCAmelCase ) -> Any: if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Dict: for itera in range(lowerCAmelCase__ ): open_list[itera].remove_element(lowerCAmelCase__ ) # print("s", s) # print("j", j) ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : Any = s SCREAMING_SNAKE_CASE__ : Union[str, Any] = (x - 1, y) SCREAMING_SNAKE_CASE__ : Any = (x + 1, y) SCREAMING_SNAKE_CASE__ : List[Any] = (x, y + 1) SCREAMING_SNAKE_CASE__ : int = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowerCAmelCase__ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = -1 SCREAMING_SNAKE_CASE__ : Any = float("""inf""" ) if valid(lowerCAmelCase__ ) and g_function[neighbours] > g_function[s] + 1: SCREAMING_SNAKE_CASE__ : int = g_function[s] + 1 SCREAMING_SNAKE_CASE__ : List[Any] = s if neighbours not in close_list_anchor: open_list[0].put(lowerCAmelCase__ , key(lowerCAmelCase__ , 0 , lowerCAmelCase__ , lowerCAmelCase__ ) ) if neighbours not in close_list_inad: for var in range(1 , lowerCAmelCase__ ): if key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) <= Wa * key( lowerCAmelCase__ , 0 , lowerCAmelCase__ , lowerCAmelCase__ ): open_list[j].put( lowerCAmelCase__ , key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list a :str = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} a :Optional[int] = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] a :int = make_common_ground() a :List[Any] = blocks_blk # hyper parameters a :str = 1 a :List[str] = 1 a :Optional[int] = 20 a :List[str] = 3 # one consistent and two other inconsistent # start and end destination a :str = (0, 0) a :Tuple = (n - 1, n - 1) a :Tuple = 1 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = {start: 0, goal: float("""inf""" )} SCREAMING_SNAKE_CASE__ : Optional[int] = {start: -1, goal: -1} SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = set() for i in range(lowerCAmelCase__ ): open_list.append(PriorityQueue() ) open_list[i].put(lowerCAmelCase__ , key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) ) SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : Any = [] while open_list[0].minkey() < float("""inf""" ): for i in range(1 , lowerCAmelCase__ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("""inf""" ): do_something(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = open_list[i].top_show() visited.add(lowerCAmelCase__ ) expand_state( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) close_list_inad.append(lowerCAmelCase__ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("""inf""" ): do_something(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) else: SCREAMING_SNAKE_CASE__ : List[str] = open_list[0].top_show() visited.add(lowerCAmelCase__ ) expand_state( lowerCAmelCase__ , 0 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) close_list_anchor.append(lowerCAmelCase__ ) print("""No path found to goal""" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(lowerCAmelCase__ ): if (j, i) in blocks: print("""#""" , end=""" """ ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("""*""" , end=""" """ ) else: print("""-""" , end=""" """ ) else: print("""*""" , end=""" """ ) if (j, i) == (n - 1, n - 1): print("""<-- End position""" , end=""" """ ) print() print("""^""" ) print("""Start position""" ) print() print("""# is an obstacle""" ) print("""- is the path taken by algorithm""" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
713
"""simple docstring""" from math import sqrt def _lowercase ( __lowerCAmelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowercase ( __lowerCAmelCase = 1_0001 ) -> int: SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = 1 while count != nth and number < 3: number += 1 if is_prime(__lowerCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(__lowerCAmelCase ): count += 1 return number if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType a :int = logging.get_logger(__name__) a :Any = { "microsoft/deberta-v2-xlarge": "https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json", "microsoft/deberta-v2-xxlarge": "https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json", "microsoft/deberta-v2-xlarge-mnli": ( "https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json" ), "microsoft/deberta-v2-xxlarge-mnli": ( "https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json" ), } class __a (__lowerCAmelCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = """deberta-v2""" def __init__( self , _a=128_100 , _a=1_536 , _a=24 , _a=24 , _a=6_144 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=0 , _a=0.02 , _a=1E-7 , _a=False , _a=-1 , _a=0 , _a=True , _a=None , _a=0 , _a="gelu" , **_a , ) -> Any: """simple docstring""" super().__init__(**_UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : str = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] = relative_attention SCREAMING_SNAKE_CASE__ : int = max_relative_positions SCREAMING_SNAKE_CASE__ : str = pad_token_id SCREAMING_SNAKE_CASE__ : int = position_biased_input # Backwards compatibility if type(_UpperCamelCase ) == str: SCREAMING_SNAKE_CASE__ : List[str] = [x.strip() for x in pos_att_type.lower().split("""|""" )] SCREAMING_SNAKE_CASE__ : List[Any] = pos_att_type SCREAMING_SNAKE_CASE__ : Dict = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE__ : int = kwargs.get("""pooler_hidden_size""" , _UpperCamelCase ) SCREAMING_SNAKE_CASE__ : str = pooler_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = pooler_hidden_act class __a (__lowerCAmelCase): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ : int = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def _a ( self ) -> int: """simple docstring""" return 12 def _a ( self , _a , _a = -1 , _a = -1 , _a = -1 , _a = False , _a = None , _a = 3 , _a = 40 , _a = 40 , _a = None , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = super().generate_dummy_inputs(preprocessor=_UpperCamelCase , framework=_UpperCamelCase ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
714
"""simple docstring""" class __a : '''simple docstring''' def __init__( self , _a , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = name SCREAMING_SNAKE_CASE__ : Optional[Any] = value SCREAMING_SNAKE_CASE__ : List[Any] = weight def __repr__( self ) -> List[Any]: """simple docstring""" return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def _a ( self ) -> Dict: """simple docstring""" return self.value def _a ( self ) -> int: """simple docstring""" return self.name def _a ( self ) -> Optional[Any]: """simple docstring""" return self.weight def _a ( self ) -> Dict: """simple docstring""" return self.value / self.weight def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict: SCREAMING_SNAKE_CASE__ : Any = [] for i in range(len(__lowerCAmelCase ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = sorted(__lowerCAmelCase , key=__lowerCAmelCase , reverse=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 0.0, 0.0 for i in range(len(__lowerCAmelCase ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def _lowercase ( ) -> List[str]: pass if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class __a (a__): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = ["""image_processor""", """tokenizer"""] _SCREAMING_SNAKE_CASE :Tuple = """BlipImageProcessor""" _SCREAMING_SNAKE_CASE :int = """AutoTokenizer""" def __init__( self , _a , _a , _a ) -> List[str]: """simple docstring""" super().__init__(_A , _A ) # add QFormer tokenizer SCREAMING_SNAKE_CASE__ : str = qformer_tokenizer def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> int: """simple docstring""" if images is None and text is None: raise ValueError("""You have to specify at least images or text.""" ) SCREAMING_SNAKE_CASE__ : List[str] = BatchFeature() if text is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , ) encoding.update(_A ) SCREAMING_SNAKE_CASE__ : Any = self.qformer_tokenizer( text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , ) SCREAMING_SNAKE_CASE__ : List[str] = qformer_text_encoding.pop("""input_ids""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = qformer_text_encoding.pop("""attention_mask""" ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor(_A , return_tensors=_A ) encoding.update(_A ) return encoding def _a ( self , *_a , **_a ) -> Dict: """simple docstring""" return self.tokenizer.batch_decode(*_A , **_A ) def _a ( self , *_a , **_a ) -> Dict: """simple docstring""" return self.tokenizer.decode(*_A , **_A ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def _a ( self , _a , **_a ) -> Dict: """simple docstring""" if os.path.isfile(_A ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(_A , exist_ok=_A ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(_A , """qformer_tokenizer""" ) self.qformer_tokenizer.save_pretrained(_A ) return super().save_pretrained(_A , **_A ) @classmethod def _a ( cls , _a , **_a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = AutoTokenizer.from_pretrained(_A , subfolder="""qformer_tokenizer""" ) SCREAMING_SNAKE_CASE__ : Dict = cls._get_arguments_from_pretrained(_A , **_A ) args.append(_A ) return cls(*_A )
715
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: a :Optional[int] = None a :Optional[Any] = logging.get_logger(__name__) a :Optional[Any] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} a :Union[str, Any] = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } a :Any = { "facebook/nllb-large-en-ro": 1_024, "facebook/nllb-200-distilled-600M": 1_024, } # fmt: off a :Tuple = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :int = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE :Tuple = NllbTokenizer _SCREAMING_SNAKE_CASE :List[int] = [] _SCREAMING_SNAKE_CASE :List[int] = [] def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , _a=False , **_a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token SCREAMING_SNAKE_CASE__ : Optional[int] = legacy_behaviour super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , legacy_behaviour=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_file SCREAMING_SNAKE_CASE__ : str = False if not self.vocab_file else True SCREAMING_SNAKE_CASE__ : Dict = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens} ) SCREAMING_SNAKE_CASE__ : List[str] = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE__ : Dict = src_lang if src_lang is not None else """eng_Latn""" SCREAMING_SNAKE_CASE__ : List[str] = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE__ : Dict = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _a ( self ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _a ( self , _a , _a , _a , _a , **_a ) -> Tuple: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ : Dict = src_lang SCREAMING_SNAKE_CASE__ : Dict = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_tokens_to_ids(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tgt_lang_id return inputs def _a ( self , _a , _a = "eng_Latn" , _a = None , _a = "fra_Latn" , **_a , ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = src_lang SCREAMING_SNAKE_CASE__ : Dict = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _a ( self ) -> str: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Dict = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : int = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : int = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.eos_token_id] SCREAMING_SNAKE_CASE__ : Any = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return SCREAMING_SNAKE_CASE__ : Dict = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: # Load checkpoint SCREAMING_SNAKE_CASE__ : Tuple = torch.load(_lowerCamelCase , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : int = chkpt["model"] # We have the base model one level deeper than the original XLM repository SCREAMING_SNAKE_CASE__ : Tuple = {} for k, v in state_dict.items(): if "pred_layer" in k: SCREAMING_SNAKE_CASE__ : Tuple = v else: SCREAMING_SNAKE_CASE__ : Optional[int] = v SCREAMING_SNAKE_CASE__ : str = chkpt["params"] SCREAMING_SNAKE_CASE__ : List[Any] = {n: v for n, v in config.items() if not isinstance(_lowerCamelCase , (torch.FloatTensor, numpy.ndarray) )} SCREAMING_SNAKE_CASE__ : Union[str, Any] = chkpt["dico_word2id"] SCREAMING_SNAKE_CASE__ : List[Any] = {s + "</w>" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""" , """""" ): i for s, i in vocab.items()} # Save pytorch-model SCREAMING_SNAKE_CASE__ : Dict = pytorch_dump_folder_path + "/" + WEIGHTS_NAME SCREAMING_SNAKE_CASE__ : Any = pytorch_dump_folder_path + "/" + CONFIG_NAME SCREAMING_SNAKE_CASE__ : Optional[Any] = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"] print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(_lowerCamelCase , _lowerCamelCase ) print(F'''Save configuration file to {pytorch_config_dump_path}''' ) with open(_lowerCamelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(_lowerCamelCase , indent=2 ) + """\n""" ) print(F'''Save vocab file to {pytorch_config_dump_path}''' ) with open(_lowerCamelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(_lowerCamelCase , indent=2 ) + """\n""" ) if __name__ == "__main__": a :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) a :Optional[Any] = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
716
"""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 _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Any: # Format the message. if name is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None else: SCREAMING_SNAKE_CASE__ : str = """.""" * max(0 , spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" SCREAMING_SNAKE_CASE__ : Dict = fmt.format(__lowerCAmelCase ) # Print and recurse (if needed). if isinstance(__lowerCAmelCase , __lowerCAmelCase ): if msg is not None: print(__lowerCAmelCase ) for k in val.keys(): recursive_print(__lowerCAmelCase , val[k] , spaces + 2 ) elif isinstance(__lowerCAmelCase , torch.Tensor ): print(__lowerCAmelCase , """:""" , val.size() ) else: print(__lowerCAmelCase , """:""" , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[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. SCREAMING_SNAKE_CASE__ : Tuple = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] SCREAMING_SNAKE_CASE__ : int = (num_heads, hidden_size, num_splits) + input_shape[1:] SCREAMING_SNAKE_CASE__ : List[str] = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = param.transpose(0 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] SCREAMING_SNAKE_CASE__ : List[str] = (num_heads, num_splits, hidden_size) + input_shape[1:] SCREAMING_SNAKE_CASE__ : Dict = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = param.transpose(0 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ : Any = param.view(*__lowerCAmelCase ) return param def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: # The converted output model. SCREAMING_SNAKE_CASE__ : List[str] = {} # old versions did not store training args SCREAMING_SNAKE_CASE__ : List[str] = input_state_dict.get("""args""" , __lowerCAmelCase ) 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)) SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.padded_vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = ds_args.max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = ds_args.num_layers SCREAMING_SNAKE_CASE__ : Dict = ds_args.num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = ds_args.ffn_hidden_size # pprint(config) # The number of heads. SCREAMING_SNAKE_CASE__ : List[str] = config.n_head # The hidden_size per head. SCREAMING_SNAKE_CASE__ : str = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_state_dict["""checkpoint_version"""] else: SCREAMING_SNAKE_CASE__ : Tuple = 0.0 # The model. SCREAMING_SNAKE_CASE__ : Any = input_state_dict["""model"""] # The language model. SCREAMING_SNAKE_CASE__ : Any = model["""language_model"""] # The embeddings. SCREAMING_SNAKE_CASE__ : str = lm["""embedding"""] # The word embeddings. SCREAMING_SNAKE_CASE__ : int = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. SCREAMING_SNAKE_CASE__ : Any = word_embeddings[: config.vocab_size, :] SCREAMING_SNAKE_CASE__ : Optional[int] = word_embeddings # The position embeddings. SCREAMING_SNAKE_CASE__ : Any = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] SCREAMING_SNAKE_CASE__ : Tuple = 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. SCREAMING_SNAKE_CASE__ : List[Any] = pos_embeddings # The transformer. SCREAMING_SNAKE_CASE__ : Union[str, Any] = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. SCREAMING_SNAKE_CASE__ : str = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. SCREAMING_SNAKE_CASE__ : Optional[int] = { """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. SCREAMING_SNAKE_CASE__ : str = layer_re.match(__lowerCAmelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. SCREAMING_SNAKE_CASE__ : Dict = int(m.group(1 ) ) # The name of the operation. SCREAMING_SNAKE_CASE__ : Optional[Any] = m.group(2 ) # Is it a weight or a bias? SCREAMING_SNAKE_CASE__ : str = m.group(3 ) # The name of the layer. SCREAMING_SNAKE_CASE__ : List[Any] = F'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): SCREAMING_SNAKE_CASE__ : Dict = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" SCREAMING_SNAKE_CASE__ : List[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. SCREAMING_SNAKE_CASE__ : Any = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = causal_mask # Insert a "dummy" tensor for masked_bias. SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor(-1E4 , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = masked_bias SCREAMING_SNAKE_CASE__ : List[str] = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. SCREAMING_SNAKE_CASE__ : str = out_val.transpose(0 , 1 ).contiguous() # Store. SCREAMING_SNAKE_CASE__ : Dict = 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": SCREAMING_SNAKE_CASE__ : Any = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Store. No change of shape. SCREAMING_SNAKE_CASE__ : str = out_val # Transpose the weights. elif weight_or_bias == "weight": SCREAMING_SNAKE_CASE__ : str = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : int = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": SCREAMING_SNAKE_CASE__ : int = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : Dict = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. SCREAMING_SNAKE_CASE__ : Union[str, Any] = transformer["""final_layernorm.weight"""] SCREAMING_SNAKE_CASE__ : str = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. SCREAMING_SNAKE_CASE__ : Tuple = word_embeddings # It should be done! return output_state_dict def _lowercase ( ) -> List[Any]: # Create the argument parser. SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""" , action="""store_true""" ) parser.add_argument( """path_to_checkpoint""" , type=__lowerCAmelCase , help="""Path to the checkpoint file (.zip archive or direct .pt file)""" , ) parser.add_argument( """--config_file""" , default="""""" , type=__lowerCAmelCase , help="""An optional config json file describing the pre-trained model.""" , ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() # Extract the basename. SCREAMING_SNAKE_CASE__ : Optional[int] = 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: SCREAMING_SNAKE_CASE__ : List[Any] = torch.load(__lowerCAmelCase , map_location="""cpu""" ) else: SCREAMING_SNAKE_CASE__ : str = torch.load(args.path_to_checkpoint , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : int = input_state_dict.get("""args""" , __lowerCAmelCase ) # 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: SCREAMING_SNAKE_CASE__ : Dict = """gelu_fast""" elif ds_args.openai_gelu: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu_new""" else: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" SCREAMING_SNAKE_CASE__ : Any = """gelu_new""" # Spell out all parameters in case the defaults change. SCREAMING_SNAKE_CASE__ : Union[str, Any] = GPTaConfig( vocab_size=5_0257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=__lowerCAmelCase , 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=__lowerCAmelCase , summary_activation=__lowerCAmelCase , summary_proj_to_labels=__lowerCAmelCase , summary_first_dropout=0.1 , scale_attn_weights=__lowerCAmelCase , use_cache=__lowerCAmelCase , bos_token_id=5_0256 , eos_token_id=5_0256 , ) else: SCREAMING_SNAKE_CASE__ : List[Any] = GPTaConfig.from_json_file(args.config_file ) SCREAMING_SNAKE_CASE__ : Tuple = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = convert_megatron_checkpoint(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(__lowerCAmelCase , __lowerCAmelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: SCREAMING_SNAKE_CASE__ : Tuple = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": SCREAMING_SNAKE_CASE__ : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": SCREAMING_SNAKE_CASE__ : Any = ds_args.tokenizer_name_or_path else: raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """gpt2""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = type(__lowerCAmelCase ).__name__ SCREAMING_SNAKE_CASE__ : Dict = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(__lowerCAmelCase ) # Save tokenizer based on args print(F'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(__lowerCAmelCase ) # Store the state_dict to file. SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , """pytorch_model.bin""" ) print(F'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
12
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a :Any = logging.get_logger(__name__) a :Optional[int] = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class __a (_UpperCAmelCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """trocr""" _SCREAMING_SNAKE_CASE :Dict = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Tuple = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self , _a=50_265 , _a=1_024 , _a=12 , _a=16 , _a=4_096 , _a="gelu" , _a=512 , _a=0.1 , _a=0.0 , _a=0.0 , _a=2 , _a=0.02 , _a=0.0 , _a=True , _a=False , _a=True , _a=True , _a=1 , _a=0 , _a=2 , **_a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = d_model SCREAMING_SNAKE_CASE__ : List[str] = decoder_layers SCREAMING_SNAKE_CASE__ : Any = decoder_attention_heads SCREAMING_SNAKE_CASE__ : Any = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : List[str] = activation_function SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = dropout SCREAMING_SNAKE_CASE__ : List[str] = attention_dropout SCREAMING_SNAKE_CASE__ : str = activation_dropout SCREAMING_SNAKE_CASE__ : Dict = init_std SCREAMING_SNAKE_CASE__ : Tuple = decoder_layerdrop SCREAMING_SNAKE_CASE__ : List[str] = use_cache SCREAMING_SNAKE_CASE__ : List[str] = scale_embedding SCREAMING_SNAKE_CASE__ : str = use_learned_position_embeddings SCREAMING_SNAKE_CASE__ : Tuple = layernorm_embedding super().__init__( pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , decoder_start_token_id=lowerCamelCase_ , **lowerCamelCase_ , )
717
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class __a (UpperCamelCase_): '''simple docstring''' def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" with open(_a , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ : str = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = input_file.read() SCREAMING_SNAKE_CASE__ : str = regexp.search(_a ) return match def _a ( self , _a ) -> Optional[Any]: """simple docstring""" with open(_a , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ : Tuple = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) SCREAMING_SNAKE_CASE__ : List[Any] = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE__ : Dict = regexp.finditer(_a ) SCREAMING_SNAKE_CASE__ : int = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_a ) ): raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ : List[str] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(_a ) ): raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
12
0
import os import re import shutil import sys import tempfile import unittest import black a :int = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. a :List[str] = ''' \""" Output class for the scheduler\'s step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \""" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None ''' class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , """schedulers/""" ) ) SCREAMING_SNAKE_CASE__ : Tuple = self.diffusers_dir shutil.copy( os.path.join(__UpperCamelCase , """src/diffusers/schedulers/scheduling_ddpm.py""" ) , os.path.join(self.diffusers_dir , """schedulers/scheduling_ddpm.py""" ) , ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """src/diffusers""" shutil.rmtree(self.diffusers_dir ) def _a ( self , _a , _a , _a , _a=None ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = comment + f'''\nclass {class_name}(nn.Module):\n''' + class_code if overwrite_result is not None: SCREAMING_SNAKE_CASE__ : str = comment + f'''\nclass {class_name}(nn.Module):\n''' + overwrite_result SCREAMING_SNAKE_CASE__ : Any = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) SCREAMING_SNAKE_CASE__ : List[Any] = black.format_str(__UpperCamelCase , mode=__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(self.diffusers_dir , """new_code.py""" ) with open(__UpperCamelCase , """w""" , newline="""\n""" ) as f: f.write(__UpperCamelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__UpperCamelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__UpperCamelCase ) with open(__UpperCamelCase , """r""" ) as f: self.assertTrue(f.read() , __UpperCamelCase ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = check_copies.find_code_in_diffusers("""schedulers.scheduling_ddpm.DDPMSchedulerOutput""" ) self.assertEqual(__UpperCamelCase , __UpperCamelCase ) def _a ( self ) -> Union[str, Any]: """simple docstring""" self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , __UpperCamelCase , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , re.sub("""DDPM""" , """Test""" , __UpperCamelCase ) , ) # Copy consistency with a really long name SCREAMING_SNAKE_CASE__ : int = """TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( f'''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}''' , f'''{long_class_name}SchedulerOutput''' , re.sub("""Bert""" , __UpperCamelCase , __UpperCamelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , __UpperCamelCase , overwrite_result=re.sub("""DDPM""" , """Test""" , __UpperCamelCase ) , )
718
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class __a : '''simple docstring''' def __init__( self , _a , _a=99 , _a=13 , _a=7 , _a=9 , _a=True , _a=True , _a=False , _a=32 , _a=5 , _a=4 , _a=37 , _a=8 , _a=0.1 , _a=0.002 , _a=1 , _a=0 , _a=0 , _a=None , _a=None , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Tuple = encoder_seq_length SCREAMING_SNAKE_CASE__ : str = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE__ : Optional[int] = self.decoder_seq_length SCREAMING_SNAKE_CASE__ : Tuple = is_training SCREAMING_SNAKE_CASE__ : Dict = use_attention_mask SCREAMING_SNAKE_CASE__ : List[str] = use_labels SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = d_ff SCREAMING_SNAKE_CASE__ : Any = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor SCREAMING_SNAKE_CASE__ : List[Any] = eos_token_id SCREAMING_SNAKE_CASE__ : List[str] = pad_token_id SCREAMING_SNAKE_CASE__ : Any = decoder_start_token_id SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : str = decoder_layers def _a ( self ) -> Tuple: """simple docstring""" return TaConfig.from_pretrained("""google/umt5-base""" ) def _a ( self , _a , _a , _a , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> Any: """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : int = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE__ : str = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_a ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_a ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=_a ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input SCREAMING_SNAKE_CASE__ : Tuple = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config() SCREAMING_SNAKE_CASE__ : List[str] = config.num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_inputs_dict(_a , _a , _a ) return config, input_dict def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() return config, inputs_dict def _a ( self ) -> List[str]: """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self ) -> List[Any]: """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = UMTaModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model( input_ids=_a , decoder_input_ids=_a , attention_mask=_a , decoder_attention_mask=_a , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=_a , decoder_input_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = result.last_hidden_state SCREAMING_SNAKE_CASE__ : Dict = result.past_key_values SCREAMING_SNAKE_CASE__ : Any = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(_a ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).get_decoder().to(_a ).eval() # first forward pass SCREAMING_SNAKE_CASE__ : str = model(_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , use_cache=_a ) self.parent.assertTrue(len(_a ) == len(_a ) ) self.parent.assertTrue(len(_a ) == len(_a ) + 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : Tuple = model(_a , past_key_values=_a )["""last_hidden_state"""] # select random slice SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) ) def _a ( self , _a , _a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).to(_a ).half().eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**_a )["""last_hidden_state"""] self.parent.assertFalse(torch.isnan(_a ).any().item() ) @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :List[str] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Union[str, Any] = True _SCREAMING_SNAKE_CASE :Tuple = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = True _SCREAMING_SNAKE_CASE :List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _SCREAMING_SNAKE_CASE :Union[str, Any] = [0.8, 0.9] def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = UMTaModelTester(self ) @unittest.skip("""Test has a segmentation fault on torch 1.8.0""" ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = UMTaModel(config_and_inputs[0] ).to(_a ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( _a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=_a , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*_a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""] SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs[0] SCREAMING_SNAKE_CASE__ : Tuple = UMTaForConditionalGeneration(_a ).eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = { """head_mask""": torch.zeros(config.num_layers , config.num_heads , device=_a ), """decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), } for attn_name, (name, mask) in zip(_a , head_masking.items() ): SCREAMING_SNAKE_CASE__ : List[str] = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": SCREAMING_SNAKE_CASE__ : str = torch.ones( config.num_decoder_layers , config.num_heads , device=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.generate( config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=_a , return_dict_in_generate=_a , **_a , ) # We check the state of decoder_attentions and cross_attentions just from the last step SCREAMING_SNAKE_CASE__ : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" ) def _a ( self ) -> Dict: """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow @unittest.skip( """Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=_a ).to(_a ) SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=_a , legacy=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ """Bonjour monsieur <extra_id_0> bien <extra_id_1>.""", """No se como puedo <extra_id_0>.""", """This is the reason why we <extra_id_0> them.""", """The <extra_id_0> walks in <extra_id_1>, seats""", """A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""", ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_a , return_tensors="""pt""" , padding=_a ).input_ids # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(_a , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids.to(_a ) ) SCREAMING_SNAKE_CASE__ : int = [ """<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""", """<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", ] SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.batch_decode(_a ) self.assertEqual(_a , _a )
12
0
from __future__ import annotations from typing import Any class __a : '''simple docstring''' def __init__( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = num_of_nodes SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : str = {} def _a ( self , _a , _a , _a ) -> None: """simple docstring""" self.m_edges.append([u_node, v_node, weight] ) def _a ( self , _a ) -> int: """simple docstring""" if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def _a ( self , _a ) -> None: """simple docstring""" if self.m_component[u_node] != u_node: for k in self.m_component: SCREAMING_SNAKE_CASE__ : Dict = self.find_component(snake_case_ ) def _a ( self , _a , _a , _a ) -> None: """simple docstring""" if component_size[u_node] <= component_size[v_node]: SCREAMING_SNAKE_CASE__ : Optional[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(snake_case_ ) elif component_size[u_node] >= component_size[v_node]: SCREAMING_SNAKE_CASE__ : Optional[int] = self.find_component(snake_case_ ) component_size[u_node] += component_size[v_node] self.set_component(snake_case_ ) def _a ( self ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : str = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) SCREAMING_SNAKE_CASE__ : Any = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = edge SCREAMING_SNAKE_CASE__ : Optional[Any] = self.m_component[u] SCREAMING_SNAKE_CASE__ : str = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(snake_case_ , snake_case_ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = edge SCREAMING_SNAKE_CASE__ : List[Any] = self.m_component[u] SCREAMING_SNAKE_CASE__ : Dict = self.m_component[v] if u_component != v_component: mst_weight += w self.union(snake_case_ , snake_case_ , snake_case_ ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 SCREAMING_SNAKE_CASE__ : Tuple = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def _lowercase ( ) -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
719
"""simple docstring""" import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a , _a = None , _a = None , _a = False , **_a , ) -> Union[str, Any]: """simple docstring""" super().__init__(features=_a , cache_dir=_a , keep_in_memory=_a , **_a ) SCREAMING_SNAKE_CASE__ : List[Any] = Sql( cache_dir=_a , features=_a , sql=_a , con=_a , **_a , ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None self.builder.download_and_prepare( download_config=_a , download_mode=_a , verification_mode=_a , base_path=_a , ) # Build dataset for splits SCREAMING_SNAKE_CASE__ : str = self.builder.as_dataset( split="""train""" , verification_mode=_a , in_memory=self.keep_in_memory ) return dataset class __a : '''simple docstring''' def __init__( self , _a , _a , _a , _a = None , _a = None , **_a , ) -> Any: """simple docstring""" if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) SCREAMING_SNAKE_CASE__ : int = dataset SCREAMING_SNAKE_CASE__ : Any = name SCREAMING_SNAKE_CASE__ : Optional[Any] = con SCREAMING_SNAKE_CASE__ : List[Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE SCREAMING_SNAKE_CASE__ : int = num_proc SCREAMING_SNAKE_CASE__ : int = to_sql_kwargs def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.to_sql_kwargs.pop("""sql""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = self.to_sql_kwargs.pop("""con""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = self.to_sql_kwargs.pop("""index""" , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._write(index=_a , **self.to_sql_kwargs ) return written def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = args SCREAMING_SNAKE_CASE__ : List[str] = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs SCREAMING_SNAKE_CASE__ : Any = query_table( table=self.dataset.data , key=slice(_a , offset + self.batch_size ) , indices=self.dataset._indices , ) SCREAMING_SNAKE_CASE__ : Optional[int] = batch.to_pandas() SCREAMING_SNAKE_CASE__ : List[Any] = df.to_sql(self.name , self.con , index=_a , **_a ) return num_rows or len(_a ) def _a ( self , _a , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _a , _a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
12
0
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class __a (SCREAMING_SNAKE_CASE__): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = 42 class __a (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__): '''simple docstring''' @register_to_config def __init__( self , _a = 32 , _a = 64 , _a = 20 , _a = 768 , _a=77 , _a=4 , _a = 0.0 , _a = "silu" , _a = None , _a = None , _a = "linear" , _a = "prd" , _a = None , _a = None , _a = None , ) -> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : str = attention_head_dim SCREAMING_SNAKE_CASE__ : Optional[Any] = num_attention_heads * attention_head_dim SCREAMING_SNAKE_CASE__ : List[str] = additional_embeddings SCREAMING_SNAKE_CASE__ : Any = time_embed_dim or inner_dim SCREAMING_SNAKE_CASE__ : Any = embedding_proj_dim or embedding_dim SCREAMING_SNAKE_CASE__ : List[str] = clip_embed_dim or embedding_dim SCREAMING_SNAKE_CASE__ : int = Timesteps(_lowercase , _lowercase , 0 ) SCREAMING_SNAKE_CASE__ : Dict = TimestepEmbedding(_lowercase , _lowercase , out_dim=_lowercase , act_fn=_lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = nn.Linear(_lowercase , _lowercase ) if embedding_proj_norm_type is None: SCREAMING_SNAKE_CASE__ : List[str] = None elif embedding_proj_norm_type == "layer": SCREAMING_SNAKE_CASE__ : Dict = nn.LayerNorm(_lowercase ) else: raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) SCREAMING_SNAKE_CASE__ : Any = nn.Linear(_lowercase , _lowercase ) if encoder_hid_proj_type is None: SCREAMING_SNAKE_CASE__ : str = None elif encoder_hid_proj_type == "linear": SCREAMING_SNAKE_CASE__ : List[str] = nn.Linear(_lowercase , _lowercase ) else: raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) SCREAMING_SNAKE_CASE__ : Any = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _lowercase ) ) if added_emb_type == "prd": SCREAMING_SNAKE_CASE__ : Dict = nn.Parameter(torch.zeros(1 , 1 , _lowercase ) ) elif added_emb_type is None: SCREAMING_SNAKE_CASE__ : int = None else: raise ValueError( f'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) SCREAMING_SNAKE_CASE__ : Tuple = nn.ModuleList( [ BasicTransformerBlock( _lowercase , _lowercase , _lowercase , dropout=_lowercase , activation_fn="""gelu""" , attention_bias=_lowercase , ) for d in range(_lowercase ) ] ) if norm_in_type == "layer": SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.LayerNorm(_lowercase ) elif norm_in_type is None: SCREAMING_SNAKE_CASE__ : List[str] = None else: raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.''' ) SCREAMING_SNAKE_CASE__ : int = nn.LayerNorm(_lowercase ) SCREAMING_SNAKE_CASE__ : str = nn.Linear(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10_000.0 ) causal_attention_mask.triu_(1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , _lowercase , persistent=_lowercase ) SCREAMING_SNAKE_CASE__ : Any = nn.Parameter(torch.zeros(1 , _lowercase ) ) SCREAMING_SNAKE_CASE__ : Dict = nn.Parameter(torch.zeros(1 , _lowercase ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def _a ( self ) -> Dict[str, AttentionProcessor]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = {} def fn_recursive_add_processors(_a , _a , _a ): if hasattr(_lowercase , """set_processor""" ): SCREAMING_SNAKE_CASE__ : str = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f'''{name}.{sub_name}''' , _lowercase , _lowercase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_lowercase , _lowercase , _lowercase ) return processors def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = len(self.attn_processors.keys() ) if isinstance(_lowercase , _lowercase ) and len(_lowercase ) != count: raise ValueError( f'''A dict of processors was passed, but the number of processors {len(_lowercase )} does not match the''' f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(_a , _a , _a ): if hasattr(_lowercase , """set_processor""" ): if not isinstance(_lowercase , _lowercase ): module.set_processor(_lowercase ) else: module.set_processor(processor.pop(f'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f'''{name}.{sub_name}''' , _lowercase , _lowercase ) for name, module in self.named_children(): fn_recursive_attn_processor(_lowercase , _lowercase , _lowercase ) def _a ( self ) -> int: """simple docstring""" self.set_attn_processor(AttnProcessor() ) def _a ( self , _a , _a , _a , _a = None , _a = None , _a = True , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = hidden_states.shape[0] SCREAMING_SNAKE_CASE__ : List[Any] = timestep if not torch.is_tensor(_lowercase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(_lowercase ) and len(timesteps.shape ) == 0: SCREAMING_SNAKE_CASE__ : str = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML SCREAMING_SNAKE_CASE__ : Optional[Any] = timesteps * torch.ones(_lowercase , dtype=timesteps.dtype , device=timesteps.device ) SCREAMING_SNAKE_CASE__ : Tuple = self.time_proj(_lowercase ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. SCREAMING_SNAKE_CASE__ : List[Any] = timesteps_projected.to(dtype=self.dtype ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.time_embedding(_lowercase ) if self.embedding_proj_norm is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.embedding_proj_norm(_lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] = self.embedding_proj(_lowercase ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: SCREAMING_SNAKE_CASE__ : List[Any] = self.encoder_hidden_states_proj(_lowercase ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) SCREAMING_SNAKE_CASE__ : Dict = self.proj_in(_lowercase ) SCREAMING_SNAKE_CASE__ : str = self.positional_embedding.to(hidden_states.dtype ) SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 if encoder_hidden_states is not None: additional_embeds.append(_lowercase ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: SCREAMING_SNAKE_CASE__ : str = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: SCREAMING_SNAKE_CASE__ : Dict = hidden_states[:, None, :] SCREAMING_SNAKE_CASE__ : List[str] = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.prd_embedding.to(hidden_states.dtype ).expand(_lowercase , -1 , -1 ) additional_embeds.append(_lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat( _lowercase , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens SCREAMING_SNAKE_CASE__ : Optional[int] = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: SCREAMING_SNAKE_CASE__ : List[Any] = F.pad( _lowercase , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) SCREAMING_SNAKE_CASE__ : int = hidden_states + positional_embeddings if attention_mask is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (1 - attention_mask.to(hidden_states.dtype )) * -10_000.0 SCREAMING_SNAKE_CASE__ : Dict = F.pad(_lowercase , (0, self.additional_embeddings) , value=0.0 ) SCREAMING_SNAKE_CASE__ : List[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) SCREAMING_SNAKE_CASE__ : int = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.norm_in(_lowercase ) for block in self.transformer_blocks: SCREAMING_SNAKE_CASE__ : Optional[Any] = block(_lowercase , attention_mask=_lowercase ) SCREAMING_SNAKE_CASE__ : int = self.norm_out(_lowercase ) if self.prd_embedding is not None: SCREAMING_SNAKE_CASE__ : Dict = hidden_states[:, -1] else: SCREAMING_SNAKE_CASE__ : Tuple = hidden_states[:, additional_embeddings_len:] SCREAMING_SNAKE_CASE__ : List[Any] = self.proj_to_clip_embeddings(_lowercase ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=_lowercase ) def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
720
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : int = 1 while repunit: SCREAMING_SNAKE_CASE__ : str = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def _lowercase ( __lowerCAmelCase = 100_0000 ) -> int: SCREAMING_SNAKE_CASE__ : Dict = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(__lowerCAmelCase ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class __a : '''simple docstring''' def __init__( self , _a , _a = 13 , _a = 64 , _a = 2 , _a = 3 , _a = 3 , _a = True , _a = True , _a = 128 , _a=[16, 32, 64, 128] , _a = 7 , _a = 4 , _a = 37 , _a = "gelu" , _a = 0.1 , _a = 0.1 , _a = 10 , _a = 0.02 , _a = 2 , _a = 1 , _a = 128 , _a = [2, 2, 2, 2] , _a = 2 , _a = 2 , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = encoder_stride SCREAMING_SNAKE_CASE__ : Dict = num_attention_outputs SCREAMING_SNAKE_CASE__ : Any = embed_dim SCREAMING_SNAKE_CASE__ : Any = embed_dim + 1 SCREAMING_SNAKE_CASE__ : Any = resolution SCREAMING_SNAKE_CASE__ : str = depths SCREAMING_SNAKE_CASE__ : List[Any] = hidden_sizes SCREAMING_SNAKE_CASE__ : Dict = dim SCREAMING_SNAKE_CASE__ : Union[str, Any] = mlp_expansion_ratio def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : str = self.get_config() return config, pixel_values, labels def _a ( self ) -> List[str]: """simple docstring""" return EfficientFormerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=A_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def _a ( self , _a , _a , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFEfficientFormerModel(config=A_ ) SCREAMING_SNAKE_CASE__ : Any = model(A_ , training=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[int] = TFEfficientFormerForImageClassification(A_ ) SCREAMING_SNAKE_CASE__ : str = model(A_ , labels=A_ , training=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Dict = TFEfficientFormerForImageClassification(A_ ) SCREAMING_SNAKE_CASE__ : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __a (_lowercase , _lowercase , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :Union[str, Any] = ( { '''feature-extraction''': TFEfficientFormerModel, '''image-classification''': ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE :int = False _SCREAMING_SNAKE_CASE :Tuple = False _SCREAMING_SNAKE_CASE :Dict = False _SCREAMING_SNAKE_CASE :Dict = False _SCREAMING_SNAKE_CASE :Any = False def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFEfficientFormerModelTester(self ) SCREAMING_SNAKE_CASE__ : Any = ConfigTester( self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def _a ( self ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""EfficientFormer does not use inputs_embeds""" ) def _a ( self ) -> Any: """simple docstring""" pass @unittest.skip(reason="""EfficientFormer does not support input and output embeddings""" ) def _a ( self ) -> Dict: """simple docstring""" pass def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(A_ ) SCREAMING_SNAKE_CASE__ : Tuple = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Tuple = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , A_ ) def _a ( self ) -> Union[str, Any]: """simple docstring""" def check_hidden_states_output(_a , _a , _a ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(A_ ) SCREAMING_SNAKE_CASE__ : Any = model(**self._prepare_for_class(A_ , A_ ) , training=A_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(A_ ) , A_ ) if hasattr(self.model_tester , """encoder_seq_length""" ): SCREAMING_SNAKE_CASE__ : int = self.model_tester.encoder_seq_length if hasattr(self.model_tester , """chunk_length""" ) and self.model_tester.chunk_length > 1: SCREAMING_SNAKE_CASE__ : List[str] = seq_length * self.model_tester.chunk_length else: SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: SCREAMING_SNAKE_CASE__ : List[Any] = outputs.decoder_hidden_states self.asseretIsInstance(A_ , (list, tuple) ) self.assertEqual(len(A_ ) , A_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(self.model_tester , """seq_length""" , A_ ) SCREAMING_SNAKE_CASE__ : Tuple = getattr(self.model_tester , """decoder_seq_length""" , A_ ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Dict = True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(A_ , A_ , A_ ) def _a ( self , _a , _a , _a=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = super()._prepare_for_class(A_ , A_ , return_labels=A_ ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet""" ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A_ ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) @slow def _a ( self ) -> Any: """simple docstring""" for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Dict = TFEfficientFormerModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(self.model_tester , """seq_length""" , A_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(self.model_tester , """encoder_seq_length""" , A_ ) SCREAMING_SNAKE_CASE__ : Dict = getattr(self.model_tester , """key_length""" , A_ ) SCREAMING_SNAKE_CASE__ : Dict = getattr(self.model_tester , """chunk_length""" , A_ ) if chunk_length is not None and hasattr(self.model_tester , """num_hashes""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : int = False SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : List[Any] = model_class(A_ ) SCREAMING_SNAKE_CASE__ : int = model(**self._prepare_for_class(A_ , A_ ) , training=A_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(A_ ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : int = model_class(A_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(A_ , A_ ) , training=A_ ) SCREAMING_SNAKE_CASE__ : str = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(A_ ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(A_ ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes SCREAMING_SNAKE_CASE__ : Optional[int] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=A_ ) for key, val in model.input_signature.items() if key in model.dummy_inputs } SCREAMING_SNAKE_CASE__ : Any = model(A_ ) self.assertTrue(outputs_dict is not None ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class __a (unittest.TestCase): '''simple docstring''' @cached_property def _a ( self ) -> List[Any]: """simple docstring""" return ( EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300""" ) if is_vision_available() else None ) @slow def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=A_ , return_tensors="""tf""" ) # forward pass SCREAMING_SNAKE_CASE__ : List[str] = model(**A_ , training=A_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , A_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant([-0.0_555, 0.4_825, -0.0_852] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , A_ , atol=1E-4 ) ) @slow def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( """snap-research/efficientformer-l1-300""" ) SCREAMING_SNAKE_CASE__ : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=A_ , return_tensors="""tf""" ) # forward pass SCREAMING_SNAKE_CASE__ : int = model(**A_ , training=A_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , A_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.constant([-0.1_312, 0.4_353, -1.0_499] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , A_ , atol=1E-4 ) )
721
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") a :Union[str, Any] = logging.getLogger(__name__) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of prediction examples to this """ """value if set.""" ) } , ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}) _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Train language if it is different from the evaluation language."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) _SCREAMING_SNAKE_CASE :Optional[bool] = field( default=UpperCamelCase_ , metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) _SCREAMING_SNAKE_CASE :str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def _lowercase ( ) -> Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE__ : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_xnli""" , __lowerCAmelCase ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : List[Any] = training_args.get_process_log_level() logger.setLevel(__lowerCAmelCase ) datasets.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__ : Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__ : Optional[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: SCREAMING_SNAKE_CASE__ : Optional[int] = load_dataset( """xnli""" , model_args.language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: SCREAMING_SNAKE_CASE__ : str = load_dataset( """xnli""" , model_args.train_language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = train_dataset.features["""label"""].names if training_args.do_eval: SCREAMING_SNAKE_CASE__ : int = load_dataset( """xnli""" , model_args.language , split="""validation""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.features["""label"""].names if training_args.do_predict: SCREAMING_SNAKE_CASE__ : int = load_dataset( """xnli""" , model_args.language , split="""test""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Tuple = predict_dataset.features["""label"""].names # Labels SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__lowerCAmelCase , idalabel={str(__lowerCAmelCase ): label for i, label in enumerate(__lowerCAmelCase )} , labelaid={label: i for i, label in enumerate(__lowerCAmelCase )} , finetuning_task="""xnli""" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : str = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : str = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch SCREAMING_SNAKE_CASE__ : Optional[Any] = False def preprocess_function(__lowerCAmelCase ): # Tokenize the texts return tokenizer( examples["""premise"""] , examples["""hypothesis"""] , padding=__lowerCAmelCase , max_length=data_args.max_seq_length , truncation=__lowerCAmelCase , ) if training_args.do_train: if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(len(__lowerCAmelCase ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE__ : str = train_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : List[str] = train_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on train dataset""" , ) # Log a few random samples from the training set: for index in random.sample(range(len(__lowerCAmelCase ) ) , 3 ): logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.''' ) if training_args.do_eval: if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__ : Any = min(len(__lowerCAmelCase ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : List[str] = eval_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on validation dataset""" , ) if training_args.do_predict: if data_args.max_predict_samples is not None: SCREAMING_SNAKE_CASE__ : int = min(len(__lowerCAmelCase ) , data_args.max_predict_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = predict_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""prediction dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : Tuple = predict_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on prediction dataset""" , ) # Get the metric function SCREAMING_SNAKE_CASE__ : Optional[Any] = evaluate.load("""xnli""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Dict = p.predictions[0] if isinstance(p.predictions , __lowerCAmelCase ) else p.predictions SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.argmax(__lowerCAmelCase , axis=1 ) return metric.compute(predictions=__lowerCAmelCase , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : List[Any] = default_data_collator elif training_args.fpaa: SCREAMING_SNAKE_CASE__ : int = DataCollatorWithPadding(__lowerCAmelCase , pad_to_multiple_of=8 ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # Initialize our Trainer SCREAMING_SNAKE_CASE__ : Union[str, Any] = Trainer( model=__lowerCAmelCase , args=__lowerCAmelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , data_collator=__lowerCAmelCase , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__ : Dict = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = last_checkpoint SCREAMING_SNAKE_CASE__ : str = trainer.train(resume_from_checkpoint=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = train_result.metrics SCREAMING_SNAKE_CASE__ : Optional[int] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Dict = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , __lowerCAmelCase ) trainer.save_metrics("""train""" , __lowerCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE__ : Any = trainer.evaluate(eval_dataset=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""eval""" , __lowerCAmelCase ) trainer.save_metrics("""eval""" , __lowerCAmelCase ) # Prediction if training_args.do_predict: logger.info("""*** Predict ***""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = trainer.predict(__lowerCAmelCase , metric_key_prefix="""predict""" ) SCREAMING_SNAKE_CASE__ : List[str] = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : int = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""predict""" , __lowerCAmelCase ) trainer.save_metrics("""predict""" , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = np.argmax(__lowerCAmelCase , axis=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(training_args.output_dir , """predictions.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCAmelCase , """w""" ) as writer: writer.write("""index\tprediction\n""" ) for index, item in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = label_list[item] writer.write(F'''{index}\t{item}\n''' ) if __name__ == "__main__": main()
12
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a :List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class __a (lowercase__): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = ['pixel_values'] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BICUBIC , _a = True , _a = None , _a = True , _a = 1 / 255 , _a = True , _a = None , _a = None , _a = True , **_a , ) -> Union[str, Any]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : str = size if size is not None else {"""shortest_edge""": 224} SCREAMING_SNAKE_CASE__ : List[str] = get_size_dict(_a , default_to_square=_a ) SCREAMING_SNAKE_CASE__ : Any = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(_a , default_to_square=_a , param_name="""crop_size""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = do_resize SCREAMING_SNAKE_CASE__ : Union[str, Any] = size SCREAMING_SNAKE_CASE__ : Union[str, Any] = resample SCREAMING_SNAKE_CASE__ : Optional[int] = do_center_crop SCREAMING_SNAKE_CASE__ : Optional[int] = crop_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_rescale SCREAMING_SNAKE_CASE__ : str = rescale_factor SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = image_mean if image_mean is not None else OPENAI_CLIP_MEAN SCREAMING_SNAKE_CASE__ : List[Any] = image_std if image_std is not None else OPENAI_CLIP_STD SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_convert_rgb def _a ( self , _a , _a , _a = PILImageResampling.BICUBIC , _a = None , **_a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_size_dict(_a , default_to_square=_a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE__ : str = get_resize_output_image_size(_a , size=size["""shortest_edge"""] , default_to_square=_a ) return resize(_a , size=_a , resample=_a , data_format=_a , **_a ) def _a ( self , _a , _a , _a = None , **_a , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(_a , size=(size["""height"""], size["""width"""]) , data_format=_a , **_a ) def _a ( self , _a , _a , _a = None , **_a , ) -> Optional[int]: """simple docstring""" return rescale(_a , scale=_a , data_format=_a , **_a ) def _a ( self , _a , _a , _a , _a = None , **_a , ) -> Tuple: """simple docstring""" return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def _a ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : Tuple = get_size_dict(_a , param_name="""size""" , default_to_square=_a ) SCREAMING_SNAKE_CASE__ : str = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE__ : str = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE__ : Dict = get_size_dict(_a , param_name="""crop_size""" , default_to_square=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE__ : Dict = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE__ : int = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb SCREAMING_SNAKE_CASE__ : int = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: SCREAMING_SNAKE_CASE__ : Dict = [convert_to_rgb(_a ) for image in images] # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : Tuple = [to_numpy_array(_a ) for image in images] if do_resize: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE__ : int = [self.center_crop(image=_a , size=_a ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : int = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE__ : Tuple = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] SCREAMING_SNAKE_CASE__ : Optional[Any] = [to_channel_dimension_format(_a , _a ) for image in images] SCREAMING_SNAKE_CASE__ : Any = {"""pixel_values""": images} return BatchFeature(data=_a , tensor_type=_a )
700
"""simple docstring""" # Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() a :str = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model a :int = { # fairseq: "wmt19-ru-en": {"length_penalty": 1.1}, "wmt19-en-ru": {"length_penalty": 1.15}, "wmt19-en-de": {"length_penalty": 1.0}, "wmt19-de-en": {"length_penalty": 1.1}, # allenai: "wmt16-en-de-dist-12-1": {"length_penalty": 0.6}, "wmt16-en-de-dist-6-1": {"length_penalty": 0.6}, "wmt16-en-de-12-1": {"length_penalty": 0.8}, "wmt19-de-en-6-6-base": {"length_penalty": 0.6}, "wmt19-de-en-6-6-big": {"length_penalty": 0.6}, } # this remaps the different models to their organization names a :Dict = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: a :List[Any] = "facebook" for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: a :str = "allenai" def _lowercase ( __lowerCAmelCase ) -> Any: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} SCREAMING_SNAKE_CASE__ : str = dict((re.sub(r"""@@$""" , """""" , __lowerCAmelCase ), v) if k.endswith("""@@""" ) else (re.sub(r"""$""" , """</w>""" , __lowerCAmelCase ), v) for k, v in d.items() ) SCREAMING_SNAKE_CASE__ : Tuple = """<s> <pad> </s> <unk>""".split() # restore the special tokens for k in keep_keys: del da[F'''{k}</w>'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] = d[k] # restore return da def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: # prep assert os.path.exists(__lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) print(F'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models SCREAMING_SNAKE_CASE__ : Optional[Any] = basename(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = dirname(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel SCREAMING_SNAKE_CASE__ : Optional[int] = cls.hub_models() SCREAMING_SNAKE_CASE__ : Optional[int] = {"""bpe""": """fastbpe""", """tokenizer""": """moses"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = """.""" # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(F'''using checkpoint {checkpoint_file}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = hub_utils.from_pretrained( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , archive_map=__lowerCAmelCase , **__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = vars(chkpt["""args"""]["""model"""] ) SCREAMING_SNAKE_CASE__ : Any = args["""source_lang"""] SCREAMING_SNAKE_CASE__ : Any = args["""target_lang"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = dirname(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = basename(__lowerCAmelCase ) # dicts SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(__lowerCAmelCase , F'''dict.{src_lang}.txt''' ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , F'''dict.{tgt_lang}.txt''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Dictionary.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = rewrite_dict_keys(src_dict.indices ) SCREAMING_SNAKE_CASE__ : Optional[int] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , """vocab-src.json""" ) print(F'''Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab SCREAMING_SNAKE_CASE__ : Optional[Any] = True for k in src_vocab.keys(): if not k.islower(): SCREAMING_SNAKE_CASE__ : Tuple = False break SCREAMING_SNAKE_CASE__ : Optional[Any] = Dictionary.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rewrite_dict_keys(tgt_dict.indices ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , """vocab-tgt.json""" ) print(F'''Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # merges_file (bpecodes) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , VOCAB_FILES_NAMES["""merges_file"""] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if os.path.exists(__lowerCAmelCase ): break with open(__lowerCAmelCase , encoding="""utf-8""" ) as fin: SCREAMING_SNAKE_CASE__ : Any = fin.read() SCREAMING_SNAKE_CASE__ : Tuple = re.sub(r""" \d+$""" , """""" , __lowerCAmelCase , 0 , re.M ) # remove frequency number print(F'''Generating {merges_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as fout: fout.write(__lowerCAmelCase ) # model config SCREAMING_SNAKE_CASE__ : Dict = os.path.join(__lowerCAmelCase , """config.json""" ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", F'''need to extend tokenizer to support bpe={args['bpe']}''' assert args["tokenizer"] == "moses", F'''need to extend tokenizer to support bpe={args['tokenizer']}''' SCREAMING_SNAKE_CASE__ : str = { """architectures""": ["""FSMTForConditionalGeneration"""], """model_type""": """fsmt""", """activation_dropout""": args["""activation_dropout"""], """activation_function""": """relu""", """attention_dropout""": args["""attention_dropout"""], """d_model""": args["""decoder_embed_dim"""], """dropout""": args["""dropout"""], """init_std""": 0.02, """max_position_embeddings""": args["""max_source_positions"""], """num_hidden_layers""": args["""encoder_layers"""], """src_vocab_size""": src_vocab_size, """tgt_vocab_size""": tgt_vocab_size, """langs""": [src_lang, tgt_lang], """encoder_attention_heads""": args["""encoder_attention_heads"""], """encoder_ffn_dim""": args["""encoder_ffn_embed_dim"""], """encoder_layerdrop""": args["""encoder_layerdrop"""], """encoder_layers""": args["""encoder_layers"""], """decoder_attention_heads""": args["""decoder_attention_heads"""], """decoder_ffn_dim""": args["""decoder_ffn_embed_dim"""], """decoder_layerdrop""": args["""decoder_layerdrop"""], """decoder_layers""": args["""decoder_layers"""], """bos_token_id""": 0, """pad_token_id""": 1, """eos_token_id""": 2, """is_encoder_decoder""": True, """scale_embedding""": not args["""no_scale_embedding"""], """tie_word_embeddings""": args["""share_all_embeddings"""], } # good hparam defaults to start with SCREAMING_SNAKE_CASE__ : Tuple = 5 SCREAMING_SNAKE_CASE__ : str = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: SCREAMING_SNAKE_CASE__ : Tuple = best_score_hparams[model_dir]["""length_penalty"""] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 1.0 print(F'''Generating {fsmt_model_config_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # tokenizer config SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = { """langs""": [src_lang, tgt_lang], """model_max_length""": 1024, """do_lower_case""": do_lower_case, } print(F'''Generating {fsmt_tokenizer_config_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # model SCREAMING_SNAKE_CASE__ : Dict = chkpt["""models"""][0] SCREAMING_SNAKE_CASE__ : int = model.state_dict() # rename keys to start with 'model.' SCREAMING_SNAKE_CASE__ : Tuple = OrderedDict(("""model.""" + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys SCREAMING_SNAKE_CASE__ : str = [ """model.model""", """model.encoder.version""", """model.decoder.version""", """model.encoder_embed_tokens.weight""", """model.decoder_embed_tokens.weight""", """model.encoder.embed_positions._float_tensor""", """model.decoder.embed_positions._float_tensor""", ] for k in ignore_keys: model_state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = FSMTConfig.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = FSMTForConditionalGeneration(__lowerCAmelCase ) # check that it loads ok model_new.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase ) # save SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) print(F'''Generating {pytorch_weights_dump_path}''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) print("""Conversion is done!""" ) print("""\nLast step is to upload the files to s3""" ) print(F'''cd {data_root}''' ) print(F'''transformers-cli upload {model_dir}''' ) if __name__ == "__main__": a :Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fsmt_checkpoint_path", default=None, type=str, required=True, help=( "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts," " bpecodes, etc." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) a :List[str] = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
12
0
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = [] create_all_state(1 , __lowerCAmelCase , __lowerCAmelCase , [] , __lowerCAmelCase ) return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Any: if level == 0: total_list.append(current_list[:] ) return for i in range(__lowerCAmelCase , total_number - level + 2 ): current_list.append(__lowerCAmelCase ) create_all_state(i + 1 , __lowerCAmelCase , level - 1 , __lowerCAmelCase , __lowerCAmelCase ) current_list.pop() def _lowercase ( __lowerCAmelCase ) -> List[Any]: for i in total_list: print(*__lowerCAmelCase ) if __name__ == "__main__": a :Union[str, Any] = 4 a :List[Any] = 2 a :Tuple = generate_all_combinations(n, k) print_all_state(total_list)
701
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = (DDPMScheduler,) def _a ( self , **_a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**_a ) return config def _a ( self ) -> str: """simple docstring""" for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def _a ( self ) -> str: """simple docstring""" for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def _a ( self ) -> Any: """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def _a ( self ) -> int: """simple docstring""" self.check_over_configs(thresholding=_a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , ) def _a ( self ) -> str: """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def _a ( self ) -> str: """simple docstring""" for t in [0, 500, 999]: self.check_over_forward(time_step=_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Any = len(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : str = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : int = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : str = pred_prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.9_606 ) < 1E-2 assert abs(result_mean.item() - 0.3_372 ) < 1E-3 def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Tuple = self.get_scheduler_config(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Dict = len(_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : int = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : Tuple = pred_prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : int = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 202.0_296 ) < 1E-2 assert abs(result_mean.item() - 0.2_631 ) < 1E-3 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = -1 else: SCREAMING_SNAKE_CASE__ : Tuple = timesteps[i + 1] SCREAMING_SNAKE_CASE__ : int = scheduler.previous_timestep(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prev_t.item() self.assertEqual(_a , _a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [100, 87, 50, 51, 0] with self.assertRaises(_a , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : int = [100, 87, 50, 1, 0] SCREAMING_SNAKE_CASE__ : List[str] = len(_a ) with self.assertRaises(_a , msg="""Can only pass one of `num_inference_steps` or `custom_timesteps`.""" ): scheduler.set_timesteps(num_inference_steps=_a , timesteps=_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( _a , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=_a )
12
0
"""simple docstring""" a :int = range(2, 20 + 1) a :int = [10**k for k in range(ks[-1] + 1)] a :dict[int, dict[int, list[list[int]]]] = {} def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = sum(a_i[j] for j in range(snake_case_ , len(snake_case_ ) ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sum(a_i[j] * base[j] for j in range(min(len(snake_case_ ) , snake_case_ ) ) ) SCREAMING_SNAKE_CASE__ : Tuple = 0, 0 SCREAMING_SNAKE_CASE__ : Tuple = n - i SCREAMING_SNAKE_CASE__ : int = memo.get(snake_case_ ) if sub_memo is not None: SCREAMING_SNAKE_CASE__ : Tuple = sub_memo.get(snake_case_ ) if jumps is not None and len(snake_case_ ) > 0: # find and make the largest jump without going over SCREAMING_SNAKE_CASE__ : Dict = -1 for _k in range(len(snake_case_ ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: SCREAMING_SNAKE_CASE__ : Union[str, Any] = _k break if max_jump >= 0: SCREAMING_SNAKE_CASE__ : Any = jumps[max_jump] # since the difference between jumps is cached, add c SCREAMING_SNAKE_CASE__ : str = diff + c for j in range(min(snake_case_ , len(snake_case_ ) ) ): SCREAMING_SNAKE_CASE__ : List[Any] = divmod(snake_case_ , 10 ) if new_c > 0: add(snake_case_ , snake_case_ , snake_case_ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [] else: SCREAMING_SNAKE_CASE__ : str = {c: []} SCREAMING_SNAKE_CASE__ : str = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps SCREAMING_SNAKE_CASE__ : Any = next_term(snake_case_ , k - 1 , i + dn , snake_case_ ) 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 SCREAMING_SNAKE_CASE__ : List[Any] = compute(snake_case_ , snake_case_ , i + dn , snake_case_ ) diff += _diff dn += terms_jumped SCREAMING_SNAKE_CASE__ : Optional[Any] = sub_memo[c] # keep jumps sorted by # of terms skipped SCREAMING_SNAKE_CASE__ : Optional[int] = 0 while j < len(snake_case_ ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(snake_case_ , (diff, dn, k) ) return (diff, dn) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: if i >= n: return 0, i if k > len(snake_case_ ): a_i.extend([0 for _ in range(k - len(snake_case_ ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) SCREAMING_SNAKE_CASE__ : Tuple = i SCREAMING_SNAKE_CASE__ : List[Any] = 0, 0, 0 for j in range(len(snake_case_ ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 SCREAMING_SNAKE_CASE__ : str = ds_c + ds_b diff += addend SCREAMING_SNAKE_CASE__ : Any = 0 for j in range(snake_case_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = a_i[j] + addend SCREAMING_SNAKE_CASE__ : str = divmod(snake_case_ , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(snake_case_ , snake_case_ , snake_case_ ) return diff, i - start_i def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: for j in range(snake_case_ , len(snake_case_ ) ): SCREAMING_SNAKE_CASE__ : int = digits[j] + addend if s >= 10: SCREAMING_SNAKE_CASE__ : List[Any] = divmod(snake_case_ , 10 ) SCREAMING_SNAKE_CASE__ : Optional[int] = addend // 10 + quotient else: SCREAMING_SNAKE_CASE__ : Optional[Any] = s SCREAMING_SNAKE_CASE__ : Optional[Any] = addend // 10 if addend == 0: break while addend > 0: SCREAMING_SNAKE_CASE__ : List[str] = divmod(snake_case_ , 10 ) digits.append(snake_case_ ) def _lowercase ( __lowerCAmelCase = 10**15 ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = [1] SCREAMING_SNAKE_CASE__ : int = 1 SCREAMING_SNAKE_CASE__ : List[Any] = 0 while True: SCREAMING_SNAKE_CASE__ : Optional[Any] = next_term(snake_case_ , 20 , i + dn , snake_case_ ) dn += terms_jumped if dn == n - i: break SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 for j in range(len(snake_case_ ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f'{solution() = }')
702
"""simple docstring""" import os a :List[str] = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1_000} def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 while index < len(__lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE__ : List[Any] = SYMBOLS[numerals[index]] SCREAMING_SNAKE_CASE__ : Dict = 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 _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = """""" SCREAMING_SNAKE_CASE__ : int = num // 1000 numerals += m_count * "M" num %= 1000 SCREAMING_SNAKE_CASE__ : List[str] = 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 SCREAMING_SNAKE_CASE__ : List[Any] = 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 _lowercase ( __lowerCAmelCase = "/p089_roman.txt" ) -> int: SCREAMING_SNAKE_CASE__ : int = 0 with open(os.path.dirname(__lowerCAmelCase ) + roman_numerals_filename ) as filea: SCREAMING_SNAKE_CASE__ : str = filea.readlines() for line in lines: SCREAMING_SNAKE_CASE__ : Union[str, Any] = line.strip() SCREAMING_SNAKE_CASE__ : Dict = parse_roman_numerals(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = generate_roman_numerals(__lowerCAmelCase ) savings += len(__lowerCAmelCase ) - len(__lowerCAmelCase ) return savings if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def _lowercase ( __lowerCAmelCase ) -> Dict: '''simple docstring''' if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("""Undefined for non-integers""" ) elif precision < 1: raise ValueError("""Undefined for non-natural numbers""" ) SCREAMING_SNAKE_CASE__ : Any = precision SCREAMING_SNAKE_CASE__ : List[str] = ceil(precision / 14 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 42_6880 * Decimal(1_0005 ).sqrt() SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : Optional[int] = 1359_1409 SCREAMING_SNAKE_CASE__ : Union[str, Any] = Decimal(_lowerCamelCase ) for k in range(1 , _lowerCamelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = factorial(6 * k ) // (factorial(3 * k ) * factorial(_lowerCamelCase ) ** 3) linear_term += 5_4514_0134 exponential_term *= -26_2537_4126_4076_8000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": a :Optional[Any] = 50 print(f'The first {n} digits of pi is: {pi(n)}')
703
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) SCREAMING_SNAKE_CASE__ : Any = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 25_543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : List[str] = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , _a ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Optional[int] = tf.convert_to_tensor( [[[-0.0_254, 0.0_235, 0.1_027], [0.0_606, -0.1_811, -0.0_418], [-0.1_561, -0.1_127, 0.2_687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
12
0
"""simple docstring""" from collections.abc import Callable def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : float = a SCREAMING_SNAKE_CASE__ : float = b if function(__lowerCAmelCase ) == 0: # one of the a or b is a root for the function return a elif function(__lowerCAmelCase ) == 0: return b elif ( function(__lowerCAmelCase ) * function(__lowerCAmelCase ) > 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__ : float = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(__lowerCAmelCase ) == 0: return mid elif function(__lowerCAmelCase ) * function(__lowerCAmelCase ) < 0: SCREAMING_SNAKE_CASE__ : List[str] = mid else: SCREAMING_SNAKE_CASE__ : Dict = mid SCREAMING_SNAKE_CASE__ : Any = start + (end - start) / 2.0 return mid def _lowercase ( __lowerCAmelCase ) -> List[str]: return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1_000)) import doctest doctest.testmod()
704
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a :List[Any] = logging.get_logger(__name__) a :Optional[int] = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """focalnet""" def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=False , _a=[192, 384, 768, 768] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1E-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1E-5 , _a=32 , _a=None , _a=None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : str = patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = embed_dim SCREAMING_SNAKE_CASE__ : List[str] = use_conv_embed SCREAMING_SNAKE_CASE__ : List[str] = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Any = focal_levels SCREAMING_SNAKE_CASE__ : Optional[Any] = focal_windows SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : str = use_layerscale SCREAMING_SNAKE_CASE__ : int = layerscale_value SCREAMING_SNAKE_CASE__ : Optional[int] = use_post_layernorm SCREAMING_SNAKE_CASE__ : Any = use_post_layernorm_in_modulation SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize_modulator SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = encoder_stride SCREAMING_SNAKE_CASE__ : Optional[int] = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
12
0
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase ) -> Any: create_state_space_tree(snake_case__ , [] , 0 , [0 for i in range(len(snake_case__ ) )] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Optional[Any]: if index == len(snake_case__ ): print(snake_case__ ) return for i in range(len(snake_case__ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = True create_state_space_tree(snake_case__ , snake_case__ , index + 1 , snake_case__ ) current_sequence.pop() SCREAMING_SNAKE_CASE__ : Optional[int] = False a :Optional[int] = [3, 1, 2, 4] generate_all_permutations(sequence) a :Dict = ["A", "B", "C"] generate_all_permutations(sequence_a)
705
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __a (unittest.TestCase): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_attention_mask SCREAMING_SNAKE_CASE__ : Tuple = use_token_type_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = num_choices def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE__ : int = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = True _SCREAMING_SNAKE_CASE :Optional[Any] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerModelTester(self ) @slow def _a ( self ) -> int: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a ) @require_flax class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.array([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ : str = model(_a )[0] SCREAMING_SNAKE_CASE__ : List[Any] = 50_000 SCREAMING_SNAKE_CASE__ : Optional[Any] = (1, 6, vocab_size) self.assertEqual(output.shape , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
12
0
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black a :Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. a :Optional[int] = " \"\"\"\n Output class for the scheduler's step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"\"\"\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n" class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , """schedulers/""" ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.diffusers_dir shutil.copy( os.path.join(__lowerCAmelCase , """src/diffusers/schedulers/scheduling_ddpm.py""" ) , os.path.join(self.diffusers_dir , """schedulers/scheduling_ddpm.py""" ) , ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """src/diffusers""" shutil.rmtree(self.diffusers_dir ) def _a ( self , _a , _a , _a , _a=None ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = comment + f'''\nclass {class_name}(nn.Module):\n''' + class_code if overwrite_result is not None: SCREAMING_SNAKE_CASE__ : Dict = comment + f'''\nclass {class_name}(nn.Module):\n''' + overwrite_result SCREAMING_SNAKE_CASE__ : Union[str, Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) SCREAMING_SNAKE_CASE__ : List[Any] = black.format_str(__lowerCAmelCase , mode=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(self.diffusers_dir , """new_code.py""" ) with open(__lowerCAmelCase , """w""" , newline="""\n""" ) as f: f.write(__lowerCAmelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__lowerCAmelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__lowerCAmelCase ) with open(__lowerCAmelCase , """r""" ) as f: self.assertTrue(f.read() , __lowerCAmelCase ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = check_copies.find_code_in_diffusers("""schedulers.scheduling_ddpm.DDPMSchedulerOutput""" ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def _a ( self ) -> Dict: """simple docstring""" self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , __lowerCAmelCase , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , re.sub("""DDPM""" , """Test""" , __lowerCAmelCase ) , ) # Copy consistency with a really long name SCREAMING_SNAKE_CASE__ : Union[str, Any] = """TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( f'''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}''' , f'''{long_class_name}SchedulerOutput''' , re.sub("""Bert""" , __lowerCAmelCase , __lowerCAmelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , __lowerCAmelCase , overwrite_result=re.sub("""DDPM""" , """Test""" , __lowerCAmelCase ) , )
706
"""simple docstring""" a :List[str] = [ (1_000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1000} SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 while place < len(__lowerCAmelCase ): if (place + 1 < len(__lowerCAmelCase )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = [] for arabic, roman in ROMAN: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : List[str] = divmod(__lowerCAmelCase , __lowerCAmelCase ) result.append(roman * factor ) if number == 0: break return "".join(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL a :List[Any] = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=False , ) -> List[str]: output_path.parent.mkdir(parents=UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( UpperCAmelCase__ , UpperCAmelCase__ , f=output_path.as_posix() , input_names=UpperCAmelCase__ , output_names=UpperCAmelCase__ , dynamic_axes=UpperCAmelCase__ , do_constant_folding=UpperCAmelCase__ , use_external_data_format=UpperCAmelCase__ , enable_onnx_checker=UpperCAmelCase__ , opset_version=UpperCAmelCase__ , ) else: export( UpperCAmelCase__ , UpperCAmelCase__ , f=output_path.as_posix() , input_names=UpperCAmelCase__ , output_names=UpperCAmelCase__ , dynamic_axes=UpperCAmelCase__ , do_constant_folding=UpperCAmelCase__ , opset_version=UpperCAmelCase__ , ) @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): SCREAMING_SNAKE_CASE__ : Tuple = """cuda""" elif fpaa and not torch.cuda.is_available(): raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """cpu""" SCREAMING_SNAKE_CASE__ : List[str] = Path(UpperCAmelCase__ ) # VAE DECODER SCREAMING_SNAKE_CASE__ : Dict = AutoencoderKL.from_pretrained(model_path + """/vae""" ) SCREAMING_SNAKE_CASE__ : Any = vae_decoder.config.latent_channels # forward only through the decoder part SCREAMING_SNAKE_CASE__ : Optional[int] = vae_decoder.decode onnx_export( UpperCAmelCase__ , model_args=( torch.randn(1 , UpperCAmelCase__ , 25 , 25 ).to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ), False, ) , output_path=output_path / """vae_decoder""" / """model.onnx""" , ordered_input_names=["""latent_sample""", """return_dict"""] , output_names=["""sample"""] , dynamic_axes={ """latent_sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, } , opset=UpperCAmelCase__ , ) del vae_decoder if __name__ == "__main__": a :Optional[int] = argparse.ArgumentParser() parser.add_argument( "--model_path", type=str, required=True, help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).", ) parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.") parser.add_argument( "--opset", default=14, type=int, help="The version of the ONNX operator set to use.", ) parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode") a :Dict = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print("SD: Done: ONNX")
707
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a :Any = { "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig", "RobertaPreLayerNormOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Union[str, Any] = [ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[Any] = [ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = [ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
12
0
"""simple docstring""" import math import qiskit def _lowercase ( __lowerCAmelCase = 1 , __lowerCAmelCase = 1 , __lowerCAmelCase = 1 ) -> qiskit.result.counts.Counts: if ( isinstance(_lowercase , _lowercase ) or isinstance(_lowercase , _lowercase ) or isinstance(_lowercase , _lowercase ) ): raise TypeError("""inputs must be integers.""" ) if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError("""inputs must be positive.""" ) if ( (math.floor(_lowercase ) != input_a) or (math.floor(_lowercase ) != input_a) or (math.floor(_lowercase ) != carry_in) ): raise ValueError("""inputs must be exact integers.""" ) if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError("""inputs must be less or equal to 2.""" ) # build registers SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.QuantumRegister(4 , """qr""" ) SCREAMING_SNAKE_CASE__ : Any = qiskit.ClassicalRegister(2 , """cr""" ) # list the entries SCREAMING_SNAKE_CASE__ : List[str] = [input_a, input_a, carry_in] SCREAMING_SNAKE_CASE__ : List[str] = qiskit.QuantumCircuit(_lowercase , _lowercase ) for i in range(0 , 3 ): if entry[i] == 2: quantum_circuit.h(_lowercase ) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(_lowercase ) # for 1 entries elif entry[i] == 0: quantum_circuit.i(_lowercase ) # for 0 entries # build the circuit quantum_circuit.ccx(0 , 1 , 3 ) # ccx = toffoli gate quantum_circuit.cx(0 , 1 ) quantum_circuit.ccx(1 , 2 , 3 ) quantum_circuit.cx(1 , 2 ) quantum_circuit.cx(0 , 1 ) quantum_circuit.measure([2, 3] , _lowercase ) # measure the last two qbits SCREAMING_SNAKE_CASE__ : int = qiskit.Aer.get_backend("""aer_simulator""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(_lowercase , _lowercase , shots=1000 ) return job.result().get_counts(_lowercase ) if __name__ == "__main__": print(f'Total sum count for state is: {quantum_full_adder(1, 1, 1)}')
708
"""simple docstring""" 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 IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : Dict = 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__ : Optional[Any] = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073], """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711], } SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_a , _a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> Any: """simple docstring""" return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **_a ) def _a ( self ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Optional[int] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=_a ) SCREAMING_SNAKE_CASE__ : int = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = AlignProcessor.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 _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[str] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(images=_a , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Any = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(text=_a ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(_a , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = 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 _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.batch_decode(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[str] = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
12
0
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = get_activation("""swish""" ) self.assertIsInstance(__lowerCAmelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = get_activation("""silu""" ) self.assertIsInstance(__lowerCAmelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = get_activation("""mish""" ) self.assertIsInstance(__lowerCAmelCase , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = get_activation("""gelu""" ) self.assertIsInstance(__lowerCAmelCase , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
709
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging a :Optional[Any] = logging.get_logger(__name__) a :Union[str, Any] = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """t5""" _SCREAMING_SNAKE_CASE :List[str] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Any = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self , _a=32_128 , _a=512 , _a=64 , _a=2_048 , _a=6 , _a=None , _a=8 , _a=32 , _a=128 , _a=0.1 , _a=1E-6 , _a=1.0 , _a="relu" , _a=True , _a=True , _a=0 , _a=1 , **_a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = d_model SCREAMING_SNAKE_CASE__ : int = d_kv SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_ff SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_layers SCREAMING_SNAKE_CASE__ : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry SCREAMING_SNAKE_CASE__ : Tuple = num_heads SCREAMING_SNAKE_CASE__ : Dict = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : str = relative_attention_max_distance SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_factor SCREAMING_SNAKE_CASE__ : Tuple = feed_forward_proj SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : List[str] = self.feed_forward_proj.split("""-""" ) SCREAMING_SNAKE_CASE__ : Dict = act_info[-1] SCREAMING_SNAKE_CASE__ : str = act_info[0] == """gated""" if len(_a ) > 1 and act_info[0] != "gated" or len(_a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": SCREAMING_SNAKE_CASE__ : List[Any] = """gelu_new""" super().__init__( pad_token_id=_a , eos_token_id=_a , is_encoder_decoder=_a , **_a , ) class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: SCREAMING_SNAKE_CASE__ : Tuple = """past_encoder_sequence + sequence""" SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch"""} SCREAMING_SNAKE_CASE__ : Tuple = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : str = {0: """batch""", 1: """decoder_sequence"""} SCREAMING_SNAKE_CASE__ : Dict = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_a , direction="""inputs""" ) return common_inputs @property def _a ( self ) -> int: """simple docstring""" return 13
12
0
"""simple docstring""" import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class __a (__UpperCAmelCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""image_processor""", """tokenizer"""] _SCREAMING_SNAKE_CASE :List[str] = """OwlViTImageProcessor""" _SCREAMING_SNAKE_CASE :List[Any] = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self , _a=None , _a=None , **_a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ : Union[str, 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__(UpperCAmelCase_ , UpperCAmelCase_ ) def __call__( self , _a=None , _a=None , _a=None , _a="max_length" , _a="np" , **_a ) -> Dict: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or (isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and not isinstance(text[0] , UpperCAmelCase_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(UpperCAmelCase_ , padding=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ )] elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(text[0] , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE__ : int = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : Optional[Any] = max([len(UpperCAmelCase_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(UpperCAmelCase_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [""" """] * (max_num_queries - len(UpperCAmelCase_ )) SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer(UpperCAmelCase_ , padding=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) encodings.append(UpperCAmelCase_ ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : List[str] = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Any = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : str = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : str = input_ids SCREAMING_SNAKE_CASE__ : Dict = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor( UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ).pixel_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : int = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_ ) , tensor_type=UpperCAmelCase_ ) def _a ( self , *_a , **_a ) -> Any: """simple docstring""" return self.image_processor.post_process(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _a ( self , *_a , **_a ) -> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _a ( self , *_a , **_a ) -> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _a ( self , *_a , **_a ) -> Optional[int]: """simple docstring""" return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _a ( self , *_a , **_a ) -> List[Any]: """simple docstring""" return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) @property def _a ( self ) -> List[str]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , UpperCAmelCase_ , ) return self.image_processor_class @property def _a ( self ) -> str: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , UpperCAmelCase_ , ) return self.image_processor
710
"""simple docstring""" from __future__ import annotations import time import numpy as np a :Optional[Any] = [8, 5, 9, 7] a :List[Any] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] a :int = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class __a : '''simple docstring''' def __init__( self , _a , _a , _a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = claim_vector SCREAMING_SNAKE_CASE__ : Any = allocated_resources_table SCREAMING_SNAKE_CASE__ : Any = maximum_claim_table def _a ( self ) -> list[int]: """simple docstring""" return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def _a ( self ) -> list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def _a ( self ) -> list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(_a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def _a ( self ) -> dict[int, list[int]]: """simple docstring""" return {self.__need().index(_a ): i for i in self.__need()} def _a ( self , **_a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.__need() SCREAMING_SNAKE_CASE__ : Any = self.__allocated_resources_table SCREAMING_SNAKE_CASE__ : Dict = self.__available_resources() SCREAMING_SNAKE_CASE__ : Dict = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 50 + """\n""" ) while need_list: SCREAMING_SNAKE_CASE__ : List[str] = False for each_need in need_list: SCREAMING_SNAKE_CASE__ : Dict = True for index, need in enumerate(_a ): if need > available_resources[index]: SCREAMING_SNAKE_CASE__ : Optional[int] = False break if execution: SCREAMING_SNAKE_CASE__ : Any = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: SCREAMING_SNAKE_CASE__ : Tuple = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(_a ) # update available/freed resources stack SCREAMING_SNAKE_CASE__ : Dict = np.array(_a ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(_a ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def _a ( self ) -> Any: """simple docstring""" print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(_a ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(_a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" from __future__ import annotations class __a : '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = data SCREAMING_SNAKE_CASE__ : Node | None = None SCREAMING_SNAKE_CASE__ : Node | None = None def _lowercase ( __lowerCAmelCase ) -> Any: # In Order traversal of the tree if tree: display(tree.left ) print(tree.data ) display(tree.right ) def _lowercase ( __lowerCAmelCase ) -> Optional[int]: return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def _lowercase ( __lowerCAmelCase ) -> List[str]: if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def _lowercase ( ) -> int: # Main function for testing. SCREAMING_SNAKE_CASE__ : Union[str, Any] = Node(1 ) SCREAMING_SNAKE_CASE__ : List[str] = Node(2 ) SCREAMING_SNAKE_CASE__ : List[str] = Node(3 ) SCREAMING_SNAKE_CASE__ : Optional[int] = Node(4 ) SCREAMING_SNAKE_CASE__ : Tuple = Node(5 ) SCREAMING_SNAKE_CASE__ : Dict = Node(6 ) SCREAMING_SNAKE_CASE__ : Optional[int] = Node(7 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Node(8 ) SCREAMING_SNAKE_CASE__ : List[str] = Node(9 ) print(is_full_binary_tree(_lowercase ) ) print(depth_of_tree(_lowercase ) ) print("""Tree is: """ ) display(_lowercase ) if __name__ == "__main__": main()
711
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: a :List[Any] = None a :Optional[int] = logging.get_logger(__name__) a :Union[str, Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} a :Optional[int] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } a :Dict = { "xlnet-base-cased": None, "xlnet-large-cased": None, } a :int = "▁" # Segments (not really needed) a :Dict = 0 a :Optional[int] = 1 a :Tuple = 2 a :List[str] = 3 a :Optional[Any] = 4 class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = """left""" _SCREAMING_SNAKE_CASE :Optional[Any] = XLNetTokenizer def __init__( self , _a=None , _a=None , _a=False , _a=True , _a=False , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<sep>" , _a="<pad>" , _a="<cls>" , _a="<mask>" , _a=["<eop>", "<eod>"] , **_a , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , additional_special_tokens=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE__ : List[str] = remove_space SCREAMING_SNAKE_CASE__ : int = keep_accents SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_file SCREAMING_SNAKE_CASE__ : Tuple = False if not self.vocab_file else True def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Tuple = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def _lowercase ( __lowerCAmelCase ) -> str: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) a :Any = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.""" , ) train_parser.add_argument("""--model_type""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Model's type.""" ) train_parser.add_argument( """--tf_checkpoint""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""TensorFlow checkpoint path or folder.""" ) train_parser.add_argument( """--pytorch_dump_output""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to the PyTorch saved model output.""" ) train_parser.add_argument("""--config""" , type=_SCREAMING_SNAKE_CASE , default="""""" , help="""Configuration file path or folder.""" ) train_parser.add_argument( """--finetuning_task_name""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help="""Optional fine-tuning task name if the TF model was a finetuned model.""" , ) train_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) def __init__( self , _a , _a , _a , _a , _a , *_a , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger("""transformers-cli/converting""" ) self._logger.info(f'''Loading model {model_type}''' ) SCREAMING_SNAKE_CASE__ : int = model_type SCREAMING_SNAKE_CASE__ : int = tf_checkpoint SCREAMING_SNAKE_CASE__ : Dict = pytorch_dump_output SCREAMING_SNAKE_CASE__ : List[Any] = config SCREAMING_SNAKE_CASE__ : Any = finetuning_task_name def _a ( self ) -> Dict: """simple docstring""" if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_SCREAMING_SNAKE_CASE ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_SCREAMING_SNAKE_CASE ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_SCREAMING_SNAKE_CASE ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_SCREAMING_SNAKE_CASE ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_SCREAMING_SNAKE_CASE ) if "ckpt" in self._tf_checkpoint.lower(): SCREAMING_SNAKE_CASE__ : Tuple = self._tf_checkpoint SCREAMING_SNAKE_CASE__ : Tuple = """""" else: SCREAMING_SNAKE_CASE__ : Tuple = self._tf_checkpoint SCREAMING_SNAKE_CASE__ : Tuple = """""" convert_transfo_xl_checkpoint_to_pytorch( _SCREAMING_SNAKE_CASE , self._config , self._pytorch_dump_output , _SCREAMING_SNAKE_CASE ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_SCREAMING_SNAKE_CASE ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_SCREAMING_SNAKE_CASE ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( """--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]""" )
712
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) + 1 SCREAMING_SNAKE_CASE__ : int = len(__lowerCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. SCREAMING_SNAKE_CASE__ : Dict = [[0 for i in range(__lowerCAmelCase )] for j in range(__lowerCAmelCase )] # since string of zero length match pattern of zero length SCREAMING_SNAKE_CASE__ : Dict = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : int = dp[0][j - 2] if pattern[j - 1] == """*""" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __lowerCAmelCase ): for j in range(1 , __lowerCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": SCREAMING_SNAKE_CASE__ : Any = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: SCREAMING_SNAKE_CASE__ : List[str] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): SCREAMING_SNAKE_CASE__ : List[Any] = dp[i - 1][j] else: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 else: SCREAMING_SNAKE_CASE__ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") a :Any = "aab" a :Optional[Any] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f'{input_string} matches the given pattern {pattern}') else: print(f'{input_string} does not match with the given pattern {pattern}')
12
0
"""simple docstring""" from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
713
"""simple docstring""" from math import sqrt def _lowercase ( __lowerCAmelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowercase ( __lowerCAmelCase = 1_0001 ) -> int: SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = 1 while count != nth and number < 3: number += 1 if is_prime(__lowerCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(__lowerCAmelCase ): count += 1 return number if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() a :Dict = logging.get_logger(__name__) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=False ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''deit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''deit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''deit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''deit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''deit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''deit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''deit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''deit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''deit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''deit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" SCREAMING_SNAKE_CASE__ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=False ) -> str: for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE__ : List[str] = """""" else: SCREAMING_SNAKE_CASE__ : str = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : str = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-config.hidden_size :] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : int = val def _lowercase ( ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ : Dict = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : List[Any] = DeiTConfig() # all deit models have fine-tuned heads SCREAMING_SNAKE_CASE__ : Optional[int] = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size SCREAMING_SNAKE_CASE__ : str = 1000 SCREAMING_SNAKE_CASE__ : Dict = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ : str = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ : Tuple = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = int(deit_name[-6:-4] ) SCREAMING_SNAKE_CASE__ : Any = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): SCREAMING_SNAKE_CASE__ : Tuple = 192 SCREAMING_SNAKE_CASE__ : int = 768 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 12 SCREAMING_SNAKE_CASE__ : int = 3 elif deit_name[9:].startswith("""small""" ): SCREAMING_SNAKE_CASE__ : List[Any] = 384 SCREAMING_SNAKE_CASE__ : Any = 1536 SCREAMING_SNAKE_CASE__ : Optional[int] = 12 SCREAMING_SNAKE_CASE__ : Any = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): SCREAMING_SNAKE_CASE__ : int = 1024 SCREAMING_SNAKE_CASE__ : Optional[int] = 4096 SCREAMING_SNAKE_CASE__ : List[Any] = 24 SCREAMING_SNAKE_CASE__ : List[Any] = 16 # load original model from timm SCREAMING_SNAKE_CASE__ : List[Any] = timm.create_model(SCREAMING_SNAKE_CASE_ , pretrained=SCREAMING_SNAKE_CASE_ ) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Dict = timm_model.state_dict() SCREAMING_SNAKE_CASE__ : Dict = create_rename_keys(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) read_in_q_k_v(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load HuggingFace model SCREAMING_SNAKE_CASE__ : Optional[int] = DeiTForImageClassificationWithTeacher(SCREAMING_SNAKE_CASE_ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by DeiTImageProcessor SCREAMING_SNAKE_CASE__ : Optional[int] = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 SCREAMING_SNAKE_CASE__ : int = DeiTImageProcessor(size=SCREAMING_SNAKE_CASE_ , crop_size=config.image_size ) SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(images=prepare_img() , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = encoding["""pixel_values"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : List[Any] = timm_model(SCREAMING_SNAKE_CASE_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(SCREAMING_SNAKE_CASE_ , outputs.logits , atol=1E-3 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(F'''Saving model {deit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": a :str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--deit_name", default="vit_deit_base_distilled_patch16_224", type=str, help="Name of the DeiT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) a :List[str] = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
714
"""simple docstring""" class __a : '''simple docstring''' def __init__( self , _a , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = name SCREAMING_SNAKE_CASE__ : Optional[Any] = value SCREAMING_SNAKE_CASE__ : List[Any] = weight def __repr__( self ) -> List[Any]: """simple docstring""" return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def _a ( self ) -> Dict: """simple docstring""" return self.value def _a ( self ) -> int: """simple docstring""" return self.name def _a ( self ) -> Optional[Any]: """simple docstring""" return self.weight def _a ( self ) -> Dict: """simple docstring""" return self.value / self.weight def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict: SCREAMING_SNAKE_CASE__ : Any = [] for i in range(len(__lowerCAmelCase ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = sorted(__lowerCAmelCase , key=__lowerCAmelCase , reverse=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 0.0, 0.0 for i in range(len(__lowerCAmelCase ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def _lowercase ( ) -> List[str]: pass if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" import math def _lowercase ( __lowerCAmelCase ) -> int: if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = F'''Input value of [number={number}] must be an integer''' raise TypeError(_lowerCAmelCase ) if number < 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = F'''Input value of [number={number}] must be > 0''' raise ValueError(_lowerCAmelCase ) elif number == 1: return 3 elif number == 2: return 5 else: SCREAMING_SNAKE_CASE__ : List[Any] = int(math.log(number // 3 , 2 ) ) + 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = [3, 5] SCREAMING_SNAKE_CASE__ : Optional[int] = 2 SCREAMING_SNAKE_CASE__ : int = 3 for block in range(1 , _lowerCAmelCase ): for _ in range(_lowerCAmelCase ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): a :List[str] = 0 try: a :Optional[Any] = proth(number) except ValueError: print(f'ValueError: there is no {number}th Proth number') continue print(f'The {number}th Proth number: {value}')
715
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: a :Optional[int] = None a :Optional[Any] = logging.get_logger(__name__) a :Optional[Any] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} a :Union[str, Any] = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } a :Any = { "facebook/nllb-large-en-ro": 1_024, "facebook/nllb-200-distilled-600M": 1_024, } # fmt: off a :Tuple = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :int = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE :Tuple = NllbTokenizer _SCREAMING_SNAKE_CASE :List[int] = [] _SCREAMING_SNAKE_CASE :List[int] = [] def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , _a=False , **_a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token SCREAMING_SNAKE_CASE__ : Optional[int] = legacy_behaviour super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , legacy_behaviour=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_file SCREAMING_SNAKE_CASE__ : str = False if not self.vocab_file else True SCREAMING_SNAKE_CASE__ : Dict = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens} ) SCREAMING_SNAKE_CASE__ : List[str] = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE__ : Dict = src_lang if src_lang is not None else """eng_Latn""" SCREAMING_SNAKE_CASE__ : List[str] = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE__ : Dict = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _a ( self ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _a ( self , _a , _a , _a , _a , **_a ) -> Tuple: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ : Dict = src_lang SCREAMING_SNAKE_CASE__ : Dict = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_tokens_to_ids(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tgt_lang_id return inputs def _a ( self , _a , _a = "eng_Latn" , _a = None , _a = "fra_Latn" , **_a , ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = src_lang SCREAMING_SNAKE_CASE__ : Dict = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _a ( self ) -> str: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Dict = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : int = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : int = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.eos_token_id] SCREAMING_SNAKE_CASE__ : Any = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return SCREAMING_SNAKE_CASE__ : Dict = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" import os def _lowercase ( __lowerCAmelCase = "input.txt" ) -> Union[str, Any]: with open(os.path.join(os.path.dirname(__lowerCAmelCase ) , __lowerCAmelCase ) ) as input_file: SCREAMING_SNAKE_CASE__ : int = [ [int(__lowerCAmelCase ) for element in line.split(""",""" )] for line in input_file.readlines() ] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = len(matrix[0] ) SCREAMING_SNAKE_CASE__ : int = [[-1 for _ in range(__lowerCAmelCase )] for _ in range(__lowerCAmelCase )] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = matrix[i][0] for j in range(1 , __lowerCAmelCase ): for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Tuple = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): SCREAMING_SNAKE_CASE__ : int = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(f'{solution() = }')
716
"""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 _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Any: # Format the message. if name is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None else: SCREAMING_SNAKE_CASE__ : str = """.""" * max(0 , spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" SCREAMING_SNAKE_CASE__ : Dict = fmt.format(__lowerCAmelCase ) # Print and recurse (if needed). if isinstance(__lowerCAmelCase , __lowerCAmelCase ): if msg is not None: print(__lowerCAmelCase ) for k in val.keys(): recursive_print(__lowerCAmelCase , val[k] , spaces + 2 ) elif isinstance(__lowerCAmelCase , torch.Tensor ): print(__lowerCAmelCase , """:""" , val.size() ) else: print(__lowerCAmelCase , """:""" , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[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. SCREAMING_SNAKE_CASE__ : Tuple = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] SCREAMING_SNAKE_CASE__ : int = (num_heads, hidden_size, num_splits) + input_shape[1:] SCREAMING_SNAKE_CASE__ : List[str] = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = param.transpose(0 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] SCREAMING_SNAKE_CASE__ : List[str] = (num_heads, num_splits, hidden_size) + input_shape[1:] SCREAMING_SNAKE_CASE__ : Dict = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = param.transpose(0 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ : Any = param.view(*__lowerCAmelCase ) return param def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: # The converted output model. SCREAMING_SNAKE_CASE__ : List[str] = {} # old versions did not store training args SCREAMING_SNAKE_CASE__ : List[str] = input_state_dict.get("""args""" , __lowerCAmelCase ) 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)) SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.padded_vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = ds_args.max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = ds_args.num_layers SCREAMING_SNAKE_CASE__ : Dict = ds_args.num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = ds_args.ffn_hidden_size # pprint(config) # The number of heads. SCREAMING_SNAKE_CASE__ : List[str] = config.n_head # The hidden_size per head. SCREAMING_SNAKE_CASE__ : str = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_state_dict["""checkpoint_version"""] else: SCREAMING_SNAKE_CASE__ : Tuple = 0.0 # The model. SCREAMING_SNAKE_CASE__ : Any = input_state_dict["""model"""] # The language model. SCREAMING_SNAKE_CASE__ : Any = model["""language_model"""] # The embeddings. SCREAMING_SNAKE_CASE__ : str = lm["""embedding"""] # The word embeddings. SCREAMING_SNAKE_CASE__ : int = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. SCREAMING_SNAKE_CASE__ : Any = word_embeddings[: config.vocab_size, :] SCREAMING_SNAKE_CASE__ : Optional[int] = word_embeddings # The position embeddings. SCREAMING_SNAKE_CASE__ : Any = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] SCREAMING_SNAKE_CASE__ : Tuple = 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. SCREAMING_SNAKE_CASE__ : List[Any] = pos_embeddings # The transformer. SCREAMING_SNAKE_CASE__ : Union[str, Any] = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. SCREAMING_SNAKE_CASE__ : str = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. SCREAMING_SNAKE_CASE__ : Optional[int] = { """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. SCREAMING_SNAKE_CASE__ : str = layer_re.match(__lowerCAmelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. SCREAMING_SNAKE_CASE__ : Dict = int(m.group(1 ) ) # The name of the operation. SCREAMING_SNAKE_CASE__ : Optional[Any] = m.group(2 ) # Is it a weight or a bias? SCREAMING_SNAKE_CASE__ : str = m.group(3 ) # The name of the layer. SCREAMING_SNAKE_CASE__ : List[Any] = F'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): SCREAMING_SNAKE_CASE__ : Dict = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" SCREAMING_SNAKE_CASE__ : List[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. SCREAMING_SNAKE_CASE__ : Any = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = causal_mask # Insert a "dummy" tensor for masked_bias. SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor(-1E4 , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = masked_bias SCREAMING_SNAKE_CASE__ : List[str] = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. SCREAMING_SNAKE_CASE__ : str = out_val.transpose(0 , 1 ).contiguous() # Store. SCREAMING_SNAKE_CASE__ : Dict = 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": SCREAMING_SNAKE_CASE__ : Any = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Store. No change of shape. SCREAMING_SNAKE_CASE__ : str = out_val # Transpose the weights. elif weight_or_bias == "weight": SCREAMING_SNAKE_CASE__ : str = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : int = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": SCREAMING_SNAKE_CASE__ : int = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : Dict = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. SCREAMING_SNAKE_CASE__ : Union[str, Any] = transformer["""final_layernorm.weight"""] SCREAMING_SNAKE_CASE__ : str = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. SCREAMING_SNAKE_CASE__ : Tuple = word_embeddings # It should be done! return output_state_dict def _lowercase ( ) -> List[Any]: # Create the argument parser. SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""" , action="""store_true""" ) parser.add_argument( """path_to_checkpoint""" , type=__lowerCAmelCase , help="""Path to the checkpoint file (.zip archive or direct .pt file)""" , ) parser.add_argument( """--config_file""" , default="""""" , type=__lowerCAmelCase , help="""An optional config json file describing the pre-trained model.""" , ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() # Extract the basename. SCREAMING_SNAKE_CASE__ : Optional[int] = 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: SCREAMING_SNAKE_CASE__ : List[Any] = torch.load(__lowerCAmelCase , map_location="""cpu""" ) else: SCREAMING_SNAKE_CASE__ : str = torch.load(args.path_to_checkpoint , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : int = input_state_dict.get("""args""" , __lowerCAmelCase ) # 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: SCREAMING_SNAKE_CASE__ : Dict = """gelu_fast""" elif ds_args.openai_gelu: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu_new""" else: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" SCREAMING_SNAKE_CASE__ : Any = """gelu_new""" # Spell out all parameters in case the defaults change. SCREAMING_SNAKE_CASE__ : Union[str, Any] = GPTaConfig( vocab_size=5_0257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=__lowerCAmelCase , 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=__lowerCAmelCase , summary_activation=__lowerCAmelCase , summary_proj_to_labels=__lowerCAmelCase , summary_first_dropout=0.1 , scale_attn_weights=__lowerCAmelCase , use_cache=__lowerCAmelCase , bos_token_id=5_0256 , eos_token_id=5_0256 , ) else: SCREAMING_SNAKE_CASE__ : List[Any] = GPTaConfig.from_json_file(args.config_file ) SCREAMING_SNAKE_CASE__ : Tuple = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = convert_megatron_checkpoint(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(__lowerCAmelCase , __lowerCAmelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: SCREAMING_SNAKE_CASE__ : Tuple = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": SCREAMING_SNAKE_CASE__ : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": SCREAMING_SNAKE_CASE__ : Any = ds_args.tokenizer_name_or_path else: raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """gpt2""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = type(__lowerCAmelCase ).__name__ SCREAMING_SNAKE_CASE__ : Dict = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(__lowerCAmelCase ) # Save tokenizer based on args print(F'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(__lowerCAmelCase ) # Store the state_dict to file. SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , """pytorch_model.bin""" ) print(F'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
12
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin a :List[Any] = random.Random() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=1.0 , __lowerCAmelCase=None , __lowerCAmelCase=None ) -> List[str]: if rng is None: SCREAMING_SNAKE_CASE__ : List[str] = global_rng SCREAMING_SNAKE_CASE__ : Tuple = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class __a (unittest.TestCase): '''simple docstring''' def __init__( self , _a , _a=7 , _a=400 , _a=2_000 , _a=1 , _a=0.0 , _a=16_000 , _a=True , _a=True , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : List[str] = batch_size SCREAMING_SNAKE_CASE__ : Dict = min_seq_length SCREAMING_SNAKE_CASE__ : int = max_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : List[Any] = feature_size SCREAMING_SNAKE_CASE__ : int = padding_value SCREAMING_SNAKE_CASE__ : str = sampling_rate SCREAMING_SNAKE_CASE__ : List[str] = return_attention_mask SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_normalize def _a ( self ) -> List[Any]: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _a ( self , _a=False , _a=False ) -> Optional[int]: """simple docstring""" def _flatten(_a ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Any = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : List[str] = [ _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: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs class __a (UpperCAmelCase__ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = WavaVecaFeatureExtractor def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = WavaVecaFeatureExtractionTester(self ) def _a ( self , _a ) -> Tuple: """simple docstring""" self.assertTrue(np.all(np.mean(lowerCamelCase__ , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowerCamelCase__ , axis=0 ) - 1 ) < 1E-3 ) ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : str = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Dict = feat_extract(lowerCamelCase__ , return_tensors="""np""" ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract(lowerCamelCase__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[Any] = np.asarray(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(lowerCamelCase__ , return_tensors="""np""" ).input_values SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(lowerCamelCase__ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertTrue(np.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-3 ) ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = ["longest", "max_length", "do_not_pad"] SCREAMING_SNAKE_CASE__ : int = [None, 1_600, None] for max_length, padding in zip(lowerCamelCase__ , lowerCamelCase__ ): SCREAMING_SNAKE_CASE__ : Any = feat_extract(lowerCamelCase__ , padding=lowerCamelCase__ , max_length=lowerCamelCase__ , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_000] ) self.assertTrue(input_values[0][1_000:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_200] ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : int = range(800 , 1_400 , 200 ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : List[str] = ["longest", "max_length", "do_not_pad"] SCREAMING_SNAKE_CASE__ : List[Any] = [None, 1_600, None] for max_length, padding in zip(lowerCamelCase__ , lowerCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract(lowerCamelCase__ , max_length=lowerCamelCase__ , padding=lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : str = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1_000] ) self._check_zero_mean_unit_variance(input_values[2][:1_200] ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract( lowerCamelCase__ , truncation=lowerCamelCase__ , max_length=1_000 , padding="""max_length""" , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( lowerCamelCase__ , truncation=lowerCamelCase__ , max_length=1_000 , padding="""longest""" , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1_000] ) 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_000) ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = feat_extract( lowerCamelCase__ , truncation=lowerCamelCase__ , max_length=2_000 , padding="""longest""" , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1_000] ) 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_200) ) @require_torch def _a ( self ) -> Optional[Any]: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : int = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def _a ( self ) -> Dict: """simple docstring""" for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: SCREAMING_SNAKE_CASE__ : List[Any] = WavaVecaConfig.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase__ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == """layer""" )
717
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class __a (UpperCamelCase_): '''simple docstring''' def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" with open(_a , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ : str = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = input_file.read() SCREAMING_SNAKE_CASE__ : str = regexp.search(_a ) return match def _a ( self , _a ) -> Optional[Any]: """simple docstring""" with open(_a , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ : Tuple = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) SCREAMING_SNAKE_CASE__ : List[Any] = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE__ : Dict = regexp.finditer(_a ) SCREAMING_SNAKE_CASE__ : int = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_a ) ): raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ : List[str] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(_a ) ): raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
12
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer a :Union[str, Any] = logging.get_logger(__name__) a :Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} a :List[str] = { "vocab_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json" ), }, } a :List[str] = { "yjernite/retribert-base-uncased": 512, } a :List[str] = { "yjernite/retribert-base-uncased": {"do_lower_case": True}, } class __a (__a): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :int = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE :Dict = RetriBertTokenizer _SCREAMING_SNAKE_CASE :str = ["input_ids", "attention_mask"] def __init__( self , _a=None , _a=None , _a=True , _a="[UNK]" , _a="[SEP]" , _a="[PAD]" , _a="[CLS]" , _a="[MASK]" , _a=True , _a=None , **_a , ) -> List[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_ , ) SCREAMING_SNAKE_CASE__ : List[str] = 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 ): SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(lowerCAmelCase_ , normalizer_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ : Tuple = do_lower_case SCREAMING_SNAKE_CASE__ : Any = strip_accents SCREAMING_SNAKE_CASE__ : Optional[int] = tokenize_chinese_chars SCREAMING_SNAKE_CASE__ : str = normalizer_class(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_lower_case def _a ( self , _a , _a=None ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self._tokenizer.model.save(lowerCAmelCase_ , name=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ )
718
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class __a : '''simple docstring''' def __init__( self , _a , _a=99 , _a=13 , _a=7 , _a=9 , _a=True , _a=True , _a=False , _a=32 , _a=5 , _a=4 , _a=37 , _a=8 , _a=0.1 , _a=0.002 , _a=1 , _a=0 , _a=0 , _a=None , _a=None , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Tuple = encoder_seq_length SCREAMING_SNAKE_CASE__ : str = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE__ : Optional[int] = self.decoder_seq_length SCREAMING_SNAKE_CASE__ : Tuple = is_training SCREAMING_SNAKE_CASE__ : Dict = use_attention_mask SCREAMING_SNAKE_CASE__ : List[str] = use_labels SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = d_ff SCREAMING_SNAKE_CASE__ : Any = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor SCREAMING_SNAKE_CASE__ : List[Any] = eos_token_id SCREAMING_SNAKE_CASE__ : List[str] = pad_token_id SCREAMING_SNAKE_CASE__ : Any = decoder_start_token_id SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : str = decoder_layers def _a ( self ) -> Tuple: """simple docstring""" return TaConfig.from_pretrained("""google/umt5-base""" ) def _a ( self , _a , _a , _a , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> Any: """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : int = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE__ : str = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_a ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_a ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=_a ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input SCREAMING_SNAKE_CASE__ : Tuple = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config() SCREAMING_SNAKE_CASE__ : List[str] = config.num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_inputs_dict(_a , _a , _a ) return config, input_dict def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() return config, inputs_dict def _a ( self ) -> List[str]: """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self ) -> List[Any]: """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = UMTaModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model( input_ids=_a , decoder_input_ids=_a , attention_mask=_a , decoder_attention_mask=_a , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=_a , decoder_input_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = result.last_hidden_state SCREAMING_SNAKE_CASE__ : Dict = result.past_key_values SCREAMING_SNAKE_CASE__ : Any = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(_a ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).get_decoder().to(_a ).eval() # first forward pass SCREAMING_SNAKE_CASE__ : str = model(_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , use_cache=_a ) self.parent.assertTrue(len(_a ) == len(_a ) ) self.parent.assertTrue(len(_a ) == len(_a ) + 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : Tuple = model(_a , past_key_values=_a )["""last_hidden_state"""] # select random slice SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) ) def _a ( self , _a , _a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).to(_a ).half().eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**_a )["""last_hidden_state"""] self.parent.assertFalse(torch.isnan(_a ).any().item() ) @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :List[str] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Union[str, Any] = True _SCREAMING_SNAKE_CASE :Tuple = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = True _SCREAMING_SNAKE_CASE :List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _SCREAMING_SNAKE_CASE :Union[str, Any] = [0.8, 0.9] def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = UMTaModelTester(self ) @unittest.skip("""Test has a segmentation fault on torch 1.8.0""" ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = UMTaModel(config_and_inputs[0] ).to(_a ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( _a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=_a , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*_a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""] SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs[0] SCREAMING_SNAKE_CASE__ : Tuple = UMTaForConditionalGeneration(_a ).eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = { """head_mask""": torch.zeros(config.num_layers , config.num_heads , device=_a ), """decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), } for attn_name, (name, mask) in zip(_a , head_masking.items() ): SCREAMING_SNAKE_CASE__ : List[str] = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": SCREAMING_SNAKE_CASE__ : str = torch.ones( config.num_decoder_layers , config.num_heads , device=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.generate( config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=_a , return_dict_in_generate=_a , **_a , ) # We check the state of decoder_attentions and cross_attentions just from the last step SCREAMING_SNAKE_CASE__ : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" ) def _a ( self ) -> Dict: """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow @unittest.skip( """Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=_a ).to(_a ) SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=_a , legacy=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ """Bonjour monsieur <extra_id_0> bien <extra_id_1>.""", """No se como puedo <extra_id_0>.""", """This is the reason why we <extra_id_0> them.""", """The <extra_id_0> walks in <extra_id_1>, seats""", """A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""", ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_a , return_tensors="""pt""" , padding=_a ).input_ids # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(_a , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids.to(_a ) ) SCREAMING_SNAKE_CASE__ : int = [ """<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""", """<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", ] SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.batch_decode(_a ) self.assertEqual(_a , _a )
12
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=__lowercase) class __a (__lowercase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = field(default="""text-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True}) _SCREAMING_SNAKE_CASE :ClassVar[Features] = Features({"""text""": Value("""string""")}) _SCREAMING_SNAKE_CASE :ClassVar[Features] = Features({"""labels""": ClassLabel}) _SCREAMING_SNAKE_CASE :str = "text" _SCREAMING_SNAKE_CASE :str = "labels" def _a ( self , _a ) -> Dict: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __a ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ : Dict = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ : str = self.label_schema.copy() SCREAMING_SNAKE_CASE__ : Tuple = features[self.label_column] SCREAMING_SNAKE_CASE__ : int = label_schema return task_template @property def _a ( self ) -> Dict[str, str]: """simple docstring""" return { self.text_column: "text", self.label_column: "labels", }
719
"""simple docstring""" import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a , _a = None , _a = None , _a = False , **_a , ) -> Union[str, Any]: """simple docstring""" super().__init__(features=_a , cache_dir=_a , keep_in_memory=_a , **_a ) SCREAMING_SNAKE_CASE__ : List[Any] = Sql( cache_dir=_a , features=_a , sql=_a , con=_a , **_a , ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None self.builder.download_and_prepare( download_config=_a , download_mode=_a , verification_mode=_a , base_path=_a , ) # Build dataset for splits SCREAMING_SNAKE_CASE__ : str = self.builder.as_dataset( split="""train""" , verification_mode=_a , in_memory=self.keep_in_memory ) return dataset class __a : '''simple docstring''' def __init__( self , _a , _a , _a , _a = None , _a = None , **_a , ) -> Any: """simple docstring""" if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) SCREAMING_SNAKE_CASE__ : int = dataset SCREAMING_SNAKE_CASE__ : Any = name SCREAMING_SNAKE_CASE__ : Optional[Any] = con SCREAMING_SNAKE_CASE__ : List[Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE SCREAMING_SNAKE_CASE__ : int = num_proc SCREAMING_SNAKE_CASE__ : int = to_sql_kwargs def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.to_sql_kwargs.pop("""sql""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = self.to_sql_kwargs.pop("""con""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = self.to_sql_kwargs.pop("""index""" , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._write(index=_a , **self.to_sql_kwargs ) return written def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = args SCREAMING_SNAKE_CASE__ : List[str] = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs SCREAMING_SNAKE_CASE__ : Any = query_table( table=self.dataset.data , key=slice(_a , offset + self.batch_size ) , indices=self.dataset._indices , ) SCREAMING_SNAKE_CASE__ : Optional[int] = batch.to_pandas() SCREAMING_SNAKE_CASE__ : List[Any] = df.to_sql(self.name , self.con , index=_a , **_a ) return num_rows or len(_a ) def _a ( self , _a , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _a , _a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
12
0
"""simple docstring""" from collections import deque from .hash_table import HashTable class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def _a ( self , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ : int = self.values[key] def _a ( self ) -> Tuple: """simple docstring""" return ( sum(self.charge_factor - len(UpperCAmelCase__ ) for slot in self.values ) / self.size_table * self.charge_factor ) def _a ( self , _a , _a=None ) -> List[Any]: """simple docstring""" if not ( len(self.values[key] ) == self.charge_factor and self.values.count(UpperCAmelCase__ ) == 0 ): return key return super()._collision_resolution(UpperCAmelCase__ , UpperCAmelCase__ )
720
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : int = 1 while repunit: SCREAMING_SNAKE_CASE__ : str = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def _lowercase ( __lowerCAmelCase = 100_0000 ) -> int: SCREAMING_SNAKE_CASE__ : Dict = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(__lowerCAmelCase ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast a :Optional[Any] = datasets.utils.logging.get_logger(__name__) @dataclass class __a (datasets.BuilderConfig): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = 1_00_00 _SCREAMING_SNAKE_CASE :Optional[Any] = None _SCREAMING_SNAKE_CASE :Any = None class __a (datasets.ArrowBasedBuilder): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = ParquetConfig def _a ( self ) -> Tuple: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def _a ( self , _a ) -> str: """simple docstring""" if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(A__ , (str, list, tuple) ): SCREAMING_SNAKE_CASE__ : Tuple = data_files if isinstance(A__ , A__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive SCREAMING_SNAKE_CASE__ : Dict = [dl_manager.iter_files(A__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] SCREAMING_SNAKE_CASE__ : List[Any] = [] for split_name, files in data_files.items(): if isinstance(A__ , A__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive SCREAMING_SNAKE_CASE__ : Any = [dl_manager.iter_files(A__ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(A__ ): with open(A__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ : List[Any] = datasets.Features.from_arrow_schema(pq.read_schema(A__ ) ) break splits.append(datasets.SplitGenerator(name=A__ , gen_kwargs={"""files""": files} ) ) return splits def _a ( self , _a ) -> pa.Table: """simple docstring""" if self.info.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 SCREAMING_SNAKE_CASE__ : int = table_cast(A__ , self.info.features.arrow_schema ) return pa_table def _a ( self , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( f'''Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'''' ) for file_idx, file in enumerate(itertools.chain.from_iterable(A__ ) ): with open(A__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ : List[Any] = pq.ParquetFile(A__ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): SCREAMING_SNAKE_CASE__ : str = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f'''{file_idx}_{batch_idx}''', self._cast_table(A__ ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(A__ )}: {e}''' ) raise
721
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") a :Union[str, Any] = logging.getLogger(__name__) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of prediction examples to this """ """value if set.""" ) } , ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}) _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Train language if it is different from the evaluation language."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) _SCREAMING_SNAKE_CASE :Optional[bool] = field( default=UpperCamelCase_ , metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) _SCREAMING_SNAKE_CASE :str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def _lowercase ( ) -> Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE__ : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_xnli""" , __lowerCAmelCase ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : List[Any] = training_args.get_process_log_level() logger.setLevel(__lowerCAmelCase ) datasets.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__ : Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__ : Optional[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: SCREAMING_SNAKE_CASE__ : Optional[int] = load_dataset( """xnli""" , model_args.language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: SCREAMING_SNAKE_CASE__ : str = load_dataset( """xnli""" , model_args.train_language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = train_dataset.features["""label"""].names if training_args.do_eval: SCREAMING_SNAKE_CASE__ : int = load_dataset( """xnli""" , model_args.language , split="""validation""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.features["""label"""].names if training_args.do_predict: SCREAMING_SNAKE_CASE__ : int = load_dataset( """xnli""" , model_args.language , split="""test""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Tuple = predict_dataset.features["""label"""].names # Labels SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__lowerCAmelCase , idalabel={str(__lowerCAmelCase ): label for i, label in enumerate(__lowerCAmelCase )} , labelaid={label: i for i, label in enumerate(__lowerCAmelCase )} , finetuning_task="""xnli""" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : str = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : str = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch SCREAMING_SNAKE_CASE__ : Optional[Any] = False def preprocess_function(__lowerCAmelCase ): # Tokenize the texts return tokenizer( examples["""premise"""] , examples["""hypothesis"""] , padding=__lowerCAmelCase , max_length=data_args.max_seq_length , truncation=__lowerCAmelCase , ) if training_args.do_train: if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(len(__lowerCAmelCase ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE__ : str = train_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : List[str] = train_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on train dataset""" , ) # Log a few random samples from the training set: for index in random.sample(range(len(__lowerCAmelCase ) ) , 3 ): logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.''' ) if training_args.do_eval: if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__ : Any = min(len(__lowerCAmelCase ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : List[str] = eval_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on validation dataset""" , ) if training_args.do_predict: if data_args.max_predict_samples is not None: SCREAMING_SNAKE_CASE__ : int = min(len(__lowerCAmelCase ) , data_args.max_predict_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = predict_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""prediction dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : Tuple = predict_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on prediction dataset""" , ) # Get the metric function SCREAMING_SNAKE_CASE__ : Optional[Any] = evaluate.load("""xnli""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Dict = p.predictions[0] if isinstance(p.predictions , __lowerCAmelCase ) else p.predictions SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.argmax(__lowerCAmelCase , axis=1 ) return metric.compute(predictions=__lowerCAmelCase , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : List[Any] = default_data_collator elif training_args.fpaa: SCREAMING_SNAKE_CASE__ : int = DataCollatorWithPadding(__lowerCAmelCase , pad_to_multiple_of=8 ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # Initialize our Trainer SCREAMING_SNAKE_CASE__ : Union[str, Any] = Trainer( model=__lowerCAmelCase , args=__lowerCAmelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , data_collator=__lowerCAmelCase , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__ : Dict = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = last_checkpoint SCREAMING_SNAKE_CASE__ : str = trainer.train(resume_from_checkpoint=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = train_result.metrics SCREAMING_SNAKE_CASE__ : Optional[int] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Dict = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , __lowerCAmelCase ) trainer.save_metrics("""train""" , __lowerCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE__ : Any = trainer.evaluate(eval_dataset=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""eval""" , __lowerCAmelCase ) trainer.save_metrics("""eval""" , __lowerCAmelCase ) # Prediction if training_args.do_predict: logger.info("""*** Predict ***""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = trainer.predict(__lowerCAmelCase , metric_key_prefix="""predict""" ) SCREAMING_SNAKE_CASE__ : List[str] = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : int = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""predict""" , __lowerCAmelCase ) trainer.save_metrics("""predict""" , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = np.argmax(__lowerCAmelCase , axis=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(training_args.output_dir , """predictions.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCAmelCase , """w""" ) as writer: writer.write("""index\tprediction\n""" ) for index, item in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = label_list[item] writer.write(F'''{index}\t{item}\n''' ) if __name__ == "__main__": main()
12
0
"""simple docstring""" from random import shuffle import tensorflow as tf from numpy import array def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : Any = int(_SCREAMING_SNAKE_CASE ) assert noofclusters < len(_SCREAMING_SNAKE_CASE ) # Find out the dimensionality SCREAMING_SNAKE_CASE__ : Optional[int] = len(vectors[0] ) # Will help select random centroids from among the available vectors SCREAMING_SNAKE_CASE__ : Optional[int] = list(range(len(_SCREAMING_SNAKE_CASE ) ) ) shuffle(_SCREAMING_SNAKE_CASE ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION SCREAMING_SNAKE_CASE__ : Optional[int] = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points SCREAMING_SNAKE_CASE__ : List[Any] = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(_SCREAMING_SNAKE_CASE ) ] ##These nodes will assign the centroid Variables the appropriate ##values SCREAMING_SNAKE_CASE__ : List[Any] = tf.placeholder("""float64""" , [dim] ) SCREAMING_SNAKE_CASE__ : int = [] for centroid in centroids: cent_assigns.append(tf.assign(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) SCREAMING_SNAKE_CASE__ : str = [tf.Variable(0 ) for i in range(len(_SCREAMING_SNAKE_CASE ) )] ##These nodes will assign an assignment Variable the appropriate ##value SCREAMING_SNAKE_CASE__ : Tuple = tf.placeholder("""int32""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for assignment in assignments: cluster_assigns.append(tf.assign(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input SCREAMING_SNAKE_CASE__ : Tuple = tf.placeholder("""float""" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors SCREAMING_SNAKE_CASE__ : Any = tf.reduce_mean(_SCREAMING_SNAKE_CASE , 0 ) ##Node for computing Euclidean distances # Placeholders for input SCREAMING_SNAKE_CASE__ : List[Any] = tf.placeholder("""float""" , [dim] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.placeholder("""float""" , [dim] ) SCREAMING_SNAKE_CASE__ : Tuple = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input SCREAMING_SNAKE_CASE__ : int = tf.placeholder("""float""" , [noofclusters] ) SCREAMING_SNAKE_CASE__ : List[str] = tf.argmin(_SCREAMING_SNAKE_CASE , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. SCREAMING_SNAKE_CASE__ : str = tf.initialize_all_variables() # Initialize all variables sess.run(_SCREAMING_SNAKE_CASE ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. SCREAMING_SNAKE_CASE__ : Union[str, Any] = 100 for _ in range(_SCREAMING_SNAKE_CASE ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(_SCREAMING_SNAKE_CASE ) ): SCREAMING_SNAKE_CASE__ : List[Any] = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. SCREAMING_SNAKE_CASE__ : List[str] = [ sess.run(_SCREAMING_SNAKE_CASE , feed_dict={va: vect, va: sess.run(_SCREAMING_SNAKE_CASE )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input SCREAMING_SNAKE_CASE__ : Tuple = sess.run( _SCREAMING_SNAKE_CASE , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(_SCREAMING_SNAKE_CASE ): # Collect all the vectors assigned to this cluster SCREAMING_SNAKE_CASE__ : Dict = [ vectors[i] for i in range(len(_SCREAMING_SNAKE_CASE ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location SCREAMING_SNAKE_CASE__ : Union[str, Any] = sess.run( _SCREAMING_SNAKE_CASE , feed_dict={mean_input: array(_SCREAMING_SNAKE_CASE )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments SCREAMING_SNAKE_CASE__ : Optional[Any] = sess.run(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE__ : Any = sess.run(_SCREAMING_SNAKE_CASE ) return centroids, assignments
700
"""simple docstring""" # Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() a :str = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model a :int = { # fairseq: "wmt19-ru-en": {"length_penalty": 1.1}, "wmt19-en-ru": {"length_penalty": 1.15}, "wmt19-en-de": {"length_penalty": 1.0}, "wmt19-de-en": {"length_penalty": 1.1}, # allenai: "wmt16-en-de-dist-12-1": {"length_penalty": 0.6}, "wmt16-en-de-dist-6-1": {"length_penalty": 0.6}, "wmt16-en-de-12-1": {"length_penalty": 0.8}, "wmt19-de-en-6-6-base": {"length_penalty": 0.6}, "wmt19-de-en-6-6-big": {"length_penalty": 0.6}, } # this remaps the different models to their organization names a :Dict = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: a :List[Any] = "facebook" for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: a :str = "allenai" def _lowercase ( __lowerCAmelCase ) -> Any: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} SCREAMING_SNAKE_CASE__ : str = dict((re.sub(r"""@@$""" , """""" , __lowerCAmelCase ), v) if k.endswith("""@@""" ) else (re.sub(r"""$""" , """</w>""" , __lowerCAmelCase ), v) for k, v in d.items() ) SCREAMING_SNAKE_CASE__ : Tuple = """<s> <pad> </s> <unk>""".split() # restore the special tokens for k in keep_keys: del da[F'''{k}</w>'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] = d[k] # restore return da def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: # prep assert os.path.exists(__lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) print(F'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models SCREAMING_SNAKE_CASE__ : Optional[Any] = basename(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = dirname(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel SCREAMING_SNAKE_CASE__ : Optional[int] = cls.hub_models() SCREAMING_SNAKE_CASE__ : Optional[int] = {"""bpe""": """fastbpe""", """tokenizer""": """moses"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = """.""" # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(F'''using checkpoint {checkpoint_file}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = hub_utils.from_pretrained( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , archive_map=__lowerCAmelCase , **__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = vars(chkpt["""args"""]["""model"""] ) SCREAMING_SNAKE_CASE__ : Any = args["""source_lang"""] SCREAMING_SNAKE_CASE__ : Any = args["""target_lang"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = dirname(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = basename(__lowerCAmelCase ) # dicts SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(__lowerCAmelCase , F'''dict.{src_lang}.txt''' ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , F'''dict.{tgt_lang}.txt''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Dictionary.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = rewrite_dict_keys(src_dict.indices ) SCREAMING_SNAKE_CASE__ : Optional[int] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , """vocab-src.json""" ) print(F'''Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab SCREAMING_SNAKE_CASE__ : Optional[Any] = True for k in src_vocab.keys(): if not k.islower(): SCREAMING_SNAKE_CASE__ : Tuple = False break SCREAMING_SNAKE_CASE__ : Optional[Any] = Dictionary.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rewrite_dict_keys(tgt_dict.indices ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , """vocab-tgt.json""" ) print(F'''Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # merges_file (bpecodes) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , VOCAB_FILES_NAMES["""merges_file"""] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if os.path.exists(__lowerCAmelCase ): break with open(__lowerCAmelCase , encoding="""utf-8""" ) as fin: SCREAMING_SNAKE_CASE__ : Any = fin.read() SCREAMING_SNAKE_CASE__ : Tuple = re.sub(r""" \d+$""" , """""" , __lowerCAmelCase , 0 , re.M ) # remove frequency number print(F'''Generating {merges_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as fout: fout.write(__lowerCAmelCase ) # model config SCREAMING_SNAKE_CASE__ : Dict = os.path.join(__lowerCAmelCase , """config.json""" ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", F'''need to extend tokenizer to support bpe={args['bpe']}''' assert args["tokenizer"] == "moses", F'''need to extend tokenizer to support bpe={args['tokenizer']}''' SCREAMING_SNAKE_CASE__ : str = { """architectures""": ["""FSMTForConditionalGeneration"""], """model_type""": """fsmt""", """activation_dropout""": args["""activation_dropout"""], """activation_function""": """relu""", """attention_dropout""": args["""attention_dropout"""], """d_model""": args["""decoder_embed_dim"""], """dropout""": args["""dropout"""], """init_std""": 0.02, """max_position_embeddings""": args["""max_source_positions"""], """num_hidden_layers""": args["""encoder_layers"""], """src_vocab_size""": src_vocab_size, """tgt_vocab_size""": tgt_vocab_size, """langs""": [src_lang, tgt_lang], """encoder_attention_heads""": args["""encoder_attention_heads"""], """encoder_ffn_dim""": args["""encoder_ffn_embed_dim"""], """encoder_layerdrop""": args["""encoder_layerdrop"""], """encoder_layers""": args["""encoder_layers"""], """decoder_attention_heads""": args["""decoder_attention_heads"""], """decoder_ffn_dim""": args["""decoder_ffn_embed_dim"""], """decoder_layerdrop""": args["""decoder_layerdrop"""], """decoder_layers""": args["""decoder_layers"""], """bos_token_id""": 0, """pad_token_id""": 1, """eos_token_id""": 2, """is_encoder_decoder""": True, """scale_embedding""": not args["""no_scale_embedding"""], """tie_word_embeddings""": args["""share_all_embeddings"""], } # good hparam defaults to start with SCREAMING_SNAKE_CASE__ : Tuple = 5 SCREAMING_SNAKE_CASE__ : str = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: SCREAMING_SNAKE_CASE__ : Tuple = best_score_hparams[model_dir]["""length_penalty"""] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 1.0 print(F'''Generating {fsmt_model_config_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # tokenizer config SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = { """langs""": [src_lang, tgt_lang], """model_max_length""": 1024, """do_lower_case""": do_lower_case, } print(F'''Generating {fsmt_tokenizer_config_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # model SCREAMING_SNAKE_CASE__ : Dict = chkpt["""models"""][0] SCREAMING_SNAKE_CASE__ : int = model.state_dict() # rename keys to start with 'model.' SCREAMING_SNAKE_CASE__ : Tuple = OrderedDict(("""model.""" + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys SCREAMING_SNAKE_CASE__ : str = [ """model.model""", """model.encoder.version""", """model.decoder.version""", """model.encoder_embed_tokens.weight""", """model.decoder_embed_tokens.weight""", """model.encoder.embed_positions._float_tensor""", """model.decoder.embed_positions._float_tensor""", ] for k in ignore_keys: model_state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = FSMTConfig.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = FSMTForConditionalGeneration(__lowerCAmelCase ) # check that it loads ok model_new.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase ) # save SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) print(F'''Generating {pytorch_weights_dump_path}''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) print("""Conversion is done!""" ) print("""\nLast step is to upload the files to s3""" ) print(F'''cd {data_root}''' ) print(F'''transformers-cli upload {model_dir}''' ) if __name__ == "__main__": a :Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fsmt_checkpoint_path", default=None, type=str, required=True, help=( "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts," " bpecodes, etc." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) a :List[str] = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
12
0
"""simple docstring""" from __future__ import annotations from math import gcd def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 2 , __lowerCAmelCase = 1 , __lowerCAmelCase = 3 , ) -> Any: # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("""The input value cannot be less than 2""" ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: return (pow(lowercase__ , 2 ) + step) % modulus for _ in range(lowercase__ ): # These track the position within the cycle detection logic. SCREAMING_SNAKE_CASE__ : List[str] = seed SCREAMING_SNAKE_CASE__ : Optional[Any] = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. SCREAMING_SNAKE_CASE__ : List[str] = rand_fn(lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = rand_fn(lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = rand_fn(lowercase__ , lowercase__ , lowercase__ ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. SCREAMING_SNAKE_CASE__ : Any = gcd(hare - tortoise , lowercase__ ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. SCREAMING_SNAKE_CASE__ : str = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse a :str = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) a :Tuple = parser.parse_args() a :int = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f'{args.num} is probably prime') else: a :Tuple = args.num // divisor print(f'{args.num} = {divisor} * {quotient}')
701
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = (DDPMScheduler,) def _a ( self , **_a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**_a ) return config def _a ( self ) -> str: """simple docstring""" for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def _a ( self ) -> str: """simple docstring""" for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def _a ( self ) -> Any: """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def _a ( self ) -> int: """simple docstring""" self.check_over_configs(thresholding=_a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , ) def _a ( self ) -> str: """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def _a ( self ) -> str: """simple docstring""" for t in [0, 500, 999]: self.check_over_forward(time_step=_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Any = len(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : str = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : int = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : str = pred_prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.9_606 ) < 1E-2 assert abs(result_mean.item() - 0.3_372 ) < 1E-3 def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Tuple = self.get_scheduler_config(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Dict = len(_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : int = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : Tuple = pred_prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : int = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 202.0_296 ) < 1E-2 assert abs(result_mean.item() - 0.2_631 ) < 1E-3 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = -1 else: SCREAMING_SNAKE_CASE__ : Tuple = timesteps[i + 1] SCREAMING_SNAKE_CASE__ : int = scheduler.previous_timestep(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prev_t.item() self.assertEqual(_a , _a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [100, 87, 50, 51, 0] with self.assertRaises(_a , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : int = [100, 87, 50, 1, 0] SCREAMING_SNAKE_CASE__ : List[str] = len(_a ) with self.assertRaises(_a , msg="""Can only pass one of `num_inference_steps` or `custom_timesteps`.""" ): scheduler.set_timesteps(num_inference_steps=_a , timesteps=_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( _a , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=_a )
12
0
"""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_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :int = ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Dict = [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys a :int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
702
"""simple docstring""" import os a :List[str] = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1_000} def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 while index < len(__lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE__ : List[Any] = SYMBOLS[numerals[index]] SCREAMING_SNAKE_CASE__ : Dict = 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 _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = """""" SCREAMING_SNAKE_CASE__ : int = num // 1000 numerals += m_count * "M" num %= 1000 SCREAMING_SNAKE_CASE__ : List[str] = 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 SCREAMING_SNAKE_CASE__ : List[Any] = 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 _lowercase ( __lowerCAmelCase = "/p089_roman.txt" ) -> int: SCREAMING_SNAKE_CASE__ : int = 0 with open(os.path.dirname(__lowerCAmelCase ) + roman_numerals_filename ) as filea: SCREAMING_SNAKE_CASE__ : str = filea.readlines() for line in lines: SCREAMING_SNAKE_CASE__ : Union[str, Any] = line.strip() SCREAMING_SNAKE_CASE__ : Dict = parse_roman_numerals(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = generate_roman_numerals(__lowerCAmelCase ) savings += len(__lowerCAmelCase ) - len(__lowerCAmelCase ) return savings if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a :Optional[int] = logging.get_logger(__name__) a :Tuple = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class __a (_UpperCAmelCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """trocr""" _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :str = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self , _a=50_265 , _a=1_024 , _a=12 , _a=16 , _a=4_096 , _a="gelu" , _a=512 , _a=0.1 , _a=0.0 , _a=0.0 , _a=2 , _a=0.02 , _a=0.0 , _a=True , _a=False , _a=True , _a=True , _a=1 , _a=0 , _a=2 , **_a , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : int = d_model SCREAMING_SNAKE_CASE__ : Any = decoder_layers SCREAMING_SNAKE_CASE__ : str = decoder_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : str = activation_function SCREAMING_SNAKE_CASE__ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = dropout SCREAMING_SNAKE_CASE__ : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE__ : Dict = activation_dropout SCREAMING_SNAKE_CASE__ : Tuple = init_std SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[int] = use_cache SCREAMING_SNAKE_CASE__ : Union[str, Any] = scale_embedding SCREAMING_SNAKE_CASE__ : Optional[Any] = use_learned_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = layernorm_embedding super().__init__( pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , decoder_start_token_id=lowercase__ , **lowercase__ , )
703
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) SCREAMING_SNAKE_CASE__ : Any = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 25_543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : List[str] = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , _a ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Optional[int] = tf.convert_to_tensor( [[[-0.0_254, 0.0_235, 0.1_027], [0.0_606, -0.1_811, -0.0_418], [-0.1_561, -0.1_127, 0.2_687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
12
0
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (__SCREAMING_SNAKE_CASE , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = LEDTokenizer _SCREAMING_SNAKE_CASE :List[Any] = LEDTokenizerFast _SCREAMING_SNAKE_CASE :Union[str, Any] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : Optional[int] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] SCREAMING_SNAKE_CASE__ : Any = dict(zip(__snake_case , range(len(__snake_case ) ) ) ) SCREAMING_SNAKE_CASE__ : List[str] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE__ : int = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ : 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 ) ) def _a ( self , **_a ) -> Optional[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__snake_case ) def _a ( self , **_a ) -> Dict: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__snake_case ) def _a ( self , _a ) -> Optional[int]: """simple docstring""" return "lower newer", "lower newer" @cached_property def _a ( self ) -> Optional[int]: """simple docstring""" return LEDTokenizer.from_pretrained("""allenai/led-base-16384""" ) @cached_property def _a ( self ) -> str: """simple docstring""" return LEDTokenizerFast.from_pretrained("""allenai/led-base-16384""" ) @require_torch def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] SCREAMING_SNAKE_CASE__ : List[Any] = [0, 250, 251, 17_818, 13, 39_186, 1_938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(__snake_case , max_length=len(__snake_case ) , padding=__snake_case , return_tensors="""pt""" ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) SCREAMING_SNAKE_CASE__ : List[Any] = batch.input_ids.tolist()[0] self.assertListEqual(__snake_case , __snake_case ) @require_torch def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer(__snake_case , padding=__snake_case , return_tensors="""pt""" ) self.assertIn("""input_ids""" , __snake_case ) self.assertIn("""attention_mask""" , __snake_case ) self.assertNotIn("""labels""" , __snake_case ) self.assertNotIn("""decoder_attention_mask""" , __snake_case ) @require_torch def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ '''Summary of the text.''', '''Another summary.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer(text_target=__snake_case , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def _a ( self ) -> Tuple: """simple docstring""" for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer( ["""I am a small frog""" * 1_024, """I am a small frog"""] , padding=__snake_case , truncation=__snake_case , return_tensors="""pt""" ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(batch.input_ids.shape , (2, 5_122) ) @require_torch def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['''A long paragraph for summarization.'''] SCREAMING_SNAKE_CASE__ : Any = [ '''Summary of the text.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer(__snake_case , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(text_target=__snake_case , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = inputs['''input_ids'''] SCREAMING_SNAKE_CASE__ : Any = targets['''input_ids'''] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def _a ( self ) -> int: """simple docstring""" for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: SCREAMING_SNAKE_CASE__ : Optional[int] = ['''Summary of the text.''', '''Another summary.'''] SCREAMING_SNAKE_CASE__ : List[Any] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(__snake_case , padding=__snake_case ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[0] * len(__snake_case ) for x in encoded_output['''input_ids''']] SCREAMING_SNAKE_CASE__ : str = tokenizer.pad(__snake_case ) self.assertSequenceEqual(outputs["""global_attention_mask"""] , __snake_case ) def _a ( self ) -> Union[str, Any]: """simple docstring""" pass def _a ( self ) -> Union[str, Any]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class.from_pretrained(__snake_case , **__snake_case ) SCREAMING_SNAKE_CASE__ : int = '''A, <mask> AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ : str = tokenizer_r.encode_plus(__snake_case , add_special_tokens=__snake_case , return_token_type_ids=__snake_case ) SCREAMING_SNAKE_CASE__ : str = tokenizer_p.encode_plus(__snake_case , add_special_tokens=__snake_case , return_token_type_ids=__snake_case ) self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual( __snake_case , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( __snake_case , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
704
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a :List[Any] = logging.get_logger(__name__) a :Optional[int] = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """focalnet""" def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=False , _a=[192, 384, 768, 768] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1E-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1E-5 , _a=32 , _a=None , _a=None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : str = patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = embed_dim SCREAMING_SNAKE_CASE__ : List[str] = use_conv_embed SCREAMING_SNAKE_CASE__ : List[str] = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Any = focal_levels SCREAMING_SNAKE_CASE__ : Optional[Any] = focal_windows SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : str = use_layerscale SCREAMING_SNAKE_CASE__ : int = layerscale_value SCREAMING_SNAKE_CASE__ : Optional[int] = use_post_layernorm SCREAMING_SNAKE_CASE__ : Any = use_post_layernorm_in_modulation SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize_modulator SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = encoder_stride SCREAMING_SNAKE_CASE__ : Optional[int] = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
12
0
"""simple docstring""" import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a :int = """true""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=82 , __lowerCAmelCase=16 ) -> Tuple: set_seed(42 ) SCREAMING_SNAKE_CASE__ : Tuple = RegressionModel() SCREAMING_SNAKE_CASE__ : Optional[int] = deepcopy(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = RegressionDataset(length=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) model.to(accelerator.device ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase , __lowerCAmelCase ) return model, ddp_model, dataloader def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=False ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""hf-internal-testing/mrpc-bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : str = load_dataset("""glue""" , """mrpc""" , split="""validation""" ) def tokenize_function(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Dict = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : Tuple = dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) SCREAMING_SNAKE_CASE__ : str = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): if use_longest: return tokenizer.pad(__lowerCAmelCase , padding="""longest""" , return_tensors="""pt""" ) return tokenizer.pad(__lowerCAmelCase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return DataLoader(__lowerCAmelCase , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=16 ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[int] = Accelerator(dispatch_batches=__lowerCAmelCase , split_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_dataloader(__lowerCAmelCase , not dispatch_batches ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoModelForSequenceClassification.from_pretrained( """hf-internal-testing/mrpc-bert-base-cased""" , return_dict=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = accelerator.prepare(__lowerCAmelCase , __lowerCAmelCase ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : List[Any] = [] for batch in dataloader: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = [], [] for logit, targ in logits_and_targets: logits.append(__lowerCAmelCase ) targs.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat(__lowerCAmelCase ), torch.cat(__lowerCAmelCase ) return logits, targs def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=82 , __lowerCAmelCase=False , __lowerCAmelCase=False , __lowerCAmelCase=16 ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = get_basic_setup(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = generate_predictions(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) assert ( len(__lowerCAmelCase ) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(__lowerCAmelCase )}''' def _lowercase ( __lowerCAmelCase = False , __lowerCAmelCase = False ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[str] = evaluate.load("""glue""" , """mrpc""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_mrpc_setup(__lowerCAmelCase , __lowerCAmelCase ) # First do baseline SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = setup["""no"""] model.to(__lowerCAmelCase ) model.eval() for batch in dataloader: batch.to(__lowerCAmelCase ) with torch.inference_mode(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=__lowerCAmelCase , references=batch["""labels"""] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = setup["""ddp"""] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ : int = batch["""labels"""] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=__lowerCAmelCase , references=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : int = Accelerator(split_batches=__lowerCAmelCase , dispatch_batches=__lowerCAmelCase ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print("""**Testing gather_for_metrics**""" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''' ) test_mrpc(__lowerCAmelCase , __lowerCAmelCase ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("""**Test torch metrics**""" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE__ : Dict = Accelerator(split_batches=__lowerCAmelCase , dispatch_batches=__lowerCAmelCase ) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''' ) test_torch_metrics(__lowerCAmelCase , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("""**Test last batch is not dropped when perfectly divisible**""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = Accelerator() test_torch_metrics(__lowerCAmelCase , 512 ) accelerator.state._reset_state() def _lowercase ( __lowerCAmelCase ) -> Tuple: main() if __name__ == "__main__": main()
705
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __a (unittest.TestCase): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_attention_mask SCREAMING_SNAKE_CASE__ : Tuple = use_token_type_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = num_choices def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE__ : int = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = True _SCREAMING_SNAKE_CASE :Optional[Any] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerModelTester(self ) @slow def _a ( self ) -> int: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a ) @require_flax class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.array([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ : str = model(_a )[0] SCREAMING_SNAKE_CASE__ : List[Any] = 50_000 SCREAMING_SNAKE_CASE__ : Optional[Any] = (1, 6, vocab_size) self.assertEqual(output.shape , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
12
0
"""simple docstring""" import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __a (_UpperCamelCase , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = ConsistencyModelPipeline _SCREAMING_SNAKE_CASE :Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_PARAMS _SCREAMING_SNAKE_CASE :Dict = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt _SCREAMING_SNAKE_CASE :List[str] = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ]) @property def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = UNetaDModel.from_pretrained( """diffusers/consistency-models-test""" , subfolder="""test_unet""" , ) return unet @property def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = UNetaDModel.from_pretrained( """diffusers/consistency-models-test""" , subfolder="""test_unet_class_cond""" , ) return unet def _a ( self , _a=False ) -> Tuple: """simple docstring""" if class_cond: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_cond_unet else: SCREAMING_SNAKE_CASE__ : Any = self.dummy_uncond_unet # Default to CM multistep sampler SCREAMING_SNAKE_CASE__ : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = { "unet": unet, "scheduler": scheduler, } return components def _a ( self , _a , _a=0 ) -> Optional[int]: """simple docstring""" if str(__a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = torch.manual_seed(__a ) else: SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device=__a ).manual_seed(__a ) SCREAMING_SNAKE_CASE__ : Any = { "batch_size": 1, "num_inference_steps": None, "timesteps": [22, 0], "generator": generator, "output_type": "np", } return inputs def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[int] = ConsistencyModelPipeline(**__a ) SCREAMING_SNAKE_CASE__ : int = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_inputs(__a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**__a ).images assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_components(class_cond=__a ) SCREAMING_SNAKE_CASE__ : List[Any] = ConsistencyModelPipeline(**__a ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(__a ) SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : List[str] = pipe(**__a ).images assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[Any] = ConsistencyModelPipeline(**__a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(__a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Optional[int] = pipe(**__a ).images assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components(class_cond=__a ) SCREAMING_SNAKE_CASE__ : List[str] = ConsistencyModelPipeline(**__a ) SCREAMING_SNAKE_CASE__ : List[str] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(__a ) SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : int = pipe(**__a ).images assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Tuple = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self , _a=0 , _a=False , _a="cpu" , _a=torch.floataa , _a=(1, 3, 64, 64) ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = torch.manual_seed(__a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "num_inference_steps": None, "timesteps": [22, 0], "class_labels": 0, "generator": generator, "output_type": "np", } if get_fixed_latents: SCREAMING_SNAKE_CASE__ : List[str] = self.get_fixed_latents(seed=__a , device=__a , dtype=__a , shape=__a ) SCREAMING_SNAKE_CASE__ : List[Any] = latents return inputs def _a ( self , _a=0 , _a="cpu" , _a=torch.floataa , _a=(1, 3, 64, 64) ) -> Dict: """simple docstring""" if type(__a ) == str: SCREAMING_SNAKE_CASE__ : int = torch.device(__a ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Generator(device=__a ).manual_seed(__a ) SCREAMING_SNAKE_CASE__ : List[Any] = randn_tensor(__a , generator=__a , device=__a , dtype=__a ) return latents def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) SCREAMING_SNAKE_CASE__ : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) SCREAMING_SNAKE_CASE__ : List[Any] = ConsistencyModelPipeline(unet=__a , scheduler=__a ) pipe.to(torch_device=__a ) pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE__ : Any = self.get_inputs() SCREAMING_SNAKE_CASE__ : List[str] = pipe(**__a ).images assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : int = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Tuple = np.array([0.0_888, 0.0_881, 0.0_666, 0.0_479, 0.0_292, 0.0_195, 0.0_201, 0.0_163, 0.0_254] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) SCREAMING_SNAKE_CASE__ : List[Any] = ConsistencyModelPipeline(unet=__a , scheduler=__a ) pipe.to(torch_device=__a ) pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_inputs() SCREAMING_SNAKE_CASE__ : List[str] = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Optional[int] = pipe(**__a ).images assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : int = np.array([0.0_340, 0.0_152, 0.0_063, 0.0_267, 0.0_221, 0.0_107, 0.0_416, 0.0_186, 0.0_217] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 @require_torch_a def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) SCREAMING_SNAKE_CASE__ : Any = ConsistencyModelPipeline(unet=__a , scheduler=__a ) pipe.to(torch_device=__a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_inputs(get_fixed_latents=__a , device=__a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__a , enable_math=__a , enable_mem_efficient=__a ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**__a ).images assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Tuple = np.array([0.1_875, 0.1_428, 0.1_289, 0.2_151, 0.2_092, 0.1_477, 0.1_877, 0.1_641, 0.1_353] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @require_torch_a def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ConsistencyModelPipeline(unet=__a , scheduler=__a ) pipe.to(torch_device=__a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE__ : int = self.get_inputs(get_fixed_latents=__a , device=__a ) SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Any = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__a , enable_math=__a , enable_mem_efficient=__a ): SCREAMING_SNAKE_CASE__ : int = pipe(**__a ).images assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = np.array([0.1_663, 0.1_948, 0.2_275, 0.1_680, 0.1_204, 0.1_245, 0.1_858, 0.1_338, 0.2_095] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
706
"""simple docstring""" a :List[str] = [ (1_000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1000} SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 while place < len(__lowerCAmelCase ): if (place + 1 < len(__lowerCAmelCase )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = [] for arabic, roman in ROMAN: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : List[str] = divmod(__lowerCAmelCase , __lowerCAmelCase ) result.append(roman * factor ) if number == 0: break return "".join(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": a :Optional[Any] = "%20".join(argv[1:]) if len(argv) > 1 else quote(str(input("Search: "))) print("Googling.....") a :Tuple = f'https://www.google.com/search?q={query}&num=100' a :Optional[Any] = requests.get( url, headers={"User-Agent": str(UserAgent().random)}, ) try: a :str = ( BeautifulSoup(res.text, "html.parser") .find("div", attrs={"class": "yuRUbf"}) .find("a") .get("href") ) except AttributeError: a :List[str] = parse_qs( BeautifulSoup(res.text, "html.parser") .find("div", attrs={"class": "kCrYT"}) .find("a") .get("href") )["url"][0] webbrowser.open(link)
707
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a :Any = { "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig", "RobertaPreLayerNormOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Union[str, Any] = [ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[Any] = [ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = [ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
12
0
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=_lowerCAmelCase) class __a (_lowerCAmelCase): '''simple docstring''' # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization _SCREAMING_SNAKE_CASE :str = field(default="""question-answering-extractive""" , metadata={"""include_in_asdict_even_if_is_default""": True}) _SCREAMING_SNAKE_CASE :ClassVar[Features] = Features({"""question""": Value("""string"""), """context""": Value("""string""")}) _SCREAMING_SNAKE_CASE :ClassVar[Features] = Features( { """answers""": Sequence( { """text""": Value("""string"""), """answer_start""": Value("""int32"""), }) }) _SCREAMING_SNAKE_CASE :str = "question" _SCREAMING_SNAKE_CASE :str = "context" _SCREAMING_SNAKE_CASE :str = "answers" @property def _a ( self ) -> Dict[str, str]: """simple docstring""" return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
708
"""simple docstring""" 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 IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : Dict = 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__ : Optional[Any] = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073], """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711], } SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_a , _a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> Any: """simple docstring""" return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **_a ) def _a ( self ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Optional[int] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=_a ) SCREAMING_SNAKE_CASE__ : int = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = AlignProcessor.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 _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[str] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(images=_a , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Any = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(text=_a ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(_a , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = 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 _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.batch_decode(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[str] = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
12
0
"""simple docstring""" from __future__ import annotations def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: if len(snake_case_ ) == 0: return False SCREAMING_SNAKE_CASE__ : str = len(snake_case_ ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint] , snake_case_ ) else: return binary_search(a_list[midpoint + 1 :] , snake_case_ ) if __name__ == "__main__": a :List[str] = input("Enter numbers separated by comma:\n").strip() a :List[Any] = [int(item.strip()) for item in user_input.split(",")] a :List[Any] = int(input("Enter the number to be found in the list:\n").strip()) a :Dict = "" if binary_search(sequence, target) else "not " print(f'{target} was {not_str}found in {sequence}')
709
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging a :Optional[Any] = logging.get_logger(__name__) a :Union[str, Any] = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """t5""" _SCREAMING_SNAKE_CASE :List[str] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Any = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self , _a=32_128 , _a=512 , _a=64 , _a=2_048 , _a=6 , _a=None , _a=8 , _a=32 , _a=128 , _a=0.1 , _a=1E-6 , _a=1.0 , _a="relu" , _a=True , _a=True , _a=0 , _a=1 , **_a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = d_model SCREAMING_SNAKE_CASE__ : int = d_kv SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_ff SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_layers SCREAMING_SNAKE_CASE__ : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry SCREAMING_SNAKE_CASE__ : Tuple = num_heads SCREAMING_SNAKE_CASE__ : Dict = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : str = relative_attention_max_distance SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_factor SCREAMING_SNAKE_CASE__ : Tuple = feed_forward_proj SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : List[str] = self.feed_forward_proj.split("""-""" ) SCREAMING_SNAKE_CASE__ : Dict = act_info[-1] SCREAMING_SNAKE_CASE__ : str = act_info[0] == """gated""" if len(_a ) > 1 and act_info[0] != "gated" or len(_a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": SCREAMING_SNAKE_CASE__ : List[Any] = """gelu_new""" super().__init__( pad_token_id=_a , eos_token_id=_a , is_encoder_decoder=_a , **_a , ) class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: SCREAMING_SNAKE_CASE__ : Tuple = """past_encoder_sequence + sequence""" SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch"""} SCREAMING_SNAKE_CASE__ : Tuple = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : str = {0: """batch""", 1: """decoder_sequence"""} SCREAMING_SNAKE_CASE__ : Dict = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_a , direction="""inputs""" ) return common_inputs @property def _a ( self ) -> int: """simple docstring""" return 13
12
0
"""simple docstring""" from timeit import timeit def _lowercase ( __lowerCAmelCase ) -> int: if number < 0: raise ValueError("""the value of input must not be negative""" ) SCREAMING_SNAKE_CASE__ : int = 0 while number: number &= number - 1 result += 1 return result def _lowercase ( __lowerCAmelCase ) -> int: if number < 0: raise ValueError("""the value of input must not be negative""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def _lowercase ( ) -> None: def do_benchmark(__lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : List[str] = '''import __main__ as z''' print(F'''Benchmark when {number = }:''' ) print(F'''{get_set_bits_count_using_modulo_operator(__UpperCamelCase ) = }''' ) SCREAMING_SNAKE_CASE__ : int = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__UpperCamelCase ) print(F'''timeit() runs in {timing} seconds''' ) print(F'''{get_set_bits_count_using_brian_kernighans_algorithm(__UpperCamelCase ) = }''' ) SCREAMING_SNAKE_CASE__ : Any = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__UpperCamelCase , ) print(F'''timeit() runs in {timing} seconds''' ) for number in (25, 37, 58, 0): do_benchmark(__UpperCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
710
"""simple docstring""" from __future__ import annotations import time import numpy as np a :Optional[Any] = [8, 5, 9, 7] a :List[Any] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] a :int = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class __a : '''simple docstring''' def __init__( self , _a , _a , _a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = claim_vector SCREAMING_SNAKE_CASE__ : Any = allocated_resources_table SCREAMING_SNAKE_CASE__ : Any = maximum_claim_table def _a ( self ) -> list[int]: """simple docstring""" return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def _a ( self ) -> list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def _a ( self ) -> list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(_a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def _a ( self ) -> dict[int, list[int]]: """simple docstring""" return {self.__need().index(_a ): i for i in self.__need()} def _a ( self , **_a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.__need() SCREAMING_SNAKE_CASE__ : Any = self.__allocated_resources_table SCREAMING_SNAKE_CASE__ : Dict = self.__available_resources() SCREAMING_SNAKE_CASE__ : Dict = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 50 + """\n""" ) while need_list: SCREAMING_SNAKE_CASE__ : List[str] = False for each_need in need_list: SCREAMING_SNAKE_CASE__ : Dict = True for index, need in enumerate(_a ): if need > available_resources[index]: SCREAMING_SNAKE_CASE__ : Optional[int] = False break if execution: SCREAMING_SNAKE_CASE__ : Any = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: SCREAMING_SNAKE_CASE__ : Tuple = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(_a ) # update available/freed resources stack SCREAMING_SNAKE_CASE__ : Dict = np.array(_a ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(_a ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def _a ( self ) -> Any: """simple docstring""" print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(_a ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(_a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING a :List[str] = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase__) class __a (lowerCAmelCase__): '''simple docstring''' def __init__( self , *_a , **_a ) -> int: """simple docstring""" super().__init__(*_lowerCamelCase , **_lowerCamelCase ) self.check_model_type(_lowerCamelCase ) def _a ( self , _a=None , _a=None , _a=None , **_a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = {}, {} if padding is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = padding if truncation is not None: SCREAMING_SNAKE_CASE__ : str = truncation if top_k is not None: SCREAMING_SNAKE_CASE__ : Tuple = top_k return preprocess_params, {}, postprocess_params def __call__( self , _a , _a = None , **_a ) -> str: """simple docstring""" if isinstance(_lowerCamelCase , (Image.Image, str) ) and isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""image""": image, """question""": question} else: SCREAMING_SNAKE_CASE__ : Optional[Any] = image SCREAMING_SNAKE_CASE__ : str = super().__call__(_lowerCamelCase , **_lowerCamelCase ) return results def _a ( self , _a , _a=False , _a=False ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = load_image(inputs["""image"""] ) SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer( inputs["""question"""] , return_tensors=self.framework , padding=_lowerCamelCase , truncation=_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Any = self.image_processor(images=_lowerCamelCase , return_tensors=self.framework ) model_inputs.update(_lowerCamelCase ) return model_inputs def _a ( self , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model(**_lowerCamelCase ) return model_outputs def _a ( self , _a , _a=5 ) -> Tuple: """simple docstring""" if top_k > self.model.config.num_labels: SCREAMING_SNAKE_CASE__ : List[Any] = self.model.config.num_labels if self.framework == "pt": SCREAMING_SNAKE_CASE__ : Optional[int] = model_outputs.logits.sigmoid()[0] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = probs.topk(_lowerCamelCase ) else: raise ValueError(f'''Unsupported framework: {self.framework}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = scores.tolist() SCREAMING_SNAKE_CASE__ : str = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(_lowerCamelCase , _lowerCamelCase )]
711
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: a :List[Any] = None a :Optional[int] = logging.get_logger(__name__) a :Union[str, Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} a :Optional[int] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } a :Dict = { "xlnet-base-cased": None, "xlnet-large-cased": None, } a :int = "▁" # Segments (not really needed) a :Dict = 0 a :Optional[int] = 1 a :Tuple = 2 a :List[str] = 3 a :Optional[Any] = 4 class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = """left""" _SCREAMING_SNAKE_CASE :Optional[Any] = XLNetTokenizer def __init__( self , _a=None , _a=None , _a=False , _a=True , _a=False , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<sep>" , _a="<pad>" , _a="<cls>" , _a="<mask>" , _a=["<eop>", "<eod>"] , **_a , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , additional_special_tokens=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE__ : List[str] = remove_space SCREAMING_SNAKE_CASE__ : int = keep_accents SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_file SCREAMING_SNAKE_CASE__ : Tuple = False if not self.vocab_file else True def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Tuple = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict = "" for i in table: res += inp[i - 1] return res def _lowercase ( __lowerCAmelCase ) -> int: return data[1:] + data[0] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = "" for i in range(len(__snake_case ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : int = int("""0b""" + data[0] + data[-1] , 2 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int("""0b""" + data[1:3] , 2 ) return bin(s[row][col] )[2:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__ : Tuple = message[:4] SCREAMING_SNAKE_CASE__ : int = message[4:] SCREAMING_SNAKE_CASE__ : int = apply_table(__snake_case , __snake_case ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = xor(__snake_case , __snake_case ) SCREAMING_SNAKE_CASE__ : Tuple = apply_sbox(__snake_case , temp[:4] ) # noqa: E741 SCREAMING_SNAKE_CASE__ : List[str] = apply_sbox(__snake_case , temp[4:] ) SCREAMING_SNAKE_CASE__ : int = "0" * (2 - len(__snake_case )) + l # noqa: E741 SCREAMING_SNAKE_CASE__ : int = "0" * (2 - len(__snake_case )) + r SCREAMING_SNAKE_CASE__ : Optional[Any] = apply_table(l + r , __snake_case ) SCREAMING_SNAKE_CASE__ : Tuple = xor(__snake_case , __snake_case ) return temp + right if __name__ == "__main__": a :Dict = input("Enter 10 bit key: ") a :Tuple = input("Enter 8 bit message: ") a :Any = [6, 3, 7, 4, 8, 5, 10, 9] a :List[str] = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] a :Tuple = [2, 4, 3, 1] a :List[Any] = [2, 6, 3, 1, 4, 8, 5, 7] a :Optional[Any] = [4, 1, 3, 5, 7, 2, 8, 6] a :Optional[int] = [4, 1, 2, 3, 2, 3, 4, 1] a :List[Any] = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] a :Union[str, Any] = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation a :int = apply_table(key, paa_table) a :Dict = temp[:5] a :Optional[int] = temp[5:] a :Optional[int] = left_shift(left) a :Union[str, Any] = left_shift(right) a :int = apply_table(left + right, pa_table) a :Tuple = left_shift(left) a :Union[str, Any] = left_shift(right) a :Dict = left_shift(left) a :Optional[Any] = left_shift(right) a :Optional[int] = apply_table(left + right, pa_table) # encryption a :Tuple = apply_table(message, IP) a :Tuple = function(expansion, sa, sa, keya, temp) a :List[Any] = temp[4:] + temp[:4] a :int = function(expansion, sa, sa, keya, temp) a :Union[str, Any] = apply_table(temp, IP_inv) print("Cipher text is:", CT) # decryption a :List[Any] = apply_table(CT, IP) a :List[Any] = function(expansion, sa, sa, keya, temp) a :int = temp[4:] + temp[:4] a :Union[str, Any] = function(expansion, sa, sa, keya, temp) a :Union[str, Any] = apply_table(temp, IP_inv) print("Plain text after decypting is:", PT)
712
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) + 1 SCREAMING_SNAKE_CASE__ : int = len(__lowerCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. SCREAMING_SNAKE_CASE__ : Dict = [[0 for i in range(__lowerCAmelCase )] for j in range(__lowerCAmelCase )] # since string of zero length match pattern of zero length SCREAMING_SNAKE_CASE__ : Dict = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : int = dp[0][j - 2] if pattern[j - 1] == """*""" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __lowerCAmelCase ): for j in range(1 , __lowerCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": SCREAMING_SNAKE_CASE__ : Any = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: SCREAMING_SNAKE_CASE__ : List[str] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): SCREAMING_SNAKE_CASE__ : List[Any] = dp[i - 1][j] else: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 else: SCREAMING_SNAKE_CASE__ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") a :Any = "aab" a :Optional[Any] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f'{input_string} matches the given pattern {pattern}') else: print(f'{input_string} does not match with the given pattern {pattern}')
12
0
"""simple docstring""" from __future__ import annotations a :List[Any] = "#" class __a : '''simple docstring''' def __init__( self ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = {} def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._trie for char in text: if char not in trie: SCREAMING_SNAKE_CASE__ : str = {} SCREAMING_SNAKE_CASE__ : Union[str, Any] = trie[char] SCREAMING_SNAKE_CASE__ : str = True def _a ( self , _a ) -> tuple | list: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self._trie for char in prefix: if char in trie: SCREAMING_SNAKE_CASE__ : List[str] = trie[char] else: return [] return self._elements(__A ) def _a ( self , _a ) -> tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for c, v in d.items(): SCREAMING_SNAKE_CASE__ : Dict = [""" """] if c == END else [(c + s) for s in self._elements(__A )] result.extend(__A ) return tuple(__A ) a :Optional[int] = Trie() a :Optional[Any] = ("depart", "detergent", "daring", "dog", "deer", "deal") for word in words: trie.insert_word(word) def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] = trie.find_word(a__ ) return tuple(string + word for word in suffixes ) def _lowercase ( ) -> str: print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
713
"""simple docstring""" from math import sqrt def _lowercase ( __lowerCAmelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowercase ( __lowerCAmelCase = 1_0001 ) -> int: SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = 1 while count != nth and number < 3: number += 1 if is_prime(__lowerCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(__lowerCAmelCase ): count += 1 return number if __name__ == "__main__": print(f'{solution() = }')
12
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 _lowercase ( __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = 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.''' ) SCREAMING_SNAKE_CASE__ : int = 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.''' ) SCREAMING_SNAKE_CASE__ : int = components[:-1] + [test_fn.replace(""".py""" , """""" )] SCREAMING_SNAKE_CASE__ : int = """.""".join(UpperCamelCase__ ) return test_module_path def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_module_path(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : int = importlib.import_module(UpperCamelCase__ ) return test_module def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Tuple = get_test_module(UpperCamelCase__ ) for attr in dir(UpperCamelCase__ ): if attr.endswith("""ModelTester""" ): tester_classes.append(getattr(UpperCamelCase__ , UpperCamelCase__ ) ) # sort with class names return sorted(UpperCamelCase__ , key=lambda __lowerCAmelCase : x.__name__ ) def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : List[str] = get_test_module(UpperCamelCase__ ) for attr in dir(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(UpperCamelCase__ , UpperCamelCase__ ) # (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). SCREAMING_SNAKE_CASE__ : int = getattr(UpperCamelCase__ , """all_model_classes""" , [] ) if len(UpperCamelCase__ ) > 0: test_classes.append(UpperCamelCase__ ) # sort with class names return sorted(UpperCamelCase__ , key=lambda __lowerCAmelCase : x.__name__ ) def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = get_test_classes(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(UpperCamelCase__ , key=lambda __lowerCAmelCase : x.__name__ ) def _lowercase ( __lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict = test_class() if hasattr(UpperCamelCase__ , """setUp""" ): test.setUp() SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if hasattr(UpperCamelCase__ , """model_tester""" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: SCREAMING_SNAKE_CASE__ : Tuple = test.model_tester.__class__ return model_tester def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : List[str] = get_test_classes(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(UpperCamelCase__ ) # sort with class names return sorted(UpperCamelCase__ , key=lambda __lowerCAmelCase : x.__name__ ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = get_test_classes_for_model(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = [] for test_class in test_classes: SCREAMING_SNAKE_CASE__ : str = get_model_tester_from_test_class(UpperCamelCase__ ) if tester_class is not None: tester_classes.append(UpperCamelCase__ ) # sort with class names return sorted(UpperCamelCase__ , key=lambda __lowerCAmelCase : x.__name__ ) def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : str = get_test_classes(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {test_class: get_model_tester_from_test_class(UpperCamelCase__ ) for test_class in test_classes} return test_tester_mapping def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = get_model_classes(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str = { model_class: get_test_classes_for_model(UpperCamelCase__ , UpperCamelCase__ ) for model_class in model_classes } return model_test_mapping def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] = get_model_classes(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = { model_class: get_tester_classes_for_model(UpperCamelCase__ , UpperCamelCase__ ) for model_class in model_classes } return model_to_tester_mapping def _lowercase ( __lowerCAmelCase ) -> str: if isinstance(UpperCamelCase__ , UpperCamelCase__ ): return o elif isinstance(UpperCamelCase__ , UpperCamelCase__ ): return o.__name__ elif isinstance(UpperCamelCase__ , (list, tuple) ): return [to_json(UpperCamelCase__ ) for x in o] elif isinstance(UpperCamelCase__ , UpperCamelCase__ ): return {to_json(UpperCamelCase__ ): to_json(UpperCamelCase__ ) for k, v in o.items()} else: return o
714
"""simple docstring""" class __a : '''simple docstring''' def __init__( self , _a , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = name SCREAMING_SNAKE_CASE__ : Optional[Any] = value SCREAMING_SNAKE_CASE__ : List[Any] = weight def __repr__( self ) -> List[Any]: """simple docstring""" return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def _a ( self ) -> Dict: """simple docstring""" return self.value def _a ( self ) -> int: """simple docstring""" return self.name def _a ( self ) -> Optional[Any]: """simple docstring""" return self.weight def _a ( self ) -> Dict: """simple docstring""" return self.value / self.weight def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict: SCREAMING_SNAKE_CASE__ : Any = [] for i in range(len(__lowerCAmelCase ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = sorted(__lowerCAmelCase , key=__lowerCAmelCase , reverse=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 0.0, 0.0 for i in range(len(__lowerCAmelCase ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def _lowercase ( ) -> List[str]: pass if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) a :Optional[int] = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :int = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[str] = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :int = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
715
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: a :Optional[int] = None a :Optional[Any] = logging.get_logger(__name__) a :Optional[Any] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} a :Union[str, Any] = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } a :Any = { "facebook/nllb-large-en-ro": 1_024, "facebook/nllb-200-distilled-600M": 1_024, } # fmt: off a :Tuple = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :int = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE :Tuple = NllbTokenizer _SCREAMING_SNAKE_CASE :List[int] = [] _SCREAMING_SNAKE_CASE :List[int] = [] def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , _a=False , **_a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token SCREAMING_SNAKE_CASE__ : Optional[int] = legacy_behaviour super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , legacy_behaviour=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_file SCREAMING_SNAKE_CASE__ : str = False if not self.vocab_file else True SCREAMING_SNAKE_CASE__ : Dict = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens} ) SCREAMING_SNAKE_CASE__ : List[str] = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE__ : Dict = src_lang if src_lang is not None else """eng_Latn""" SCREAMING_SNAKE_CASE__ : List[str] = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE__ : Dict = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _a ( self ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _a ( self , _a , _a , _a , _a , **_a ) -> Tuple: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ : Dict = src_lang SCREAMING_SNAKE_CASE__ : Dict = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_tokens_to_ids(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tgt_lang_id return inputs def _a ( self , _a , _a = "eng_Latn" , _a = None , _a = "fra_Latn" , **_a , ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = src_lang SCREAMING_SNAKE_CASE__ : Dict = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _a ( self ) -> str: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Dict = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : int = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : int = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.eos_token_id] SCREAMING_SNAKE_CASE__ : Any = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return SCREAMING_SNAKE_CASE__ : Dict = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class __a : '''simple docstring''' def __init__( self , _a=2 , _a=3 , _a=64 , _a=None ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(__a ) SCREAMING_SNAKE_CASE__ : Dict = length SCREAMING_SNAKE_CASE__ : str = rng.normal(size=(length,) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> Union[str, Any]: """simple docstring""" return self.length def __getitem__( self , _a ) -> Optional[int]: """simple docstring""" return {"x": self.x[i], "y": self.y[i]} class __a (torch.nn.Module): '''simple docstring''' def __init__( self , _a=0 , _a=0 , _a=False ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) SCREAMING_SNAKE_CASE__ : str = True def _a ( self , _a=None ) -> Optional[Any]: """simple docstring""" if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = False return x * self.a[0] + self.b[0] class __a (torch.nn.Module): '''simple docstring''' def __init__( self , _a=0 , _a=0 , _a=False ) -> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : int = torch.nn.Parameter(torch.tensor(__a ).float() ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Parameter(torch.tensor(__a ).float() ) SCREAMING_SNAKE_CASE__ : List[str] = True def _a ( self , _a=None ) -> List[Any]: """simple docstring""" if self.first_batch: print(f'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) SCREAMING_SNAKE_CASE__ : Dict = False return x * self.a + self.b def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> int: from datasets import load_dataset from transformers import AutoTokenizer SCREAMING_SNAKE_CASE__ : List[str] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {'train': 'tests/test_samples/MRPC/train.csv', 'validation': 'tests/test_samples/MRPC/dev.csv'} SCREAMING_SNAKE_CASE__ : Tuple = load_dataset("""csv""" , data_files=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = datasets['train'].unique("""label""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {v: i for i, v in enumerate(__lowerCAmelCase )} def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer( examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase , padding="""max_length""" ) if "label" in examples: SCREAMING_SNAKE_CASE__ : Tuple = [label_to_id[l] for l in examples['label']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""sentence1""", """sentence2""", """label"""] , ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__lowerCAmelCase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__lowerCAmelCase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : Tuple = DataLoader(tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=2 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = DataLoader(tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=1 ) return train_dataloader, eval_dataloader
716
"""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 _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Any: # Format the message. if name is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None else: SCREAMING_SNAKE_CASE__ : str = """.""" * max(0 , spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" SCREAMING_SNAKE_CASE__ : Dict = fmt.format(__lowerCAmelCase ) # Print and recurse (if needed). if isinstance(__lowerCAmelCase , __lowerCAmelCase ): if msg is not None: print(__lowerCAmelCase ) for k in val.keys(): recursive_print(__lowerCAmelCase , val[k] , spaces + 2 ) elif isinstance(__lowerCAmelCase , torch.Tensor ): print(__lowerCAmelCase , """:""" , val.size() ) else: print(__lowerCAmelCase , """:""" , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[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. SCREAMING_SNAKE_CASE__ : Tuple = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] SCREAMING_SNAKE_CASE__ : int = (num_heads, hidden_size, num_splits) + input_shape[1:] SCREAMING_SNAKE_CASE__ : List[str] = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = param.transpose(0 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] SCREAMING_SNAKE_CASE__ : List[str] = (num_heads, num_splits, hidden_size) + input_shape[1:] SCREAMING_SNAKE_CASE__ : Dict = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = param.transpose(0 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ : Any = param.view(*__lowerCAmelCase ) return param def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: # The converted output model. SCREAMING_SNAKE_CASE__ : List[str] = {} # old versions did not store training args SCREAMING_SNAKE_CASE__ : List[str] = input_state_dict.get("""args""" , __lowerCAmelCase ) 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)) SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.padded_vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = ds_args.max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = ds_args.num_layers SCREAMING_SNAKE_CASE__ : Dict = ds_args.num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = ds_args.ffn_hidden_size # pprint(config) # The number of heads. SCREAMING_SNAKE_CASE__ : List[str] = config.n_head # The hidden_size per head. SCREAMING_SNAKE_CASE__ : str = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_state_dict["""checkpoint_version"""] else: SCREAMING_SNAKE_CASE__ : Tuple = 0.0 # The model. SCREAMING_SNAKE_CASE__ : Any = input_state_dict["""model"""] # The language model. SCREAMING_SNAKE_CASE__ : Any = model["""language_model"""] # The embeddings. SCREAMING_SNAKE_CASE__ : str = lm["""embedding"""] # The word embeddings. SCREAMING_SNAKE_CASE__ : int = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. SCREAMING_SNAKE_CASE__ : Any = word_embeddings[: config.vocab_size, :] SCREAMING_SNAKE_CASE__ : Optional[int] = word_embeddings # The position embeddings. SCREAMING_SNAKE_CASE__ : Any = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] SCREAMING_SNAKE_CASE__ : Tuple = 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. SCREAMING_SNAKE_CASE__ : List[Any] = pos_embeddings # The transformer. SCREAMING_SNAKE_CASE__ : Union[str, Any] = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. SCREAMING_SNAKE_CASE__ : str = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. SCREAMING_SNAKE_CASE__ : Optional[int] = { """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. SCREAMING_SNAKE_CASE__ : str = layer_re.match(__lowerCAmelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. SCREAMING_SNAKE_CASE__ : Dict = int(m.group(1 ) ) # The name of the operation. SCREAMING_SNAKE_CASE__ : Optional[Any] = m.group(2 ) # Is it a weight or a bias? SCREAMING_SNAKE_CASE__ : str = m.group(3 ) # The name of the layer. SCREAMING_SNAKE_CASE__ : List[Any] = F'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): SCREAMING_SNAKE_CASE__ : Dict = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" SCREAMING_SNAKE_CASE__ : List[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. SCREAMING_SNAKE_CASE__ : Any = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = causal_mask # Insert a "dummy" tensor for masked_bias. SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor(-1E4 , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = masked_bias SCREAMING_SNAKE_CASE__ : List[str] = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. SCREAMING_SNAKE_CASE__ : str = out_val.transpose(0 , 1 ).contiguous() # Store. SCREAMING_SNAKE_CASE__ : Dict = 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": SCREAMING_SNAKE_CASE__ : Any = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Store. No change of shape. SCREAMING_SNAKE_CASE__ : str = out_val # Transpose the weights. elif weight_or_bias == "weight": SCREAMING_SNAKE_CASE__ : str = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : int = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": SCREAMING_SNAKE_CASE__ : int = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : Dict = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. SCREAMING_SNAKE_CASE__ : Union[str, Any] = transformer["""final_layernorm.weight"""] SCREAMING_SNAKE_CASE__ : str = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. SCREAMING_SNAKE_CASE__ : Tuple = word_embeddings # It should be done! return output_state_dict def _lowercase ( ) -> List[Any]: # Create the argument parser. SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""" , action="""store_true""" ) parser.add_argument( """path_to_checkpoint""" , type=__lowerCAmelCase , help="""Path to the checkpoint file (.zip archive or direct .pt file)""" , ) parser.add_argument( """--config_file""" , default="""""" , type=__lowerCAmelCase , help="""An optional config json file describing the pre-trained model.""" , ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() # Extract the basename. SCREAMING_SNAKE_CASE__ : Optional[int] = 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: SCREAMING_SNAKE_CASE__ : List[Any] = torch.load(__lowerCAmelCase , map_location="""cpu""" ) else: SCREAMING_SNAKE_CASE__ : str = torch.load(args.path_to_checkpoint , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : int = input_state_dict.get("""args""" , __lowerCAmelCase ) # 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: SCREAMING_SNAKE_CASE__ : Dict = """gelu_fast""" elif ds_args.openai_gelu: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu_new""" else: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" SCREAMING_SNAKE_CASE__ : Any = """gelu_new""" # Spell out all parameters in case the defaults change. SCREAMING_SNAKE_CASE__ : Union[str, Any] = GPTaConfig( vocab_size=5_0257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=__lowerCAmelCase , 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=__lowerCAmelCase , summary_activation=__lowerCAmelCase , summary_proj_to_labels=__lowerCAmelCase , summary_first_dropout=0.1 , scale_attn_weights=__lowerCAmelCase , use_cache=__lowerCAmelCase , bos_token_id=5_0256 , eos_token_id=5_0256 , ) else: SCREAMING_SNAKE_CASE__ : List[Any] = GPTaConfig.from_json_file(args.config_file ) SCREAMING_SNAKE_CASE__ : Tuple = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = convert_megatron_checkpoint(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(__lowerCAmelCase , __lowerCAmelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: SCREAMING_SNAKE_CASE__ : Tuple = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": SCREAMING_SNAKE_CASE__ : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": SCREAMING_SNAKE_CASE__ : Any = ds_args.tokenizer_name_or_path else: raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """gpt2""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = type(__lowerCAmelCase ).__name__ SCREAMING_SNAKE_CASE__ : Dict = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(__lowerCAmelCase ) # Save tokenizer based on args print(F'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(__lowerCAmelCase ) # Store the state_dict to file. SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , """pytorch_model.bin""" ) print(F'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
12
0
"""simple docstring""" 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 a :List[str] = logging.get_logger(__name__) a :int = { "EleutherAI/gpt-j-6B": "https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json", # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """gptj""" _SCREAMING_SNAKE_CASE :Union[str, Any] = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _a=50_400 , _a=2_048 , _a=4_096 , _a=28 , _a=16 , _a=64 , _a=None , _a="gelu_new" , _a=0.0 , _a=0.0 , _a=0.0 , _a=1E-5 , _a=0.02 , _a=True , _a=50_256 , _a=50_256 , _a=False , **_a , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = n_positions SCREAMING_SNAKE_CASE__ : Tuple = n_embd SCREAMING_SNAKE_CASE__ : List[str] = n_layer SCREAMING_SNAKE_CASE__ : Union[str, Any] = n_head SCREAMING_SNAKE_CASE__ : Optional[int] = n_inner SCREAMING_SNAKE_CASE__ : str = rotary_dim SCREAMING_SNAKE_CASE__ : Optional[Any] = activation_function SCREAMING_SNAKE_CASE__ : Optional[Any] = resid_pdrop SCREAMING_SNAKE_CASE__ : Dict = embd_pdrop SCREAMING_SNAKE_CASE__ : Optional[int] = attn_pdrop SCREAMING_SNAKE_CASE__ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : str = bos_token_id SCREAMING_SNAKE_CASE__ : int = eos_token_id super().__init__( bos_token_id=__A , eos_token_id=__A , tie_word_embeddings=__A , **__A ) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a = "default" , _a = None , _a = False , ) -> List[str]: """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__ : str = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(__A , direction="""inputs""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch""", 1: """past_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : Optional[Any] = {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 def _a ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 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__ : str = 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__ : str = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE__ : Optional[int] = seqlen + 2 SCREAMING_SNAKE_CASE__ : Tuple = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE__ : Any = [ (torch.zeros(__A ), torch.zeros(__A )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE__ : int = common_inputs["""attention_mask"""] if self.use_past: SCREAMING_SNAKE_CASE__ : int = ordered_inputs["""attention_mask"""].dtype SCREAMING_SNAKE_CASE__ : Any = 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
717
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class __a (UpperCamelCase_): '''simple docstring''' def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" with open(_a , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ : str = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = input_file.read() SCREAMING_SNAKE_CASE__ : str = regexp.search(_a ) return match def _a ( self , _a ) -> Optional[Any]: """simple docstring""" with open(_a , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ : Tuple = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) SCREAMING_SNAKE_CASE__ : List[Any] = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE__ : Dict = regexp.finditer(_a ) SCREAMING_SNAKE_CASE__ : int = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_a ) ): raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ : List[str] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(_a ) ): raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
12
0
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 ( __lowerCAmelCase="" ) -> int: SCREAMING_SNAKE_CASE__ : str = tempfile.mkdtemp() return os.path.join(_lowerCamelCase , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = torch.rand(12 , dtype=torch.floataa ) - 0.5 SCREAMING_SNAKE_CASE__ : str = AgentAudio(_lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(_lowercase , agent_type.to_raw() , atol=1E-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(_lowercase ) ) # Ensure that the file contains the same value as the original tensor SCREAMING_SNAKE_CASE__ : str = sf.read(_lowercase ) self.assertTrue(torch.allclose(_lowercase , torch.tensor(_lowercase ) , atol=1E-4 ) ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = torch.rand(12 , dtype=torch.floataa ) - 0.5 SCREAMING_SNAKE_CASE__ : Optional[int] = get_new_path(suffix=""".wav""" ) sf.write(_lowercase , _lowercase , 16_000 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AgentAudio(_lowercase ) self.assertTrue(torch.allclose(_lowercase , agent_type.to_raw() , atol=1E-4 ) ) self.assertEqual(agent_type.to_string() , _lowercase ) @require_vision @require_torch class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = torch.randint(0 , 256 , (64, 64, 3) ) SCREAMING_SNAKE_CASE__ : Dict = AgentImage(_lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(_lowercase , 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(_lowercase ) ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" SCREAMING_SNAKE_CASE__ : List[str] = Image.open(_lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] = AgentImage(_lowercase ) 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(_lowercase ) ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" SCREAMING_SNAKE_CASE__ : List[str] = Image.open(_lowercase ) SCREAMING_SNAKE_CASE__ : str = AgentImage(_lowercase ) 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(_lowercase ) ) class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = """Hey!""" SCREAMING_SNAKE_CASE__ : int = AgentText(_lowercase ) self.assertEqual(_lowercase , agent_type.to_string() ) self.assertEqual(_lowercase , agent_type.to_raw() ) self.assertEqual(_lowercase , _lowercase )
718
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class __a : '''simple docstring''' def __init__( self , _a , _a=99 , _a=13 , _a=7 , _a=9 , _a=True , _a=True , _a=False , _a=32 , _a=5 , _a=4 , _a=37 , _a=8 , _a=0.1 , _a=0.002 , _a=1 , _a=0 , _a=0 , _a=None , _a=None , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Tuple = encoder_seq_length SCREAMING_SNAKE_CASE__ : str = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE__ : Optional[int] = self.decoder_seq_length SCREAMING_SNAKE_CASE__ : Tuple = is_training SCREAMING_SNAKE_CASE__ : Dict = use_attention_mask SCREAMING_SNAKE_CASE__ : List[str] = use_labels SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = d_ff SCREAMING_SNAKE_CASE__ : Any = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor SCREAMING_SNAKE_CASE__ : List[Any] = eos_token_id SCREAMING_SNAKE_CASE__ : List[str] = pad_token_id SCREAMING_SNAKE_CASE__ : Any = decoder_start_token_id SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : str = decoder_layers def _a ( self ) -> Tuple: """simple docstring""" return TaConfig.from_pretrained("""google/umt5-base""" ) def _a ( self , _a , _a , _a , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> Any: """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : int = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE__ : str = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_a ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_a ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=_a ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input SCREAMING_SNAKE_CASE__ : Tuple = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config() SCREAMING_SNAKE_CASE__ : List[str] = config.num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_inputs_dict(_a , _a , _a ) return config, input_dict def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() return config, inputs_dict def _a ( self ) -> List[str]: """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self ) -> List[Any]: """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = UMTaModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model( input_ids=_a , decoder_input_ids=_a , attention_mask=_a , decoder_attention_mask=_a , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=_a , decoder_input_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = result.last_hidden_state SCREAMING_SNAKE_CASE__ : Dict = result.past_key_values SCREAMING_SNAKE_CASE__ : Any = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(_a ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).get_decoder().to(_a ).eval() # first forward pass SCREAMING_SNAKE_CASE__ : str = model(_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , use_cache=_a ) self.parent.assertTrue(len(_a ) == len(_a ) ) self.parent.assertTrue(len(_a ) == len(_a ) + 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : Tuple = model(_a , past_key_values=_a )["""last_hidden_state"""] # select random slice SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) ) def _a ( self , _a , _a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).to(_a ).half().eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**_a )["""last_hidden_state"""] self.parent.assertFalse(torch.isnan(_a ).any().item() ) @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :List[str] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Union[str, Any] = True _SCREAMING_SNAKE_CASE :Tuple = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = True _SCREAMING_SNAKE_CASE :List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _SCREAMING_SNAKE_CASE :Union[str, Any] = [0.8, 0.9] def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = UMTaModelTester(self ) @unittest.skip("""Test has a segmentation fault on torch 1.8.0""" ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = UMTaModel(config_and_inputs[0] ).to(_a ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( _a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=_a , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*_a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""] SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs[0] SCREAMING_SNAKE_CASE__ : Tuple = UMTaForConditionalGeneration(_a ).eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = { """head_mask""": torch.zeros(config.num_layers , config.num_heads , device=_a ), """decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), } for attn_name, (name, mask) in zip(_a , head_masking.items() ): SCREAMING_SNAKE_CASE__ : List[str] = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": SCREAMING_SNAKE_CASE__ : str = torch.ones( config.num_decoder_layers , config.num_heads , device=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.generate( config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=_a , return_dict_in_generate=_a , **_a , ) # We check the state of decoder_attentions and cross_attentions just from the last step SCREAMING_SNAKE_CASE__ : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" ) def _a ( self ) -> Dict: """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow @unittest.skip( """Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=_a ).to(_a ) SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=_a , legacy=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ """Bonjour monsieur <extra_id_0> bien <extra_id_1>.""", """No se como puedo <extra_id_0>.""", """This is the reason why we <extra_id_0> them.""", """The <extra_id_0> walks in <extra_id_1>, seats""", """A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""", ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_a , return_tensors="""pt""" , padding=_a ).input_ids # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(_a , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids.to(_a ) ) SCREAMING_SNAKE_CASE__ : int = [ """<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""", """<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", ] SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.batch_decode(_a ) self.assertEqual(_a , _a )
12
0
a :Any = [ 'DownloadConfig', 'DownloadManager', 'DownloadMode', 'StreamingDownloadManager', ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
719
"""simple docstring""" import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a , _a = None , _a = None , _a = False , **_a , ) -> Union[str, Any]: """simple docstring""" super().__init__(features=_a , cache_dir=_a , keep_in_memory=_a , **_a ) SCREAMING_SNAKE_CASE__ : List[Any] = Sql( cache_dir=_a , features=_a , sql=_a , con=_a , **_a , ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None self.builder.download_and_prepare( download_config=_a , download_mode=_a , verification_mode=_a , base_path=_a , ) # Build dataset for splits SCREAMING_SNAKE_CASE__ : str = self.builder.as_dataset( split="""train""" , verification_mode=_a , in_memory=self.keep_in_memory ) return dataset class __a : '''simple docstring''' def __init__( self , _a , _a , _a , _a = None , _a = None , **_a , ) -> Any: """simple docstring""" if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) SCREAMING_SNAKE_CASE__ : int = dataset SCREAMING_SNAKE_CASE__ : Any = name SCREAMING_SNAKE_CASE__ : Optional[Any] = con SCREAMING_SNAKE_CASE__ : List[Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE SCREAMING_SNAKE_CASE__ : int = num_proc SCREAMING_SNAKE_CASE__ : int = to_sql_kwargs def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.to_sql_kwargs.pop("""sql""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = self.to_sql_kwargs.pop("""con""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = self.to_sql_kwargs.pop("""index""" , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._write(index=_a , **self.to_sql_kwargs ) return written def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = args SCREAMING_SNAKE_CASE__ : List[str] = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs SCREAMING_SNAKE_CASE__ : Any = query_table( table=self.dataset.data , key=slice(_a , offset + self.batch_size ) , indices=self.dataset._indices , ) SCREAMING_SNAKE_CASE__ : Optional[int] = batch.to_pandas() SCREAMING_SNAKE_CASE__ : List[Any] = df.to_sql(self.name , self.con , index=_a , **_a ) return num_rows or len(_a ) def _a ( self , _a , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _a , _a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available a :Union[str, Any] = { "configuration_longt5": ["LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongT5Config", "LongT5OnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[str] = [ "LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST", "LongT5EncoderModel", "LongT5ForConditionalGeneration", "LongT5Model", "LongT5PreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Tuple = [ "FlaxLongT5ForConditionalGeneration", "FlaxLongT5Model", "FlaxLongT5PreTrainedModel", ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys a :List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
720
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : int = 1 while repunit: SCREAMING_SNAKE_CASE__ : str = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def _lowercase ( __lowerCAmelCase = 100_0000 ) -> int: SCREAMING_SNAKE_CASE__ : Dict = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(__lowerCAmelCase ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable a :Any = {"""configuration_dpt""": ["""DPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DPTConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[Any] = ["""DPTFeatureExtractor"""] a :int = ["""DPTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Tuple = [ """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 a :Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
721
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") a :Union[str, Any] = logging.getLogger(__name__) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of prediction examples to this """ """value if set.""" ) } , ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}) _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Train language if it is different from the evaluation language."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) _SCREAMING_SNAKE_CASE :Optional[bool] = field( default=UpperCamelCase_ , metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) _SCREAMING_SNAKE_CASE :str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def _lowercase ( ) -> Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE__ : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_xnli""" , __lowerCAmelCase ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : List[Any] = training_args.get_process_log_level() logger.setLevel(__lowerCAmelCase ) datasets.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__ : Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__ : Optional[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: SCREAMING_SNAKE_CASE__ : Optional[int] = load_dataset( """xnli""" , model_args.language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: SCREAMING_SNAKE_CASE__ : str = load_dataset( """xnli""" , model_args.train_language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = train_dataset.features["""label"""].names if training_args.do_eval: SCREAMING_SNAKE_CASE__ : int = load_dataset( """xnli""" , model_args.language , split="""validation""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.features["""label"""].names if training_args.do_predict: SCREAMING_SNAKE_CASE__ : int = load_dataset( """xnli""" , model_args.language , split="""test""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Tuple = predict_dataset.features["""label"""].names # Labels SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__lowerCAmelCase , idalabel={str(__lowerCAmelCase ): label for i, label in enumerate(__lowerCAmelCase )} , labelaid={label: i for i, label in enumerate(__lowerCAmelCase )} , finetuning_task="""xnli""" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : str = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : str = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch SCREAMING_SNAKE_CASE__ : Optional[Any] = False def preprocess_function(__lowerCAmelCase ): # Tokenize the texts return tokenizer( examples["""premise"""] , examples["""hypothesis"""] , padding=__lowerCAmelCase , max_length=data_args.max_seq_length , truncation=__lowerCAmelCase , ) if training_args.do_train: if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(len(__lowerCAmelCase ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE__ : str = train_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : List[str] = train_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on train dataset""" , ) # Log a few random samples from the training set: for index in random.sample(range(len(__lowerCAmelCase ) ) , 3 ): logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.''' ) if training_args.do_eval: if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__ : Any = min(len(__lowerCAmelCase ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : List[str] = eval_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on validation dataset""" , ) if training_args.do_predict: if data_args.max_predict_samples is not None: SCREAMING_SNAKE_CASE__ : int = min(len(__lowerCAmelCase ) , data_args.max_predict_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = predict_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""prediction dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : Tuple = predict_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on prediction dataset""" , ) # Get the metric function SCREAMING_SNAKE_CASE__ : Optional[Any] = evaluate.load("""xnli""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Dict = p.predictions[0] if isinstance(p.predictions , __lowerCAmelCase ) else p.predictions SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.argmax(__lowerCAmelCase , axis=1 ) return metric.compute(predictions=__lowerCAmelCase , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : List[Any] = default_data_collator elif training_args.fpaa: SCREAMING_SNAKE_CASE__ : int = DataCollatorWithPadding(__lowerCAmelCase , pad_to_multiple_of=8 ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # Initialize our Trainer SCREAMING_SNAKE_CASE__ : Union[str, Any] = Trainer( model=__lowerCAmelCase , args=__lowerCAmelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , data_collator=__lowerCAmelCase , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__ : Dict = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = last_checkpoint SCREAMING_SNAKE_CASE__ : str = trainer.train(resume_from_checkpoint=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = train_result.metrics SCREAMING_SNAKE_CASE__ : Optional[int] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Dict = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , __lowerCAmelCase ) trainer.save_metrics("""train""" , __lowerCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE__ : Any = trainer.evaluate(eval_dataset=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""eval""" , __lowerCAmelCase ) trainer.save_metrics("""eval""" , __lowerCAmelCase ) # Prediction if training_args.do_predict: logger.info("""*** Predict ***""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = trainer.predict(__lowerCAmelCase , metric_key_prefix="""predict""" ) SCREAMING_SNAKE_CASE__ : List[str] = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : int = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""predict""" , __lowerCAmelCase ) trainer.save_metrics("""predict""" , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = np.argmax(__lowerCAmelCase , axis=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(training_args.output_dir , """predictions.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCAmelCase , """w""" ) as writer: writer.write("""index\tprediction\n""" ) for index, item in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = label_list[item] writer.write(F'''{index}\t{item}\n''' ) if __name__ == "__main__": main()
12
0
"""simple docstring""" from __future__ import annotations import typing from collections.abc import Iterable import numpy as np a :Union[str, Any] = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 a :List[Any] = typing.Union[np.floataa, int, float] # noqa: UP007 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: return np.sqrt(np.sum((np.asarray(__lowerCAmelCase ) - np.asarray(__lowerCAmelCase )) ** 2 ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: return sum((va - va) ** 2 for va, va in zip(__lowerCAmelCase , __lowerCAmelCase ) ) ** (1 / 2) if __name__ == "__main__": def _lowercase ( ) -> int: from timeit import timeit print("""Without Numpy""" ) print( timeit( """euclidean_distance_no_np([1, 2, 3], [4, 5, 6])""" , number=1_0000 , globals=globals() , ) ) print("""With Numpy""" ) print( timeit( """euclidean_distance([1, 2, 3], [4, 5, 6])""" , number=1_0000 , globals=globals() , ) ) benchmark()
700
"""simple docstring""" # Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() a :str = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model a :int = { # fairseq: "wmt19-ru-en": {"length_penalty": 1.1}, "wmt19-en-ru": {"length_penalty": 1.15}, "wmt19-en-de": {"length_penalty": 1.0}, "wmt19-de-en": {"length_penalty": 1.1}, # allenai: "wmt16-en-de-dist-12-1": {"length_penalty": 0.6}, "wmt16-en-de-dist-6-1": {"length_penalty": 0.6}, "wmt16-en-de-12-1": {"length_penalty": 0.8}, "wmt19-de-en-6-6-base": {"length_penalty": 0.6}, "wmt19-de-en-6-6-big": {"length_penalty": 0.6}, } # this remaps the different models to their organization names a :Dict = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: a :List[Any] = "facebook" for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: a :str = "allenai" def _lowercase ( __lowerCAmelCase ) -> Any: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} SCREAMING_SNAKE_CASE__ : str = dict((re.sub(r"""@@$""" , """""" , __lowerCAmelCase ), v) if k.endswith("""@@""" ) else (re.sub(r"""$""" , """</w>""" , __lowerCAmelCase ), v) for k, v in d.items() ) SCREAMING_SNAKE_CASE__ : Tuple = """<s> <pad> </s> <unk>""".split() # restore the special tokens for k in keep_keys: del da[F'''{k}</w>'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] = d[k] # restore return da def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: # prep assert os.path.exists(__lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) print(F'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models SCREAMING_SNAKE_CASE__ : Optional[Any] = basename(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = dirname(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel SCREAMING_SNAKE_CASE__ : Optional[int] = cls.hub_models() SCREAMING_SNAKE_CASE__ : Optional[int] = {"""bpe""": """fastbpe""", """tokenizer""": """moses"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = """.""" # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(F'''using checkpoint {checkpoint_file}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = hub_utils.from_pretrained( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , archive_map=__lowerCAmelCase , **__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = vars(chkpt["""args"""]["""model"""] ) SCREAMING_SNAKE_CASE__ : Any = args["""source_lang"""] SCREAMING_SNAKE_CASE__ : Any = args["""target_lang"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = dirname(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = basename(__lowerCAmelCase ) # dicts SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(__lowerCAmelCase , F'''dict.{src_lang}.txt''' ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , F'''dict.{tgt_lang}.txt''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Dictionary.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = rewrite_dict_keys(src_dict.indices ) SCREAMING_SNAKE_CASE__ : Optional[int] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , """vocab-src.json""" ) print(F'''Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab SCREAMING_SNAKE_CASE__ : Optional[Any] = True for k in src_vocab.keys(): if not k.islower(): SCREAMING_SNAKE_CASE__ : Tuple = False break SCREAMING_SNAKE_CASE__ : Optional[Any] = Dictionary.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rewrite_dict_keys(tgt_dict.indices ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , """vocab-tgt.json""" ) print(F'''Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # merges_file (bpecodes) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , VOCAB_FILES_NAMES["""merges_file"""] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if os.path.exists(__lowerCAmelCase ): break with open(__lowerCAmelCase , encoding="""utf-8""" ) as fin: SCREAMING_SNAKE_CASE__ : Any = fin.read() SCREAMING_SNAKE_CASE__ : Tuple = re.sub(r""" \d+$""" , """""" , __lowerCAmelCase , 0 , re.M ) # remove frequency number print(F'''Generating {merges_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as fout: fout.write(__lowerCAmelCase ) # model config SCREAMING_SNAKE_CASE__ : Dict = os.path.join(__lowerCAmelCase , """config.json""" ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", F'''need to extend tokenizer to support bpe={args['bpe']}''' assert args["tokenizer"] == "moses", F'''need to extend tokenizer to support bpe={args['tokenizer']}''' SCREAMING_SNAKE_CASE__ : str = { """architectures""": ["""FSMTForConditionalGeneration"""], """model_type""": """fsmt""", """activation_dropout""": args["""activation_dropout"""], """activation_function""": """relu""", """attention_dropout""": args["""attention_dropout"""], """d_model""": args["""decoder_embed_dim"""], """dropout""": args["""dropout"""], """init_std""": 0.02, """max_position_embeddings""": args["""max_source_positions"""], """num_hidden_layers""": args["""encoder_layers"""], """src_vocab_size""": src_vocab_size, """tgt_vocab_size""": tgt_vocab_size, """langs""": [src_lang, tgt_lang], """encoder_attention_heads""": args["""encoder_attention_heads"""], """encoder_ffn_dim""": args["""encoder_ffn_embed_dim"""], """encoder_layerdrop""": args["""encoder_layerdrop"""], """encoder_layers""": args["""encoder_layers"""], """decoder_attention_heads""": args["""decoder_attention_heads"""], """decoder_ffn_dim""": args["""decoder_ffn_embed_dim"""], """decoder_layerdrop""": args["""decoder_layerdrop"""], """decoder_layers""": args["""decoder_layers"""], """bos_token_id""": 0, """pad_token_id""": 1, """eos_token_id""": 2, """is_encoder_decoder""": True, """scale_embedding""": not args["""no_scale_embedding"""], """tie_word_embeddings""": args["""share_all_embeddings"""], } # good hparam defaults to start with SCREAMING_SNAKE_CASE__ : Tuple = 5 SCREAMING_SNAKE_CASE__ : str = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: SCREAMING_SNAKE_CASE__ : Tuple = best_score_hparams[model_dir]["""length_penalty"""] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 1.0 print(F'''Generating {fsmt_model_config_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # tokenizer config SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = { """langs""": [src_lang, tgt_lang], """model_max_length""": 1024, """do_lower_case""": do_lower_case, } print(F'''Generating {fsmt_tokenizer_config_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # model SCREAMING_SNAKE_CASE__ : Dict = chkpt["""models"""][0] SCREAMING_SNAKE_CASE__ : int = model.state_dict() # rename keys to start with 'model.' SCREAMING_SNAKE_CASE__ : Tuple = OrderedDict(("""model.""" + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys SCREAMING_SNAKE_CASE__ : str = [ """model.model""", """model.encoder.version""", """model.decoder.version""", """model.encoder_embed_tokens.weight""", """model.decoder_embed_tokens.weight""", """model.encoder.embed_positions._float_tensor""", """model.decoder.embed_positions._float_tensor""", ] for k in ignore_keys: model_state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = FSMTConfig.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = FSMTForConditionalGeneration(__lowerCAmelCase ) # check that it loads ok model_new.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase ) # save SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) print(F'''Generating {pytorch_weights_dump_path}''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) print("""Conversion is done!""" ) print("""\nLast step is to upload the files to s3""" ) print(F'''cd {data_root}''' ) print(F'''transformers-cli upload {model_dir}''' ) if __name__ == "__main__": a :Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fsmt_checkpoint_path", default=None, type=str, required=True, help=( "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts," " bpecodes, etc." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) a :List[str] = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
12
0
"""simple docstring""" import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging a :Optional[Any] = logging.get_logger(__name__) a :int = {"vocab_file": "vocab.txt"} a :Optional[int] = { "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } a :Optional[int] = { "facebook/esm2_t6_8M_UR50D": 1_024, "facebook/esm2_t12_35M_UR50D": 1_024, } def _lowercase ( __lowerCAmelCase ) -> List[Any]: with open(SCREAMING_SNAKE_CASE_ , """r""" ) as f: SCREAMING_SNAKE_CASE__ : Tuple = f.read().splitlines() return [l.strip() for l in lines] class __a (_UpperCAmelCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Optional[int] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :Any = ["""input_ids""", """attention_mask"""] def __init__( self , _a , _a="<unk>" , _a="<cls>" , _a="<pad>" , _a="<mask>" , _a="<eos>" , **_a , ) -> Tuple: """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = load_vocab_file(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE__ : Any = unk_token SCREAMING_SNAKE_CASE__ : str = cls_token SCREAMING_SNAKE_CASE__ : Dict = pad_token SCREAMING_SNAKE_CASE__ : Tuple = mask_token SCREAMING_SNAKE_CASE__ : Any = eos_token SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _a ( self , _a ) -> str: """simple docstring""" return self._id_to_token.get(lowercase__ , self.unk_token ) def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" return self._token_to_id.get(lowercase__ , self._token_to_id.get(self.unk_token ) ) def _a ( self , _a , **_a ) -> Any: """simple docstring""" return text.split() def _a ( self , _a=False ) -> Tuple: """simple docstring""" return len(self._id_to_token ) def _a ( self ) -> Optional[int]: """simple docstring""" return {token: i for i, token in enumerate(self.all_tokens )} def _a ( self , _a ) -> Any: """simple docstring""" return self._token_to_id.get(lowercase__ , self._token_to_id.get(self.unk_token ) ) def _a ( self , _a ) -> List[Any]: """simple docstring""" return self._id_to_token.get(lowercase__ , self.unk_token ) def _a ( self , _a , _a = None ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError("""Cannot tokenize multiple sequences when EOS token is not set!""" ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _a ( self , _a , _a = None , _a = False ) -> Optional[int]: """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [1] + ([0] * len(lowercase__ )) + [1] if token_ids_a is not None: mask += [0] * len(lowercase__ ) + [1] return mask def _a ( self , _a , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(lowercase__ , (filename_prefix + """-""" if filename_prefix else """""") + """vocab.txt""" ) with open(lowercase__ , """w""" ) as f: f.write("""\n""".join(self.all_tokens ) ) return (vocab_file,) @property def _a ( self ) -> List[Any]: """simple docstring""" return self.get_vocab_size(with_added_tokens=lowercase__ ) def _a ( self , _a , _a = False ) -> List[Any]: """simple docstring""" return super()._add_tokens(lowercase__ , special_tokens=lowercase__ )
701
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = (DDPMScheduler,) def _a ( self , **_a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**_a ) return config def _a ( self ) -> str: """simple docstring""" for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def _a ( self ) -> str: """simple docstring""" for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def _a ( self ) -> Any: """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def _a ( self ) -> int: """simple docstring""" self.check_over_configs(thresholding=_a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , ) def _a ( self ) -> str: """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def _a ( self ) -> str: """simple docstring""" for t in [0, 500, 999]: self.check_over_forward(time_step=_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Any = len(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : str = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : int = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : str = pred_prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.9_606 ) < 1E-2 assert abs(result_mean.item() - 0.3_372 ) < 1E-3 def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Tuple = self.get_scheduler_config(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Dict = len(_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : int = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : Tuple = pred_prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : int = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 202.0_296 ) < 1E-2 assert abs(result_mean.item() - 0.2_631 ) < 1E-3 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = -1 else: SCREAMING_SNAKE_CASE__ : Tuple = timesteps[i + 1] SCREAMING_SNAKE_CASE__ : int = scheduler.previous_timestep(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prev_t.item() self.assertEqual(_a , _a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [100, 87, 50, 51, 0] with self.assertRaises(_a , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : int = [100, 87, 50, 1, 0] SCREAMING_SNAKE_CASE__ : List[str] = len(_a ) with self.assertRaises(_a , msg="""Can only pass one of `num_inference_steps` or `custom_timesteps`.""" ): scheduler.set_timesteps(num_inference_steps=_a , timesteps=_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( _a , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=_a )
12
0
"""simple docstring""" import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup a :Dict = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def _lowercase ( __lowerCAmelCase = "dhaka" , __lowerCAmelCase = 5 ) -> int: SCREAMING_SNAKE_CASE__ : List[str] = min(SCREAMING_SNAKE_CASE_ , 50 ) # Prevent abuse! SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'q': query, 'tbm': 'isch', 'hl': 'en', 'ijn': '0', } SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get("""https://www.google.com/search""" , params=SCREAMING_SNAKE_CASE_ , headers=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = BeautifulSoup(html.text , """html.parser""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ''.join( re.findall(r"""AF_initDataCallback\(([^<]+)\);""" , str(soup.select("""script""" ) ) ) ) SCREAMING_SNAKE_CASE__ : List[str] = json.dumps(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : Any = json.loads(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : str = re.findall( r"""\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",""" , SCREAMING_SNAKE_CASE_ , ) if not matched_google_image_data: return 0 SCREAMING_SNAKE_CASE__ : Dict = re.sub( r"""\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]""" , """""" , str(SCREAMING_SNAKE_CASE_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = re.findall( r"""(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]""" , SCREAMING_SNAKE_CASE_ , ) for index, fixed_full_res_image in enumerate(SCREAMING_SNAKE_CASE_ ): if index >= max_images: return index SCREAMING_SNAKE_CASE__ : Any = bytes(SCREAMING_SNAKE_CASE_ , """ascii""" ).decode( """unicode-escape""" ) SCREAMING_SNAKE_CASE__ : Tuple = bytes(SCREAMING_SNAKE_CASE_ , """ascii""" ).decode( """unicode-escape""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = urllib.request.build_opener() SCREAMING_SNAKE_CASE__ : Optional[int] = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582', ) ] urllib.request.install_opener(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : str = F'''query_{query.replace(' ' , '_' )}''' if not os.path.exists(SCREAMING_SNAKE_CASE_ ): os.makedirs(SCREAMING_SNAKE_CASE_ ) urllib.request.urlretrieve( # noqa: S310 SCREAMING_SNAKE_CASE_ , F'''{path_name}/original_size_img_{index}.jpg''' ) return index if __name__ == "__main__": try: a :Any = download_images_from_google_query(sys.argv[1]) print(f'{image_count} images were downloaded to disk.') except IndexError: print("Please provide a search term.") raise
702
"""simple docstring""" import os a :List[str] = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1_000} def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 while index < len(__lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE__ : List[Any] = SYMBOLS[numerals[index]] SCREAMING_SNAKE_CASE__ : Dict = 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 _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = """""" SCREAMING_SNAKE_CASE__ : int = num // 1000 numerals += m_count * "M" num %= 1000 SCREAMING_SNAKE_CASE__ : List[str] = 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 SCREAMING_SNAKE_CASE__ : List[Any] = 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 _lowercase ( __lowerCAmelCase = "/p089_roman.txt" ) -> int: SCREAMING_SNAKE_CASE__ : int = 0 with open(os.path.dirname(__lowerCAmelCase ) + roman_numerals_filename ) as filea: SCREAMING_SNAKE_CASE__ : str = filea.readlines() for line in lines: SCREAMING_SNAKE_CASE__ : Union[str, Any] = line.strip() SCREAMING_SNAKE_CASE__ : Dict = parse_roman_numerals(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = generate_roman_numerals(__lowerCAmelCase ) savings += len(__lowerCAmelCase ) - len(__lowerCAmelCase ) return savings if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: '''simple docstring''' while second != 0: SCREAMING_SNAKE_CASE__ : List[str] = first & second first ^= second SCREAMING_SNAKE_CASE__ : str = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() a :Tuple = int(input("Enter the first number: ").strip()) a :Tuple = int(input("Enter the second number: ").strip()) print(f'{add(first, second) = }')
703
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) SCREAMING_SNAKE_CASE__ : Any = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 25_543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : List[str] = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , _a ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Optional[int] = tf.convert_to_tensor( [[[-0.0_254, 0.0_235, 0.1_027], [0.0_606, -0.1_811, -0.0_418], [-0.1_561, -0.1_127, 0.2_687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable a :Dict = { "configuration_gpt_neox_japanese": ["GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXJapaneseConfig"], "tokenization_gpt_neox_japanese": ["GPTNeoXJapaneseTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Tuple = [ "GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXJapaneseForCausalLM", "GPTNeoXJapaneseLayer", "GPTNeoXJapaneseModel", "GPTNeoXJapanesePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
704
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a :List[Any] = logging.get_logger(__name__) a :Optional[int] = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """focalnet""" def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=False , _a=[192, 384, 768, 768] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1E-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1E-5 , _a=32 , _a=None , _a=None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : str = patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = embed_dim SCREAMING_SNAKE_CASE__ : List[str] = use_conv_embed SCREAMING_SNAKE_CASE__ : List[str] = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Any = focal_levels SCREAMING_SNAKE_CASE__ : Optional[Any] = focal_windows SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : str = use_layerscale SCREAMING_SNAKE_CASE__ : int = layerscale_value SCREAMING_SNAKE_CASE__ : Optional[int] = use_post_layernorm SCREAMING_SNAKE_CASE__ : Any = use_post_layernorm_in_modulation SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize_modulator SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = encoder_stride SCREAMING_SNAKE_CASE__ : Optional[int] = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
12
0
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : List[str] = """""" try: with open(lowerCAmelCase__ , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : str = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: lexicon.pop(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Any = last_match_id if math.loga(lowerCAmelCase__ ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Any = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : Dict = bin(lowerCAmelCase__ )[2:] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : str = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : str = len(lowerCAmelCase__ ) for i in range(len(lowerCAmelCase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Dict = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) index += 1 SCREAMING_SNAKE_CASE__ : Any = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(lowerCAmelCase__ )[2:] SCREAMING_SNAKE_CASE__ : int = len(lowerCAmelCase__ ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Dict: SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowerCAmelCase__ , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ to_write[i : i + byte_length] for i in range(0 , len(lowerCAmelCase__ ) , lowerCAmelCase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(lowerCAmelCase__ , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : int = read_file_binary(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : str = compress_data(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = add_file_length(lowerCAmelCase__ , lowerCAmelCase__ ) write_file_binary(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
705
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __a (unittest.TestCase): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_attention_mask SCREAMING_SNAKE_CASE__ : Tuple = use_token_type_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = num_choices def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE__ : int = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = True _SCREAMING_SNAKE_CASE :Optional[Any] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerModelTester(self ) @slow def _a ( self ) -> int: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a ) @require_flax class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.array([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ : str = model(_a )[0] SCREAMING_SNAKE_CASE__ : List[Any] = 50_000 SCREAMING_SNAKE_CASE__ : Optional[Any] = (1, 6, vocab_size) self.assertEqual(output.shape , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
12
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __a (unittest.TestCase): '''simple docstring''' def __init__( self , _a , _a=7 , _a=3 , _a=18 , _a=30 , _a=400 , _a=True , _a=None , _a=True , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Optional[int] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Tuple = max_resolution SCREAMING_SNAKE_CASE__ : Tuple = do_resize SCREAMING_SNAKE_CASE__ : Dict = size SCREAMING_SNAKE_CASE__ : List[str] = apply_ocr def _a ( self ) -> Tuple: """simple docstring""" return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __a (__lowerCamelCase , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = LayoutLMvaImageProcessingTester(self ) @property def _a ( self ) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , """do_resize""" ) ) self.assertTrue(hasattr(a_ , """size""" ) ) self.assertTrue(hasattr(a_ , """apply_ocr""" ) ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) SCREAMING_SNAKE_CASE__ : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def _a ( self ) -> Tuple: """simple docstring""" pass def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) self.assertIsInstance(encoding.words , a_ ) self.assertIsInstance(encoding.boxes , a_ ) # Test batched SCREAMING_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.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) # Test not batched input SCREAMING_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.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched SCREAMING_SNAKE_CASE__ : 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.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, 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.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched SCREAMING_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.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = LayoutLMvaImageProcessor() from datasets import load_dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""hf-internal-testing/fixtures_docvqa""" , split="""test""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.open(ds[0]["""file"""] ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : List[Any] = image_processing(a_ , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 SCREAMING_SNAKE_CASE__ : List[Any] = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 SCREAMING_SNAKE_CASE__ : Tuple = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , a_ ) self.assertListEqual(encoding.boxes , a_ ) # with apply_OCR = False SCREAMING_SNAKE_CASE__ : List[str] = LayoutLMvaImageProcessor(apply_ocr=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = image_processing(a_ , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
706
"""simple docstring""" a :List[str] = [ (1_000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1000} SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 while place < len(__lowerCAmelCase ): if (place + 1 < len(__lowerCAmelCase )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = [] for arabic, roman in ROMAN: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : List[str] = divmod(__lowerCAmelCase , __lowerCAmelCase ) result.append(roman * factor ) if number == 0: break return "".join(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ["""a""", """b""", """c"""] # Defaults to last layer if both are None SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_aligned_output_features_output_indices(_a , _a , _a ) self.assertEqual(_a , ["""c"""] ) self.assertEqual(_a , [2] ) # Out indices set to match out features SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = get_aligned_output_features_output_indices(["""a""", """c"""] , _a , _a ) self.assertEqual(_a , ["""a""", """c"""] ) self.assertEqual(_a , [0, 2] ) # Out features set to match out indices SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = get_aligned_output_features_output_indices(_a , [0, 2] , _a ) self.assertEqual(_a , ["""a""", """c"""] ) self.assertEqual(_a , [0, 2] ) # Out features selected from negative indices SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_aligned_output_features_output_indices(_a , [-3, -1] , _a ) self.assertEqual(_a , ["""a""", """c"""] ) self.assertEqual(_a , [-3, -1] ) def _a ( self ) -> List[str]: """simple docstring""" with self.assertRaises(_a ): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , _a ) # Out features must be a list with self.assertRaises(_a ): verify_out_features_out_indices(("""a""", """b""") , (0, 1) , ["""a""", """b"""] ) # Out features must be a subset of stage names with self.assertRaises(_a ): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , ["""a"""] ) # Out indices must be a list or tuple with self.assertRaises(_a ): verify_out_features_out_indices(_a , 0 , ["""a""", """b"""] ) # Out indices must be a subset of stage names with self.assertRaises(_a ): verify_out_features_out_indices(_a , (0, 1) , ["""a"""] ) # Out features and out indices must be the same length with self.assertRaises(_a ): verify_out_features_out_indices(["""a""", """b"""] , (0,) , ["""a""", """b""", """c"""] ) # Out features should match out indices with self.assertRaises(_a ): verify_out_features_out_indices(["""a""", """b"""] , (0, 2) , ["""a""", """b""", """c"""] ) # Out features and out indices should be in order with self.assertRaises(_a ): verify_out_features_out_indices(["""b""", """a"""] , (0, 1) , ["""a""", """b"""] ) # Check passes with valid inputs verify_out_features_out_indices(["""a""", """b""", """d"""] , (0, 1, -1) , ["""a""", """b""", """c""", """d"""] ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = BackboneMixin() SCREAMING_SNAKE_CASE__ : str = ["""a""", """b""", """c"""] SCREAMING_SNAKE_CASE__ : str = ["""a""", """c"""] SCREAMING_SNAKE_CASE__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["""a""", """c"""] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly SCREAMING_SNAKE_CASE__ : Optional[Any] = ["""a""", """b"""] self.assertEqual(backbone.out_features , ["""a""", """b"""] ) self.assertEqual(backbone.out_indices , [0, 1] ) SCREAMING_SNAKE_CASE__ : Tuple = [-3, -1] self.assertEqual(backbone.out_features , ["""a""", """c"""] ) self.assertEqual(backbone.out_indices , [-3, -1] )
707
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a :Any = { "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig", "RobertaPreLayerNormOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Union[str, Any] = [ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[Any] = [ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = [ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a :Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Tuple = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :int = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
708
"""simple docstring""" 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 IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : Dict = 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__ : Optional[Any] = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073], """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711], } SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_a , _a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> Any: """simple docstring""" return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **_a ) def _a ( self ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Optional[int] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=_a ) SCREAMING_SNAKE_CASE__ : int = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = AlignProcessor.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 _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[str] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(images=_a , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Any = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(text=_a ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(_a , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = 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 _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.batch_decode(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[str] = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
12
0
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: if not (isinstance(A_ , A_ ) and isinstance(A_ , A_ )): raise ValueError("""longest_common_substring() takes two strings for inputs""" ) SCREAMING_SNAKE_CASE__ : List[str] = len(A_ ) SCREAMING_SNAKE_CASE__ : List[str] = len(A_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[0] * (texta_length + 1) for _ in range(texta_length + 1 )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 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__ : int = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: SCREAMING_SNAKE_CASE__ : Tuple = i SCREAMING_SNAKE_CASE__ : Tuple = dp[i][j] return texta[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
709
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging a :Optional[Any] = logging.get_logger(__name__) a :Union[str, Any] = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """t5""" _SCREAMING_SNAKE_CASE :List[str] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Any = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self , _a=32_128 , _a=512 , _a=64 , _a=2_048 , _a=6 , _a=None , _a=8 , _a=32 , _a=128 , _a=0.1 , _a=1E-6 , _a=1.0 , _a="relu" , _a=True , _a=True , _a=0 , _a=1 , **_a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = d_model SCREAMING_SNAKE_CASE__ : int = d_kv SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_ff SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_layers SCREAMING_SNAKE_CASE__ : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry SCREAMING_SNAKE_CASE__ : Tuple = num_heads SCREAMING_SNAKE_CASE__ : Dict = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : str = relative_attention_max_distance SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_factor SCREAMING_SNAKE_CASE__ : Tuple = feed_forward_proj SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : List[str] = self.feed_forward_proj.split("""-""" ) SCREAMING_SNAKE_CASE__ : Dict = act_info[-1] SCREAMING_SNAKE_CASE__ : str = act_info[0] == """gated""" if len(_a ) > 1 and act_info[0] != "gated" or len(_a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": SCREAMING_SNAKE_CASE__ : List[Any] = """gelu_new""" super().__init__( pad_token_id=_a , eos_token_id=_a , is_encoder_decoder=_a , **_a , ) class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: SCREAMING_SNAKE_CASE__ : Tuple = """past_encoder_sequence + sequence""" SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch"""} SCREAMING_SNAKE_CASE__ : Tuple = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : str = {0: """batch""", 1: """decoder_sequence"""} SCREAMING_SNAKE_CASE__ : Dict = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_a , direction="""inputs""" ) return common_inputs @property def _a ( self ) -> int: """simple docstring""" return 13
12
0
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : int = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) SCREAMING_SNAKE_CASE__ : list = [] for char_count in range(__lowerCAmelCase ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(__lowerCAmelCase ) if __name__ == "__main__": print(alternative_string_arrange("AB", "XYZ"), end=" ")
710
"""simple docstring""" from __future__ import annotations import time import numpy as np a :Optional[Any] = [8, 5, 9, 7] a :List[Any] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] a :int = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class __a : '''simple docstring''' def __init__( self , _a , _a , _a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = claim_vector SCREAMING_SNAKE_CASE__ : Any = allocated_resources_table SCREAMING_SNAKE_CASE__ : Any = maximum_claim_table def _a ( self ) -> list[int]: """simple docstring""" return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def _a ( self ) -> list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def _a ( self ) -> list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(_a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def _a ( self ) -> dict[int, list[int]]: """simple docstring""" return {self.__need().index(_a ): i for i in self.__need()} def _a ( self , **_a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.__need() SCREAMING_SNAKE_CASE__ : Any = self.__allocated_resources_table SCREAMING_SNAKE_CASE__ : Dict = self.__available_resources() SCREAMING_SNAKE_CASE__ : Dict = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 50 + """\n""" ) while need_list: SCREAMING_SNAKE_CASE__ : List[str] = False for each_need in need_list: SCREAMING_SNAKE_CASE__ : Dict = True for index, need in enumerate(_a ): if need > available_resources[index]: SCREAMING_SNAKE_CASE__ : Optional[int] = False break if execution: SCREAMING_SNAKE_CASE__ : Any = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: SCREAMING_SNAKE_CASE__ : Tuple = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(_a ) # update available/freed resources stack SCREAMING_SNAKE_CASE__ : Dict = np.array(_a ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(_a ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def _a ( self ) -> Any: """simple docstring""" print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(_a ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(_a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
711
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: a :List[Any] = None a :Optional[int] = logging.get_logger(__name__) a :Union[str, Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} a :Optional[int] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } a :Dict = { "xlnet-base-cased": None, "xlnet-large-cased": None, } a :int = "▁" # Segments (not really needed) a :Dict = 0 a :Optional[int] = 1 a :Tuple = 2 a :List[str] = 3 a :Optional[Any] = 4 class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = """left""" _SCREAMING_SNAKE_CASE :Optional[Any] = XLNetTokenizer def __init__( self , _a=None , _a=None , _a=False , _a=True , _a=False , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<sep>" , _a="<pad>" , _a="<cls>" , _a="<mask>" , _a=["<eop>", "<eod>"] , **_a , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , additional_special_tokens=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE__ : List[str] = remove_space SCREAMING_SNAKE_CASE__ : int = keep_accents SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_file SCREAMING_SNAKE_CASE__ : Tuple = False if not self.vocab_file else True def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Tuple = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" import json import sys def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> List[str]: with open(lowerCamelCase_ , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.load(lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = ["""<details>""", """<summary>Show updated benchmarks!</summary>""", """ """] for benchmark_name in sorted(lowerCamelCase_ ): SCREAMING_SNAKE_CASE__ : str = results[benchmark_name] SCREAMING_SNAKE_CASE__ : Union[str, Any] = benchmark_name.split("""/""" )[-1] output_md.append(F'''### Benchmark: {benchmark_file_name}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """| metric |""" SCREAMING_SNAKE_CASE__ : Dict = """|--------|""" SCREAMING_SNAKE_CASE__ : int = """| new / old (diff) |""" for metric_name in sorted(lowerCamelCase_ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = benchmark_res[metric_name] SCREAMING_SNAKE_CASE__ : Tuple = metric_vals["""new"""] SCREAMING_SNAKE_CASE__ : Optional[int] = metric_vals.get("""old""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Tuple = metric_vals.get("""diff""" , lowerCamelCase_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = F''' {new_val:f}''' if isinstance(lowerCamelCase_ , (int, float) ) else """None""" if old_val is not None: val_str += F''' / {old_val:f}''' if isinstance(lowerCamelCase_ , (int, float) ) else "None" if dif_val is not None: val_str += F''' ({dif_val:f})''' if isinstance(lowerCamelCase_ , (int, float) ) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append("""</details>""" ) with open(lowerCamelCase_ , """w""" , encoding="""utf-8""" ) as f: f.writelines("""\n""".join(lowerCamelCase_ ) ) if __name__ == "__main__": a :Dict = sys.argv[1] a :Any = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
712
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) + 1 SCREAMING_SNAKE_CASE__ : int = len(__lowerCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. SCREAMING_SNAKE_CASE__ : Dict = [[0 for i in range(__lowerCAmelCase )] for j in range(__lowerCAmelCase )] # since string of zero length match pattern of zero length SCREAMING_SNAKE_CASE__ : Dict = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : int = dp[0][j - 2] if pattern[j - 1] == """*""" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __lowerCAmelCase ): for j in range(1 , __lowerCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": SCREAMING_SNAKE_CASE__ : Any = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: SCREAMING_SNAKE_CASE__ : List[str] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): SCREAMING_SNAKE_CASE__ : List[Any] = dp[i - 1][j] else: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 else: SCREAMING_SNAKE_CASE__ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") a :Any = "aab" a :Optional[Any] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f'{input_string} matches the given pattern {pattern}') else: print(f'{input_string} does not match with the given pattern {pattern}')
12
0
"""simple docstring""" from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean a :Optional[Any] = 0 a :int = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a :int = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right a :List[str] = tuple[int, int] class __a : '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = pos_x SCREAMING_SNAKE_CASE__ : str = pos_y SCREAMING_SNAKE_CASE__ : List[str] = (pos_y, pos_x) SCREAMING_SNAKE_CASE__ : Union[str, Any] = goal_x SCREAMING_SNAKE_CASE__ : Dict = goal_y SCREAMING_SNAKE_CASE__ : List[Any] = g_cost SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : str = self.calculate_heuristic() SCREAMING_SNAKE_CASE__ : Optional[int] = self.g_cost + self.h_cost def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.pos_x - self.goal_x SCREAMING_SNAKE_CASE__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(UpperCamelCase_ ) + abs(UpperCamelCase_ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self , _a ) -> str: """simple docstring""" return self.f_cost < other.f_cost class __a : '''simple docstring''' def __init__( self , _a , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ : int = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99_999 , UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ : List[str] = [self.start] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Any = False def _a ( self ) -> Optional[int]: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(UpperCamelCase_ ) self.closed_nodes.append(UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_successors(UpperCamelCase_ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(UpperCamelCase_ ) else: # retrieve the best current path SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.open_nodes.pop(self.open_nodes.index(UpperCamelCase_ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(UpperCamelCase_ ) else: self.open_nodes.append(UpperCamelCase_ ) return [self.start.pos] def _a ( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = [] for action in delta: SCREAMING_SNAKE_CASE__ : Tuple = parent.pos_x + action[1] SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCamelCase_ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( UpperCamelCase_ , UpperCamelCase_ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , UpperCamelCase_ , ) ) return successors def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = node SCREAMING_SNAKE_CASE__ : Optional[int] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = current_node.parent path.reverse() return path class __a : '''simple docstring''' def __init__( self , _a , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AStar(UpperCamelCase_ , UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ : Any = AStar(UpperCamelCase_ , UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ : Any = False def _a ( self ) -> str: """simple docstring""" while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() SCREAMING_SNAKE_CASE__ : Optional[int] = self.fwd_astar.open_nodes.pop(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( UpperCamelCase_ , UpperCamelCase_ ) self.fwd_astar.closed_nodes.append(UpperCamelCase_ ) self.bwd_astar.closed_nodes.append(UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ : str = current_bwd_node SCREAMING_SNAKE_CASE__ : Any = current_fwd_node SCREAMING_SNAKE_CASE__ : Dict = { self.fwd_astar: self.fwd_astar.get_successors(UpperCamelCase_ ), self.bwd_astar: self.bwd_astar.get_successors(UpperCamelCase_ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(UpperCamelCase_ ) else: # retrieve the best current path SCREAMING_SNAKE_CASE__ : str = astar.open_nodes.pop( astar.open_nodes.index(UpperCamelCase_ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(UpperCamelCase_ ) else: astar.open_nodes.append(UpperCamelCase_ ) return [self.fwd_astar.start.pos] def _a ( self , _a , _a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.fwd_astar.retrace_path(UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.bwd_astar.retrace_path(UpperCamelCase_ ) bwd_path.pop() bwd_path.reverse() SCREAMING_SNAKE_CASE__ : str = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] a :Any = (0, 0) a :Optional[int] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a :List[Any] = time.time() a :Dict = AStar(init, goal) a :Dict = a_star.search() a :int = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') a :str = time.time() a :Any = BidirectionalAStar(init, goal) a :Tuple = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
713
"""simple docstring""" from math import sqrt def _lowercase ( __lowerCAmelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowercase ( __lowerCAmelCase = 1_0001 ) -> int: SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Tuple = 1 while count != nth and number < 3: number += 1 if is_prime(__lowerCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(__lowerCAmelCase ): count += 1 return number if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta 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[str] = GPTaTokenizer _SCREAMING_SNAKE_CASE :List[Any] = GPTaTokenizerFast _SCREAMING_SNAKE_CASE :Any = True _SCREAMING_SNAKE_CASE :List[str] = {"""add_prefix_space""": True} _SCREAMING_SNAKE_CASE :Union[str, Any] = False def _a ( self ) -> int: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] SCREAMING_SNAKE_CASE__ : Optional[Any] = dict(zip(_a , range(len(_a ) ) ) ) SCREAMING_SNAKE_CASE__ : str = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] SCREAMING_SNAKE_CASE__ : List[str] = {"unk_token": "<unk>"} SCREAMING_SNAKE_CASE__ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_a ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(_a ) ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = "lower newer" SCREAMING_SNAKE_CASE__ : Optional[Any] = "lower newer" return input_text, output_text def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ : Dict = "lower newer" SCREAMING_SNAKE_CASE__ : Optional[Any] = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.tokenize(_a , add_prefix_space=_a ) self.assertListEqual(_a , _a ) SCREAMING_SNAKE_CASE__ : Any = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : str = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , _a ) def _a ( self ) -> List[str]: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_rust_tokenizer(add_prefix_space=_a ) SCREAMING_SNAKE_CASE__ : int = "lower newer" # Testing tokenization SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(_a , add_prefix_space=_a ) SCREAMING_SNAKE_CASE__ : int = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(_a , add_special_tokens=_a , add_prefix_space=_a ) SCREAMING_SNAKE_CASE__ : Dict = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE__ : List[str] = self.get_rust_tokenizer(add_prefix_space=_a ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(_a , add_prefix_space=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) # Testing the unknown token SCREAMING_SNAKE_CASE__ : List[Any] = tokens + [rust_tokenizer.unk_token] SCREAMING_SNAKE_CASE__ : Optional[Any] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(_a ) , _a ) def _a ( self , *_a , **_a ) -> Dict: """simple docstring""" pass def _a ( self , _a=15 ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(_a , **_a ) # Simple input SCREAMING_SNAKE_CASE__ : Dict = "This is a simple input" SCREAMING_SNAKE_CASE__ : List[str] = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : Optional[int] = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(_a , tokenizer_r.encode , _a , max_length=_a , padding="""max_length""" ) # Simple input self.assertRaises(_a , tokenizer_r.encode_plus , _a , max_length=_a , padding="""max_length""" ) # Simple input self.assertRaises( _a , tokenizer_r.batch_encode_plus , _a , max_length=_a , padding="""max_length""" , ) # Pair input self.assertRaises(_a , tokenizer_r.encode , _a , max_length=_a , padding="""max_length""" ) # Pair input self.assertRaises(_a , tokenizer_r.encode_plus , _a , max_length=_a , padding="""max_length""" ) # Pair input self.assertRaises( _a , tokenizer_r.batch_encode_plus , _a , max_length=_a , padding="""max_length""" , ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token="""<pad>""" ) # Simple input SCREAMING_SNAKE_CASE__ : Optional[int] = "This is a simple input" SCREAMING_SNAKE_CASE__ : List[str] = ["This is a simple input looooooooong", "This is a simple input"] SCREAMING_SNAKE_CASE__ : List[Any] = ("This is a simple input", "This is a pair") SCREAMING_SNAKE_CASE__ : Optional[Any] = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] SCREAMING_SNAKE_CASE__ : Any = tokenizer.pad_token_id SCREAMING_SNAKE_CASE__ : Dict = tokenizer(_a , padding="""max_length""" , max_length=30 , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(_a , padding=_a , truncate=_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(*_a , padding="""max_length""" , max_length=60 , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(_a , padding=_a , truncate=_a , return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = "$$$" SCREAMING_SNAKE_CASE__ : Dict = GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=_a , add_bos_token=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = "This is a simple input" SCREAMING_SNAKE_CASE__ : Dict = ["This is a simple input 1", "This is a simple input 2"] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.bos_token_id SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer(_a ) SCREAMING_SNAKE_CASE__ : int = tokenizer(_a ) self.assertEqual(out_s.input_ids[0] , _a ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(out_s.input_ids ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , _a ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: """simple docstring""" pass def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [self.get_tokenizer(do_lower_case=_a , add_bos_token=_a )] for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ : str = "Encode this." SCREAMING_SNAKE_CASE__ : List[Any] = "This one too please." SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode(_a , add_special_tokens=_a ) encoded_sequence += tokenizer.encode(_a , add_special_tokens=_a ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode_plus( _a , _a , add_special_tokens=_a , return_special_tokens_mask=_a , ) SCREAMING_SNAKE_CASE__ : Tuple = encoded_sequence_dict["input_ids"] SCREAMING_SNAKE_CASE__ : int = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(_a ) , len(_a ) ) SCREAMING_SNAKE_CASE__ : List[str] = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(_a ) ] SCREAMING_SNAKE_CASE__ : Any = [x for x in filtered_sequence if x is not None] self.assertEqual(_a , _a ) @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = AutoTokenizer.from_pretrained("""facebook/opt-350m""" , from_slow=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _a , ) self.assertEqual(_a , [2, 250, 1_345, 9, 10, 4_758] ) tokenizer.save_pretrained("""test_opt""" ) SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""./test_opt""" ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.encode( _a , ) self.assertEqual(_a , [2, 250, 1_345, 9, 10, 4_758] ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = AutoTokenizer.from_pretrained("""facebook/opt-350m""" , use_slow=_a ) SCREAMING_SNAKE_CASE__ : int = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _a , ) # Same as above self.assertEqual(_a , [2, 250, 1_345, 9, 10, 4_758] ) @unittest.skip("""This test is failing because of a bug in the fast tokenizer""" ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""facebook/opt-350m""" , from_slow=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = "bos" SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.get_vocab()["bos"] SCREAMING_SNAKE_CASE__ : Optional[Any] = "A photo of a cat" SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode( _a , ) # We changed the bos token self.assertEqual(_a , [31_957, 250, 1_345, 9, 10, 4_758] ) tokenizer.save_pretrained("""./tok""" ) SCREAMING_SNAKE_CASE__ : Any = AutoTokenizer.from_pretrained("""./tok""" ) self.assertTrue(tokenizer.is_fast ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode( _a , ) self.assertEqual(_a , [31_957, 250, 1_345, 9, 10, 4_758] )
714
"""simple docstring""" class __a : '''simple docstring''' def __init__( self , _a , _a , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = name SCREAMING_SNAKE_CASE__ : Optional[Any] = value SCREAMING_SNAKE_CASE__ : List[Any] = weight def __repr__( self ) -> List[Any]: """simple docstring""" return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def _a ( self ) -> Dict: """simple docstring""" return self.value def _a ( self ) -> int: """simple docstring""" return self.name def _a ( self ) -> Optional[Any]: """simple docstring""" return self.weight def _a ( self ) -> Dict: """simple docstring""" return self.value / self.weight def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict: SCREAMING_SNAKE_CASE__ : Any = [] for i in range(len(__lowerCAmelCase ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[Any] = sorted(__lowerCAmelCase , key=__lowerCAmelCase , reverse=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 0.0, 0.0 for i in range(len(__lowerCAmelCase ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def _lowercase ( ) -> List[str]: pass if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor a :Union[str, Any] = logging.get_logger(__name__) class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , *_a , **_a ) -> None: """simple docstring""" warnings.warn( """The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use OwlViTImageProcessor instead.""" , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_ )
715
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: a :Optional[int] = None a :Optional[Any] = logging.get_logger(__name__) a :Optional[Any] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} a :Union[str, Any] = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } a :Any = { "facebook/nllb-large-en-ro": 1_024, "facebook/nllb-200-distilled-600M": 1_024, } # fmt: off a :Tuple = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :int = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE :Tuple = NllbTokenizer _SCREAMING_SNAKE_CASE :List[int] = [] _SCREAMING_SNAKE_CASE :List[int] = [] def __init__( self , _a=None , _a=None , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=None , _a=None , _a=None , _a=False , **_a , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token SCREAMING_SNAKE_CASE__ : Optional[int] = legacy_behaviour super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , legacy_behaviour=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_file SCREAMING_SNAKE_CASE__ : str = False if not self.vocab_file else True SCREAMING_SNAKE_CASE__ : Dict = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens} ) SCREAMING_SNAKE_CASE__ : List[str] = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE__ : Dict = src_lang if src_lang is not None else """eng_Latn""" SCREAMING_SNAKE_CASE__ : List[str] = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE__ : Dict = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _a ( self ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _a ( self , _a , _a , _a , _a , **_a ) -> Tuple: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ : Dict = src_lang SCREAMING_SNAKE_CASE__ : Dict = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_tokens_to_ids(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tgt_lang_id return inputs def _a ( self , _a , _a = "eng_Latn" , _a = None , _a = "fra_Latn" , **_a , ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = src_lang SCREAMING_SNAKE_CASE__ : Dict = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def _a ( self ) -> Optional[Any]: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _a ( self ) -> str: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Dict = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Dict = [self.eos_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : int = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : int = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _a ( self , _a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.convert_tokens_to_ids(_a ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.cur_lang_code] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.eos_token_id] SCREAMING_SNAKE_CASE__ : Any = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE__ : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return SCREAMING_SNAKE_CASE__ : Dict = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a :int = {"configuration_plbart": ["PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "PLBartConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[int] = ["PLBartTokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = [ "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 :List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure)
716
"""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 _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Any: # Format the message. if name is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None else: SCREAMING_SNAKE_CASE__ : str = """.""" * max(0 , spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" SCREAMING_SNAKE_CASE__ : Dict = fmt.format(__lowerCAmelCase ) # Print and recurse (if needed). if isinstance(__lowerCAmelCase , __lowerCAmelCase ): if msg is not None: print(__lowerCAmelCase ) for k in val.keys(): recursive_print(__lowerCAmelCase , val[k] , spaces + 2 ) elif isinstance(__lowerCAmelCase , torch.Tensor ): print(__lowerCAmelCase , """:""" , val.size() ) else: print(__lowerCAmelCase , """:""" , __lowerCAmelCase ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[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. SCREAMING_SNAKE_CASE__ : Tuple = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] SCREAMING_SNAKE_CASE__ : int = (num_heads, hidden_size, num_splits) + input_shape[1:] SCREAMING_SNAKE_CASE__ : List[str] = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = param.transpose(0 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] SCREAMING_SNAKE_CASE__ : List[str] = (num_heads, num_splits, hidden_size) + input_shape[1:] SCREAMING_SNAKE_CASE__ : Dict = param.view(*__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = param.transpose(0 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ : Any = param.view(*__lowerCAmelCase ) return param def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: # The converted output model. SCREAMING_SNAKE_CASE__ : List[str] = {} # old versions did not store training args SCREAMING_SNAKE_CASE__ : List[str] = input_state_dict.get("""args""" , __lowerCAmelCase ) 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)) SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.padded_vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = ds_args.max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = ds_args.hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = ds_args.num_layers SCREAMING_SNAKE_CASE__ : Dict = ds_args.num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = ds_args.ffn_hidden_size # pprint(config) # The number of heads. SCREAMING_SNAKE_CASE__ : List[str] = config.n_head # The hidden_size per head. SCREAMING_SNAKE_CASE__ : str = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_state_dict["""checkpoint_version"""] else: SCREAMING_SNAKE_CASE__ : Tuple = 0.0 # The model. SCREAMING_SNAKE_CASE__ : Any = input_state_dict["""model"""] # The language model. SCREAMING_SNAKE_CASE__ : Any = model["""language_model"""] # The embeddings. SCREAMING_SNAKE_CASE__ : str = lm["""embedding"""] # The word embeddings. SCREAMING_SNAKE_CASE__ : int = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. SCREAMING_SNAKE_CASE__ : Any = word_embeddings[: config.vocab_size, :] SCREAMING_SNAKE_CASE__ : Optional[int] = word_embeddings # The position embeddings. SCREAMING_SNAKE_CASE__ : Any = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] SCREAMING_SNAKE_CASE__ : Tuple = 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. SCREAMING_SNAKE_CASE__ : List[Any] = pos_embeddings # The transformer. SCREAMING_SNAKE_CASE__ : Union[str, Any] = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. SCREAMING_SNAKE_CASE__ : str = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. SCREAMING_SNAKE_CASE__ : Optional[int] = { """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. SCREAMING_SNAKE_CASE__ : str = layer_re.match(__lowerCAmelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. SCREAMING_SNAKE_CASE__ : Dict = int(m.group(1 ) ) # The name of the operation. SCREAMING_SNAKE_CASE__ : Optional[Any] = m.group(2 ) # Is it a weight or a bias? SCREAMING_SNAKE_CASE__ : str = m.group(3 ) # The name of the layer. SCREAMING_SNAKE_CASE__ : List[Any] = F'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): SCREAMING_SNAKE_CASE__ : Dict = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" SCREAMING_SNAKE_CASE__ : List[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. SCREAMING_SNAKE_CASE__ : Any = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = causal_mask # Insert a "dummy" tensor for masked_bias. SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor(-1E4 , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = masked_bias SCREAMING_SNAKE_CASE__ : List[str] = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. SCREAMING_SNAKE_CASE__ : str = out_val.transpose(0 , 1 ).contiguous() # Store. SCREAMING_SNAKE_CASE__ : Dict = 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": SCREAMING_SNAKE_CASE__ : Any = fix_query_key_value_ordering(__lowerCAmelCase , __lowerCAmelCase , 3 , __lowerCAmelCase , __lowerCAmelCase ) # Store. No change of shape. SCREAMING_SNAKE_CASE__ : str = out_val # Transpose the weights. elif weight_or_bias == "weight": SCREAMING_SNAKE_CASE__ : str = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : int = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": SCREAMING_SNAKE_CASE__ : int = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : Dict = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. SCREAMING_SNAKE_CASE__ : Union[str, Any] = transformer["""final_layernorm.weight"""] SCREAMING_SNAKE_CASE__ : str = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. SCREAMING_SNAKE_CASE__ : Tuple = word_embeddings # It should be done! return output_state_dict def _lowercase ( ) -> List[Any]: # Create the argument parser. SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""" , action="""store_true""" ) parser.add_argument( """path_to_checkpoint""" , type=__lowerCAmelCase , help="""Path to the checkpoint file (.zip archive or direct .pt file)""" , ) parser.add_argument( """--config_file""" , default="""""" , type=__lowerCAmelCase , help="""An optional config json file describing the pre-trained model.""" , ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() # Extract the basename. SCREAMING_SNAKE_CASE__ : Optional[int] = 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: SCREAMING_SNAKE_CASE__ : List[Any] = torch.load(__lowerCAmelCase , map_location="""cpu""" ) else: SCREAMING_SNAKE_CASE__ : str = torch.load(args.path_to_checkpoint , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : int = input_state_dict.get("""args""" , __lowerCAmelCase ) # 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: SCREAMING_SNAKE_CASE__ : Dict = """gelu_fast""" elif ds_args.openai_gelu: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu_new""" else: SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu""" else: # in the very early days this used to be "gelu_new" SCREAMING_SNAKE_CASE__ : Any = """gelu_new""" # Spell out all parameters in case the defaults change. SCREAMING_SNAKE_CASE__ : Union[str, Any] = GPTaConfig( vocab_size=5_0257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=__lowerCAmelCase , 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=__lowerCAmelCase , summary_activation=__lowerCAmelCase , summary_proj_to_labels=__lowerCAmelCase , summary_first_dropout=0.1 , scale_attn_weights=__lowerCAmelCase , use_cache=__lowerCAmelCase , bos_token_id=5_0256 , eos_token_id=5_0256 , ) else: SCREAMING_SNAKE_CASE__ : List[Any] = GPTaConfig.from_json_file(args.config_file ) SCREAMING_SNAKE_CASE__ : Tuple = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = convert_megatron_checkpoint(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(__lowerCAmelCase , __lowerCAmelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: SCREAMING_SNAKE_CASE__ : Tuple = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": SCREAMING_SNAKE_CASE__ : Any = """gpt2""" elif tokenizer_type == "PretrainedFromHF": SCREAMING_SNAKE_CASE__ : Any = ds_args.tokenizer_name_or_path else: raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """gpt2""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = type(__lowerCAmelCase ).__name__ SCREAMING_SNAKE_CASE__ : Dict = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(__lowerCAmelCase ) # Save tokenizer based on args print(F'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(__lowerCAmelCase ) # Store the state_dict to file. SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , """pytorch_model.bin""" ) print(F'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
12
0
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ : List[str] = [int(__lowerCAmelCase ) for i in ip_va_address.split(""".""" ) if i.isdigit()] return len(__lowerCAmelCase ) == 4 and all(0 <= int(__lowerCAmelCase ) <= 254 for octet in octets ) if __name__ == "__main__": a :List[Any] = input().strip() a :Any = 'valid' if is_ip_va_address_valid(ip) else 'invalid' print(f'{ip} is a {valid_or_invalid} IP v4 address.')
717
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class __a (UpperCamelCase_): '''simple docstring''' def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" with open(_a , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ : str = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = input_file.read() SCREAMING_SNAKE_CASE__ : str = regexp.search(_a ) return match def _a ( self , _a ) -> Optional[Any]: """simple docstring""" with open(_a , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ : Tuple = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) SCREAMING_SNAKE_CASE__ : List[Any] = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE__ : Dict = regexp.finditer(_a ) SCREAMING_SNAKE_CASE__ : int = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_a ) ): raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ : List[str] = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(_a ) ): raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
12
0
import fcntl import os import socket import torch import torch.distributed as dist def _lowercase ( *__lowerCAmelCase ) -> Any: with open(__lowerCAmelCase , """r""" ) as fh: fcntl.flock(__lowerCAmelCase , fcntl.LOCK_EX ) try: print(*__lowerCAmelCase ) finally: fcntl.flock(__lowerCAmelCase , fcntl.LOCK_UN ) a :Tuple = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) a :Dict = torch.device("cuda", local_rank) a :Dict = socket.gethostname() a :Tuple = f'[{hostname}-{local_rank}]' try: # test distributed dist.init_process_group("nccl") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank a :Tuple = dist.get_rank() a :str = dist.get_world_size() printflock(f'{gpu} is OK (global rank: {rank}/{world_size})') dist.barrier() if rank == 0: printflock(f'pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}') except Exception: printflock(f'{gpu} is broken') raise
718
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class __a : '''simple docstring''' def __init__( self , _a , _a=99 , _a=13 , _a=7 , _a=9 , _a=True , _a=True , _a=False , _a=32 , _a=5 , _a=4 , _a=37 , _a=8 , _a=0.1 , _a=0.002 , _a=1 , _a=0 , _a=0 , _a=None , _a=None , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Tuple = encoder_seq_length SCREAMING_SNAKE_CASE__ : str = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE__ : Optional[int] = self.decoder_seq_length SCREAMING_SNAKE_CASE__ : Tuple = is_training SCREAMING_SNAKE_CASE__ : Dict = use_attention_mask SCREAMING_SNAKE_CASE__ : List[str] = use_labels SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = d_ff SCREAMING_SNAKE_CASE__ : Any = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor SCREAMING_SNAKE_CASE__ : List[Any] = eos_token_id SCREAMING_SNAKE_CASE__ : List[str] = pad_token_id SCREAMING_SNAKE_CASE__ : Any = decoder_start_token_id SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : str = decoder_layers def _a ( self ) -> Tuple: """simple docstring""" return TaConfig.from_pretrained("""google/umt5-base""" ) def _a ( self , _a , _a , _a , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> Any: """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : int = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE__ : str = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_a ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_a ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=_a ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input SCREAMING_SNAKE_CASE__ : Tuple = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config() SCREAMING_SNAKE_CASE__ : List[str] = config.num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_inputs_dict(_a , _a , _a ) return config, input_dict def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() return config, inputs_dict def _a ( self ) -> List[str]: """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self ) -> List[Any]: """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = UMTaModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model( input_ids=_a , decoder_input_ids=_a , attention_mask=_a , decoder_attention_mask=_a , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=_a , decoder_input_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = result.last_hidden_state SCREAMING_SNAKE_CASE__ : Dict = result.past_key_values SCREAMING_SNAKE_CASE__ : Any = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(_a ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).get_decoder().to(_a ).eval() # first forward pass SCREAMING_SNAKE_CASE__ : str = model(_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , use_cache=_a ) self.parent.assertTrue(len(_a ) == len(_a ) ) self.parent.assertTrue(len(_a ) == len(_a ) + 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : Tuple = model(_a , past_key_values=_a )["""last_hidden_state"""] # select random slice SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) ) def _a ( self , _a , _a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).to(_a ).half().eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**_a )["""last_hidden_state"""] self.parent.assertFalse(torch.isnan(_a ).any().item() ) @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :List[str] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Union[str, Any] = True _SCREAMING_SNAKE_CASE :Tuple = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = True _SCREAMING_SNAKE_CASE :List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _SCREAMING_SNAKE_CASE :Union[str, Any] = [0.8, 0.9] def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = UMTaModelTester(self ) @unittest.skip("""Test has a segmentation fault on torch 1.8.0""" ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = UMTaModel(config_and_inputs[0] ).to(_a ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( _a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=_a , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*_a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""] SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs[0] SCREAMING_SNAKE_CASE__ : Tuple = UMTaForConditionalGeneration(_a ).eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = { """head_mask""": torch.zeros(config.num_layers , config.num_heads , device=_a ), """decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), } for attn_name, (name, mask) in zip(_a , head_masking.items() ): SCREAMING_SNAKE_CASE__ : List[str] = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": SCREAMING_SNAKE_CASE__ : str = torch.ones( config.num_decoder_layers , config.num_heads , device=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.generate( config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=_a , return_dict_in_generate=_a , **_a , ) # We check the state of decoder_attentions and cross_attentions just from the last step SCREAMING_SNAKE_CASE__ : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" ) def _a ( self ) -> Dict: """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow @unittest.skip( """Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=_a ).to(_a ) SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=_a , legacy=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ """Bonjour monsieur <extra_id_0> bien <extra_id_1>.""", """No se como puedo <extra_id_0>.""", """This is the reason why we <extra_id_0> them.""", """The <extra_id_0> walks in <extra_id_1>, seats""", """A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""", ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_a , return_tensors="""pt""" , padding=_a ).input_ids # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(_a , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids.to(_a ) ) SCREAMING_SNAKE_CASE__ : int = [ """<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""", """<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", ] SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.batch_decode(_a ) self.assertEqual(_a , _a )
12
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a :Union[str, Any] = logging.get_logger(__name__) a :Union[str, Any] = { "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class __a (__lowerCamelCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = """vit_mae""" def __init__( self , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-1_2 , _a=224 , _a=16 , _a=3 , _a=True , _a=16 , _a=512 , _a=8 , _a=2_048 , _a=0.75 , _a=False , **_a , ) -> Union[str, Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : str = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = initializer_range SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = image_size SCREAMING_SNAKE_CASE__ : str = patch_size SCREAMING_SNAKE_CASE__ : Dict = num_channels SCREAMING_SNAKE_CASE__ : List[Any] = qkv_bias SCREAMING_SNAKE_CASE__ : Any = decoder_num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = decoder_hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = decoder_num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = decoder_intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = mask_ratio SCREAMING_SNAKE_CASE__ : List[str] = norm_pix_loss
719
"""simple docstring""" import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __a (UpperCamelCase_): '''simple docstring''' def __init__( self , _a , _a , _a = None , _a = None , _a = False , **_a , ) -> Union[str, Any]: """simple docstring""" super().__init__(features=_a , cache_dir=_a , keep_in_memory=_a , **_a ) SCREAMING_SNAKE_CASE__ : List[Any] = Sql( cache_dir=_a , features=_a , sql=_a , con=_a , **_a , ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None self.builder.download_and_prepare( download_config=_a , download_mode=_a , verification_mode=_a , base_path=_a , ) # Build dataset for splits SCREAMING_SNAKE_CASE__ : str = self.builder.as_dataset( split="""train""" , verification_mode=_a , in_memory=self.keep_in_memory ) return dataset class __a : '''simple docstring''' def __init__( self , _a , _a , _a , _a = None , _a = None , **_a , ) -> Any: """simple docstring""" if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) SCREAMING_SNAKE_CASE__ : int = dataset SCREAMING_SNAKE_CASE__ : Any = name SCREAMING_SNAKE_CASE__ : Optional[Any] = con SCREAMING_SNAKE_CASE__ : List[Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE SCREAMING_SNAKE_CASE__ : int = num_proc SCREAMING_SNAKE_CASE__ : int = to_sql_kwargs def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.to_sql_kwargs.pop("""sql""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = self.to_sql_kwargs.pop("""con""" , _a ) SCREAMING_SNAKE_CASE__ : Tuple = self.to_sql_kwargs.pop("""index""" , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._write(index=_a , **self.to_sql_kwargs ) return written def _a ( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = args SCREAMING_SNAKE_CASE__ : List[str] = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs SCREAMING_SNAKE_CASE__ : Any = query_table( table=self.dataset.data , key=slice(_a , offset + self.batch_size ) , indices=self.dataset._indices , ) SCREAMING_SNAKE_CASE__ : Optional[int] = batch.to_pandas() SCREAMING_SNAKE_CASE__ : List[Any] = df.to_sql(self.name , self.con , index=_a , **_a ) return num_rows or len(_a ) def _a ( self , _a , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _a , _a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
12
0
"""simple docstring""" from random import randint from tempfile import TemporaryFile import numpy as np def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 if start < end: SCREAMING_SNAKE_CASE__ : Any = randint(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = a[end] SCREAMING_SNAKE_CASE__ : int = a[pivot] SCREAMING_SNAKE_CASE__ : Optional[Any] = temp SCREAMING_SNAKE_CASE__ : Tuple = _in_place_partition(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) count += _in_place_quick_sort(__lowerCAmelCase , __lowerCAmelCase , p - 1 ) count += _in_place_quick_sort(__lowerCAmelCase , p + 1 , __lowerCAmelCase ) return count def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : str = randint(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = a[end] SCREAMING_SNAKE_CASE__ : Tuple = a[pivot] SCREAMING_SNAKE_CASE__ : Union[str, Any] = temp SCREAMING_SNAKE_CASE__ : Any = start - 1 for index in range(__lowerCAmelCase , __lowerCAmelCase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value SCREAMING_SNAKE_CASE__ : Union[str, Any] = new_pivot_index + 1 SCREAMING_SNAKE_CASE__ : Any = a[new_pivot_index] SCREAMING_SNAKE_CASE__ : List[str] = a[index] SCREAMING_SNAKE_CASE__ : Optional[Any] = temp SCREAMING_SNAKE_CASE__ : Tuple = a[new_pivot_index + 1] SCREAMING_SNAKE_CASE__ : int = a[end] SCREAMING_SNAKE_CASE__ : int = temp return new_pivot_index + 1, count a :Tuple = TemporaryFile() a :Tuple = 100 # 1000 elements are to be sorted a :int = 0, 1 # mean and standard deviation a :Any = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array a :Any = np.load(outfile) a :Optional[int] = len(M) - 1 a :Dict = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
720
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : int = 1 while repunit: SCREAMING_SNAKE_CASE__ : str = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def _lowercase ( __lowerCAmelCase = 100_0000 ) -> int: SCREAMING_SNAKE_CASE__ : Dict = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(__lowerCAmelCase ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file a :Dict = "Run commands across TPU VMs for initial setup before running `accelerate launch`." def _lowercase ( __lowerCAmelCase=None ) -> int: if subparsers is not None: SCREAMING_SNAKE_CASE__ : Dict = subparsers.add_parser("""tpu-config""" , description=_description ) else: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser("""Accelerate tpu-config command""" , description=_description ) # Core arguments SCREAMING_SNAKE_CASE__ : List[str] = parser.add_argument_group( """Config Arguments""" , """Arguments that can be configured through `accelerate config`.""" ) config_args.add_argument( """--config_file""" , type=__lowerCAmelCase , default=__lowerCAmelCase , help="""Path to the config file to use for accelerate.""" , ) config_args.add_argument( """--tpu_name""" , default=__lowerCAmelCase , help="""The name of the TPU to use. If not specified, will use the TPU specified in the config file.""" , ) config_args.add_argument( """--tpu_zone""" , default=__lowerCAmelCase , help="""The zone of the TPU to use. If not specified, will use the zone specified in the config file.""" , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_argument_group("""TPU Arguments""" , """Arguments for options ran inside the TPU.""" ) pod_args.add_argument( """--use_alpha""" , action="""store_true""" , help="""Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.""" , ) pod_args.add_argument( """--command_file""" , default=__lowerCAmelCase , help="""The path to the file containing the commands to run on the pod on startup.""" , ) pod_args.add_argument( """--command""" , action="""append""" , nargs="""+""" , help="""A command to run on the pod. Can be passed multiple times.""" , ) pod_args.add_argument( """--install_accelerate""" , action="""store_true""" , help="""Whether to install accelerate on the pod. Defaults to False.""" , ) pod_args.add_argument( """--accelerate_version""" , default="""latest""" , help="""The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.""" , ) pod_args.add_argument( """--debug""" , action="""store_true""" , help="""If set, will print the command that would be run instead of running it.""" ) if subparsers is not None: parser.set_defaults(func=__lowerCAmelCase ) return parser def _lowercase ( __lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__ : Optional[int] = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : int = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: SCREAMING_SNAKE_CASE__ : str = defaults.command_file if not args.command and defaults.commands is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = defaults.commands if not args.tpu_name: SCREAMING_SNAKE_CASE__ : List[str] = defaults.tpu_name if not args.tpu_zone: SCREAMING_SNAKE_CASE__ : Tuple = defaults.tpu_zone if args.accelerate_version == "dev": SCREAMING_SNAKE_CASE__ : Tuple = '''git+https://github.com/huggingface/accelerate.git''' elif args.accelerate_version == "latest": SCREAMING_SNAKE_CASE__ : Optional[Any] = '''accelerate -U''' elif isinstance(parse(args.accelerate_version ) , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = F'''accelerate=={args.accelerate_version}''' if not args.command_file and not args.command: raise ValueError("""You must specify either a command file or a command to run on the pod.""" ) if args.command_file: with open(args.command_file , """r""" ) as f: SCREAMING_SNAKE_CASE__ : Any = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate SCREAMING_SNAKE_CASE__ : str = ['''cd /usr/share'''] if args.install_accelerate: new_cmd += [F'''pip install {args.accelerate_version}'''] new_cmd += args.command SCREAMING_SNAKE_CASE__ : List[str] = '''; '''.join(__lowerCAmelCase ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess SCREAMING_SNAKE_CASE__ : Optional[Any] = ['''gcloud'''] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'''Running {' '.join(__lowerCAmelCase )}''' ) return subprocess.run(__lowerCAmelCase ) print("""Successfully setup pod.""" ) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = tpu_command_parser() SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() tpu_command_launcher(__lowerCAmelCase )
721
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") a :Union[str, Any] = logging.getLogger(__name__) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) _SCREAMING_SNAKE_CASE :Optional[int] = field( default=UpperCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of prediction examples to this """ """value if set.""" ) } , ) @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}) _SCREAMING_SNAKE_CASE :str = field( default=UpperCamelCase_ , metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Train language if it is different from the evaluation language."""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}) _SCREAMING_SNAKE_CASE :Optional[str] = field( default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) _SCREAMING_SNAKE_CASE :Optional[bool] = field( default=UpperCamelCase_ , metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) _SCREAMING_SNAKE_CASE :str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _SCREAMING_SNAKE_CASE :bool = field( default=UpperCamelCase_ , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def _lowercase ( ) -> Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE__ : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_xnli""" , __lowerCAmelCase ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : List[Any] = training_args.get_process_log_level() logger.setLevel(__lowerCAmelCase ) datasets.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.set_verbosity(__lowerCAmelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__ : Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__ : Optional[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: SCREAMING_SNAKE_CASE__ : Optional[int] = load_dataset( """xnli""" , model_args.language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: SCREAMING_SNAKE_CASE__ : str = load_dataset( """xnli""" , model_args.train_language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = train_dataset.features["""label"""].names if training_args.do_eval: SCREAMING_SNAKE_CASE__ : int = load_dataset( """xnli""" , model_args.language , split="""validation""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.features["""label"""].names if training_args.do_predict: SCREAMING_SNAKE_CASE__ : int = load_dataset( """xnli""" , model_args.language , split="""test""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Tuple = predict_dataset.features["""label"""].names # Labels SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : Any = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__lowerCAmelCase , idalabel={str(__lowerCAmelCase ): label for i, label in enumerate(__lowerCAmelCase )} , labelaid={label: i for i, label in enumerate(__lowerCAmelCase )} , finetuning_task="""xnli""" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ : str = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__lowerCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : str = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch SCREAMING_SNAKE_CASE__ : Optional[Any] = False def preprocess_function(__lowerCAmelCase ): # Tokenize the texts return tokenizer( examples["""premise"""] , examples["""hypothesis"""] , padding=__lowerCAmelCase , max_length=data_args.max_seq_length , truncation=__lowerCAmelCase , ) if training_args.do_train: if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(len(__lowerCAmelCase ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE__ : str = train_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : List[str] = train_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on train dataset""" , ) # Log a few random samples from the training set: for index in random.sample(range(len(__lowerCAmelCase ) ) , 3 ): logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.''' ) if training_args.do_eval: if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__ : Any = min(len(__lowerCAmelCase ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : List[str] = eval_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on validation dataset""" , ) if training_args.do_predict: if data_args.max_predict_samples is not None: SCREAMING_SNAKE_CASE__ : int = min(len(__lowerCAmelCase ) , data_args.max_predict_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = predict_dataset.select(range(__lowerCAmelCase ) ) with training_args.main_process_first(desc="""prediction dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : Tuple = predict_dataset.map( __lowerCAmelCase , batched=__lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on prediction dataset""" , ) # Get the metric function SCREAMING_SNAKE_CASE__ : Optional[Any] = evaluate.load("""xnli""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Dict = p.predictions[0] if isinstance(p.predictions , __lowerCAmelCase ) else p.predictions SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.argmax(__lowerCAmelCase , axis=1 ) return metric.compute(predictions=__lowerCAmelCase , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ : List[Any] = default_data_collator elif training_args.fpaa: SCREAMING_SNAKE_CASE__ : int = DataCollatorWithPadding(__lowerCAmelCase , pad_to_multiple_of=8 ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None # Initialize our Trainer SCREAMING_SNAKE_CASE__ : Union[str, Any] = Trainer( model=__lowerCAmelCase , args=__lowerCAmelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__lowerCAmelCase , tokenizer=__lowerCAmelCase , data_collator=__lowerCAmelCase , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__ : Dict = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = last_checkpoint SCREAMING_SNAKE_CASE__ : str = trainer.train(resume_from_checkpoint=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = train_result.metrics SCREAMING_SNAKE_CASE__ : Optional[int] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : Dict = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , __lowerCAmelCase ) trainer.save_metrics("""train""" , __lowerCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE__ : Any = trainer.evaluate(eval_dataset=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""eval""" , __lowerCAmelCase ) trainer.save_metrics("""eval""" , __lowerCAmelCase ) # Prediction if training_args.do_predict: logger.info("""*** Predict ***""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = trainer.predict(__lowerCAmelCase , metric_key_prefix="""predict""" ) SCREAMING_SNAKE_CASE__ : List[str] = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__ : int = min(__lowerCAmelCase , len(__lowerCAmelCase ) ) trainer.log_metrics("""predict""" , __lowerCAmelCase ) trainer.save_metrics("""predict""" , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = np.argmax(__lowerCAmelCase , axis=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(training_args.output_dir , """predictions.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCAmelCase , """w""" ) as writer: writer.write("""index\tprediction\n""" ) for index, item in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[int] = label_list[item] writer.write(F'''{index}\t{item}\n''' ) if __name__ == "__main__": main()
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a :Optional[int] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
700
"""simple docstring""" # Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() a :str = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model a :int = { # fairseq: "wmt19-ru-en": {"length_penalty": 1.1}, "wmt19-en-ru": {"length_penalty": 1.15}, "wmt19-en-de": {"length_penalty": 1.0}, "wmt19-de-en": {"length_penalty": 1.1}, # allenai: "wmt16-en-de-dist-12-1": {"length_penalty": 0.6}, "wmt16-en-de-dist-6-1": {"length_penalty": 0.6}, "wmt16-en-de-12-1": {"length_penalty": 0.8}, "wmt19-de-en-6-6-base": {"length_penalty": 0.6}, "wmt19-de-en-6-6-big": {"length_penalty": 0.6}, } # this remaps the different models to their organization names a :Dict = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: a :List[Any] = "facebook" for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: a :str = "allenai" def _lowercase ( __lowerCAmelCase ) -> Any: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} SCREAMING_SNAKE_CASE__ : str = dict((re.sub(r"""@@$""" , """""" , __lowerCAmelCase ), v) if k.endswith("""@@""" ) else (re.sub(r"""$""" , """</w>""" , __lowerCAmelCase ), v) for k, v in d.items() ) SCREAMING_SNAKE_CASE__ : Tuple = """<s> <pad> </s> <unk>""".split() # restore the special tokens for k in keep_keys: del da[F'''{k}</w>'''] SCREAMING_SNAKE_CASE__ : Union[str, Any] = d[k] # restore return da def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: # prep assert os.path.exists(__lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) print(F'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models SCREAMING_SNAKE_CASE__ : Optional[Any] = basename(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = dirname(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel SCREAMING_SNAKE_CASE__ : Optional[int] = cls.hub_models() SCREAMING_SNAKE_CASE__ : Optional[int] = {"""bpe""": """fastbpe""", """tokenizer""": """moses"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = """.""" # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(F'''using checkpoint {checkpoint_file}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = hub_utils.from_pretrained( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , archive_map=__lowerCAmelCase , **__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = vars(chkpt["""args"""]["""model"""] ) SCREAMING_SNAKE_CASE__ : Any = args["""source_lang"""] SCREAMING_SNAKE_CASE__ : Any = args["""target_lang"""] SCREAMING_SNAKE_CASE__ : Optional[Any] = dirname(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = basename(__lowerCAmelCase ) # dicts SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(__lowerCAmelCase , F'''dict.{src_lang}.txt''' ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(__lowerCAmelCase , F'''dict.{tgt_lang}.txt''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Dictionary.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = rewrite_dict_keys(src_dict.indices ) SCREAMING_SNAKE_CASE__ : Optional[int] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , """vocab-src.json""" ) print(F'''Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab SCREAMING_SNAKE_CASE__ : Optional[Any] = True for k in src_vocab.keys(): if not k.islower(): SCREAMING_SNAKE_CASE__ : Tuple = False break SCREAMING_SNAKE_CASE__ : Optional[Any] = Dictionary.load(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rewrite_dict_keys(tgt_dict.indices ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , """vocab-tgt.json""" ) print(F'''Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # merges_file (bpecodes) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(__lowerCAmelCase , VOCAB_FILES_NAMES["""merges_file"""] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if os.path.exists(__lowerCAmelCase ): break with open(__lowerCAmelCase , encoding="""utf-8""" ) as fin: SCREAMING_SNAKE_CASE__ : Any = fin.read() SCREAMING_SNAKE_CASE__ : Tuple = re.sub(r""" \d+$""" , """""" , __lowerCAmelCase , 0 , re.M ) # remove frequency number print(F'''Generating {merges_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as fout: fout.write(__lowerCAmelCase ) # model config SCREAMING_SNAKE_CASE__ : Dict = os.path.join(__lowerCAmelCase , """config.json""" ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", F'''need to extend tokenizer to support bpe={args['bpe']}''' assert args["tokenizer"] == "moses", F'''need to extend tokenizer to support bpe={args['tokenizer']}''' SCREAMING_SNAKE_CASE__ : str = { """architectures""": ["""FSMTForConditionalGeneration"""], """model_type""": """fsmt""", """activation_dropout""": args["""activation_dropout"""], """activation_function""": """relu""", """attention_dropout""": args["""attention_dropout"""], """d_model""": args["""decoder_embed_dim"""], """dropout""": args["""dropout"""], """init_std""": 0.02, """max_position_embeddings""": args["""max_source_positions"""], """num_hidden_layers""": args["""encoder_layers"""], """src_vocab_size""": src_vocab_size, """tgt_vocab_size""": tgt_vocab_size, """langs""": [src_lang, tgt_lang], """encoder_attention_heads""": args["""encoder_attention_heads"""], """encoder_ffn_dim""": args["""encoder_ffn_embed_dim"""], """encoder_layerdrop""": args["""encoder_layerdrop"""], """encoder_layers""": args["""encoder_layers"""], """decoder_attention_heads""": args["""decoder_attention_heads"""], """decoder_ffn_dim""": args["""decoder_ffn_embed_dim"""], """decoder_layerdrop""": args["""decoder_layerdrop"""], """decoder_layers""": args["""decoder_layers"""], """bos_token_id""": 0, """pad_token_id""": 1, """eos_token_id""": 2, """is_encoder_decoder""": True, """scale_embedding""": not args["""no_scale_embedding"""], """tie_word_embeddings""": args["""share_all_embeddings"""], } # good hparam defaults to start with SCREAMING_SNAKE_CASE__ : Tuple = 5 SCREAMING_SNAKE_CASE__ : str = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: SCREAMING_SNAKE_CASE__ : Tuple = best_score_hparams[model_dir]["""length_penalty"""] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 1.0 print(F'''Generating {fsmt_model_config_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # tokenizer config SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = { """langs""": [src_lang, tgt_lang], """model_max_length""": 1024, """do_lower_case""": do_lower_case, } print(F'''Generating {fsmt_tokenizer_config_file}''' ) with open(__lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) ) # model SCREAMING_SNAKE_CASE__ : Dict = chkpt["""models"""][0] SCREAMING_SNAKE_CASE__ : int = model.state_dict() # rename keys to start with 'model.' SCREAMING_SNAKE_CASE__ : Tuple = OrderedDict(("""model.""" + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys SCREAMING_SNAKE_CASE__ : str = [ """model.model""", """model.encoder.version""", """model.decoder.version""", """model.encoder_embed_tokens.weight""", """model.decoder_embed_tokens.weight""", """model.encoder.embed_positions._float_tensor""", """model.decoder.embed_positions._float_tensor""", ] for k in ignore_keys: model_state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = FSMTConfig.from_pretrained(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = FSMTForConditionalGeneration(__lowerCAmelCase ) # check that it loads ok model_new.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase ) # save SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) print(F'''Generating {pytorch_weights_dump_path}''' ) torch.save(__lowerCAmelCase , __lowerCAmelCase ) print("""Conversion is done!""" ) print("""\nLast step is to upload the files to s3""" ) print(F'''cd {data_root}''' ) print(F'''transformers-cli upload {model_dir}''' ) if __name__ == "__main__": a :Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fsmt_checkpoint_path", default=None, type=str, required=True, help=( "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts," " bpecodes, etc." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) a :List[str] = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
12
0
"""simple docstring""" import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=30 , _a=2 , _a=3 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=None , _a=2 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : Dict = image_size SCREAMING_SNAKE_CASE__ : int = patch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_channels SCREAMING_SNAKE_CASE__ : Dict = is_training SCREAMING_SNAKE_CASE__ : Tuple = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : str = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : Tuple = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : Optional[Any] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str = num_patches + 1 def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Dict = self.get_config() return config, pixel_values, labels def _a ( self ) -> int: """simple docstring""" return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a ( self , _a , _a , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = ViTModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , _a , _a , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = ViTForMaskedImageModeling(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(__lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Dict = 1 SCREAMING_SNAKE_CASE__ : List[Any] = ViTForMaskedImageModeling(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE__ : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(__lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Dict = ViTForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = ViTForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE__ ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __a (lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :List[Any] = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :List[Any] = True _SCREAMING_SNAKE_CASE :str = False _SCREAMING_SNAKE_CASE :Any = False _SCREAMING_SNAKE_CASE :Optional[Any] = False def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = ViTModelTester(self ) SCREAMING_SNAKE_CASE__ : Dict = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _a ( self ) -> str: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def _a ( self ) -> Optional[Any]: """simple docstring""" pass def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(__lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase , nn.Linear ) ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Tuple = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCamelCase ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @slow def _a ( self ) -> Any: """simple docstring""" for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = ViTModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : int = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __a (unittest.TestCase): '''simple docstring''' @cached_property def _a ( self ) -> Any: """simple docstring""" return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=__lowerCamelCase , return_tensors="""pt""" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-0.2_744, 0.8_215, -0.0_836] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1E-4 ) ) @slow def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Tuple = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=480 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=__lowerCamelCase , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : Tuple = inputs.pixel_values.to(__lowerCamelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[int] = model(__lowerCamelCase , interpolate_pos_encoding=__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size((1, 3_601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor( [[4.2_340, 4.3_906, -6.6_692], [4.5_463, 1.8_928, -6.7_257], [4.4_429, 0.8_496, -5.8_585]] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __lowerCamelCase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE__ : str = prepare_img() SCREAMING_SNAKE_CASE__ : Any = image_processor(images=__lowerCamelCase , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = inputs.pixel_values.to(__lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Tuple = model(__lowerCamelCase )
701
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = (DDPMScheduler,) def _a ( self , **_a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**_a ) return config def _a ( self ) -> str: """simple docstring""" for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def _a ( self ) -> str: """simple docstring""" for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def _a ( self ) -> Any: """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def _a ( self ) -> Optional[int]: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def _a ( self ) -> int: """simple docstring""" self.check_over_configs(thresholding=_a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , ) def _a ( self ) -> str: """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def _a ( self ) -> str: """simple docstring""" for t in [0, 500, 999]: self.check_over_forward(time_step=_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Any = len(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : str = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : int = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : str = pred_prev_sample SCREAMING_SNAKE_CASE__ : str = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.9_606 ) < 1E-2 assert abs(result_mean.item() - 0.3_372 ) < 1E-3 def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Tuple = self.get_scheduler_config(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Dict = len(_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual SCREAMING_SNAKE_CASE__ : int = model(_a , _a ) # 2. predict previous mean of sample x_t-1 SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance SCREAMING_SNAKE_CASE__ : Tuple = pred_prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(_a ) ) SCREAMING_SNAKE_CASE__ : int = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 202.0_296 ) < 1E-2 assert abs(result_mean.item() - 0.2_631 ) < 1E-3 def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Dict = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = -1 else: SCREAMING_SNAKE_CASE__ : Tuple = timesteps[i + 1] SCREAMING_SNAKE_CASE__ : int = scheduler.previous_timestep(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prev_t.item() self.assertEqual(_a , _a ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : int = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [100, 87, 50, 51, 0] with self.assertRaises(_a , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=_a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : int = [100, 87, 50, 1, 0] SCREAMING_SNAKE_CASE__ : List[str] = len(_a ) with self.assertRaises(_a , msg="""Can only pass one of `num_inference_steps` or `custom_timesteps`.""" ): scheduler.set_timesteps(num_inference_steps=_a , timesteps=_a ) def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( _a , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=_a )
12
0
"""simple docstring""" import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset a :int = "bert-base-cased" a :List[str] = "google/pegasus-xsum" a :List[Any] = [" Sam ate lunch today.", "Sams lunch ingredients."] a :Any = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"] a :Optional[Any] = "patrickvonplaten/t5-tiny-random" a :Optional[int] = "sshleifer/bart-tiny-random" a :List[str] = "sshleifer/tiny-mbart" a :Any = "sshleifer/tiny-marian-en-de" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : Dict = """\n""".join(UpperCamelCase__ ) Path(UpperCamelCase__ ).open("""w""" ).writelines(UpperCamelCase__ ) def _lowercase ( __lowerCAmelCase ) -> str: for split in ["train", "val", "test"]: _dump_articles(os.path.join(UpperCamelCase__ , F'''{split}.source''' ) , UpperCamelCase__ ) _dump_articles(os.path.join(UpperCamelCase__ , F'''{split}.target''' ) , UpperCamelCase__ ) return tmp_dir class __a (UpperCAmelCase_): '''simple docstring''' @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def _a ( self , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = AutoTokenizer.from_pretrained(_lowercase ) SCREAMING_SNAKE_CASE__ : Dict = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(len(tokenizer.encode(_lowercase ) ) for a in ARTICLES ) SCREAMING_SNAKE_CASE__ : Optional[Any] = max(len(tokenizer.encode(_lowercase ) ) for a in SUMMARIES ) SCREAMING_SNAKE_CASE__ : List[Any] = 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = """ro_RO""", """de_DE""" # ignored for all but mbart, but never causes error. SCREAMING_SNAKE_CASE__ : Any = SeqaSeqDataset( _lowercase , data_dir=_lowercase , type_path="""train""" , max_source_length=_lowercase , max_target_length=_lowercase , src_lang=_lowercase , tgt_lang=_lowercase , ) SCREAMING_SNAKE_CASE__ : Dict = DataLoader(_lowercase , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(_lowercase , _lowercase ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place SCREAMING_SNAKE_CASE__ : Optional[int] = shift_tokens_right(batch["""labels"""] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def _a ( self , _a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained(_lowercase ) SCREAMING_SNAKE_CASE__ : int = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE__ : str = max(len(tokenizer.encode(_lowercase ) ) for a in ARTICLES ) SCREAMING_SNAKE_CASE__ : int = max(len(tokenizer.encode(_lowercase ) ) for a in SUMMARIES ) SCREAMING_SNAKE_CASE__ : List[str] = 4 SCREAMING_SNAKE_CASE__ : List[str] = LegacySeqaSeqDataset( _lowercase , data_dir=_lowercase , type_path="""train""" , max_source_length=20 , max_target_length=_lowercase , ) SCREAMING_SNAKE_CASE__ : str = DataLoader(_lowercase , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 20 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained("""facebook/mbart-large-cc25""" ) SCREAMING_SNAKE_CASE__ : List[Any] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tmp_dir.joinpath("""train.source""" ).open().readlines() SCREAMING_SNAKE_CASE__ : List[str] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(_lowercase , _lowercase , 128 , _lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] = {x.name for x in tmp_dir.iterdir()} SCREAMING_SNAKE_CASE__ : List[Any] = {x.name for x in save_dir.iterdir()} SCREAMING_SNAKE_CASE__ : str = save_dir.joinpath("""train.source""" ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(_lowercase ) < len(_lowercase ) assert len(_lowercase ) == 1 assert len(packed_examples[0] ) == sum(len(_lowercase ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="""This test requires fairseq""" ) def _a ( self ) -> Optional[Any]: """simple docstring""" if not FAIRSEQ_AVAILABLE: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self._get_dataset(max_len=64 ) SCREAMING_SNAKE_CASE__ : Any = 64 SCREAMING_SNAKE_CASE__ : int = ds.make_dynamic_sampler(_lowercase , required_batch_size_multiple=_lowercase ) SCREAMING_SNAKE_CASE__ : Any = [len(_lowercase ) for x in batch_sampler] assert len(set(_lowercase ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(_lowercase ) == len(_lowercase ) # no dropped or added examples SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader(_lowercase , batch_sampler=_lowercase , collate_fn=ds.collate_fn , num_workers=2 ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch in data_loader: SCREAMING_SNAKE_CASE__ : List[str] = batch["""input_ids"""].shape SCREAMING_SNAKE_CASE__ : List[Any] = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple SCREAMING_SNAKE_CASE__ : Dict = np.product(batch["""input_ids"""].shape ) num_src_per_batch.append(_lowercase ) if num_src_tokens > (max_tokens * 1.1): failures.append(_lowercase ) assert num_src_per_batch[0] == max(_lowercase ) if failures: raise AssertionError(f'''too many tokens in {len(_lowercase )} batches''' ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self._get_dataset(max_len=512 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 2 SCREAMING_SNAKE_CASE__ : str = ds.make_sortish_sampler(_lowercase , shuffle=_lowercase ) SCREAMING_SNAKE_CASE__ : Any = DataLoader(_lowercase , batch_size=_lowercase , collate_fn=ds.collate_fn , num_workers=2 ) SCREAMING_SNAKE_CASE__ : Any = DataLoader(_lowercase , batch_size=_lowercase , collate_fn=ds.collate_fn , num_workers=2 , sampler=_lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.pad_token_id def count_pad_tokens(_a , _a="input_ids" ): return [batch[k].eq(_lowercase ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(_lowercase , k="""labels""" ) ) < sum(count_pad_tokens(_lowercase , k="""labels""" ) ) assert sum(count_pad_tokens(_lowercase ) ) < sum(count_pad_tokens(_lowercase ) ) assert len(_lowercase ) == len(_lowercase ) def _a ( self , _a=1_000 , _a=128 ) -> Optional[Any]: """simple docstring""" if os.getenv("""USE_REAL_DATA""" , _lowercase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = """examples/seq2seq/wmt_en_ro""" SCREAMING_SNAKE_CASE__ : List[str] = max_len * 2 * 64 if not Path(_lowercase ).joinpath("""train.len""" ).exists(): save_len_file(_lowercase , _lowercase ) else: SCREAMING_SNAKE_CASE__ : Any = """examples/seq2seq/test_data/wmt_en_ro""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_len * 4 save_len_file(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE__ : List[str] = AutoTokenizer.from_pretrained(_lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] = SeqaSeqDataset( _lowercase , data_dir=_lowercase , type_path="""train""" , max_source_length=_lowercase , max_target_length=_lowercase , n_obs=_lowercase , ) return ds, max_tokens, tokenizer def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self._get_dataset() SCREAMING_SNAKE_CASE__ : List[Any] = set(DistributedSortishSampler(_lowercase , 256 , num_replicas=2 , rank=0 , add_extra_examples=_lowercase ) ) SCREAMING_SNAKE_CASE__ : Any = set(DistributedSortishSampler(_lowercase , 256 , num_replicas=2 , rank=1 , add_extra_examples=_lowercase ) ) assert idsa.intersection(_lowercase ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def _a ( self , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoTokenizer.from_pretrained(_lowercase , use_fast=_lowercase ) if tok_name == MBART_TINY: SCREAMING_SNAKE_CASE__ : Dict = SeqaSeqDataset( _lowercase , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="""train""" , max_source_length=4 , max_target_length=8 , src_lang="""EN""" , tgt_lang="""FR""" , ) SCREAMING_SNAKE_CASE__ : Tuple = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: SCREAMING_SNAKE_CASE__ : Dict = SeqaSeqDataset( _lowercase , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="""train""" , max_source_length=4 , max_target_length=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(_lowercase ) == 1 if tok_name == BART_TINY else len(_lowercase ) == 0
702
"""simple docstring""" import os a :List[str] = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1_000} def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 while index < len(__lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE__ : List[Any] = SYMBOLS[numerals[index]] SCREAMING_SNAKE_CASE__ : Dict = 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 _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Optional[int] = """""" SCREAMING_SNAKE_CASE__ : int = num // 1000 numerals += m_count * "M" num %= 1000 SCREAMING_SNAKE_CASE__ : List[str] = 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 SCREAMING_SNAKE_CASE__ : List[Any] = 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 _lowercase ( __lowerCAmelCase = "/p089_roman.txt" ) -> int: SCREAMING_SNAKE_CASE__ : int = 0 with open(os.path.dirname(__lowerCAmelCase ) + roman_numerals_filename ) as filea: SCREAMING_SNAKE_CASE__ : str = filea.readlines() for line in lines: SCREAMING_SNAKE_CASE__ : Union[str, Any] = line.strip() SCREAMING_SNAKE_CASE__ : Dict = parse_roman_numerals(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = generate_roman_numerals(__lowerCAmelCase ) savings += len(__lowerCAmelCase ) - len(__lowerCAmelCase ) return savings if __name__ == "__main__": print(f'{solution() = }')
12
0
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("""repo_id""" , ["""canonical_dataset_name""", """org-name/dataset-name"""] ) @pytest.mark.parametrize("""path""" , ["""filename.csv""", """filename with blanks.csv"""] ) @pytest.mark.parametrize("""revision""" , [None, """v2"""] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = hf_hub_url(repo_id=__SCREAMING_SNAKE_CASE , path=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(__SCREAMING_SNAKE_CASE )}'''
703
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) SCREAMING_SNAKE_CASE__ : Any = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 25_543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : List[str] = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , _a ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Optional[int] = tf.convert_to_tensor( [[[-0.0_254, 0.0_235, 0.1_027], [0.0_606, -0.1_811, -0.0_418], [-0.1_561, -0.1_127, 0.2_687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
12
0
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES a :Optional[Any] = logging.get_logger(__name__) a :Any = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) a :Optional[int] = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) a :Union[str, Any] = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) a :Union[str, Any] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) a :List[str] = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) a :Optional[int] = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) a :str = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) a :Any = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) a :int = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) a :List[str] = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) a :Any = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) a :Optional[int] = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) a :List[Any] = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) a :List[Any] = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) a :Optional[int] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) a :List[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) a :str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) a :Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) a :List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) a :Tuple = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) a :List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) a :Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) a :Dict = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) a :Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) a :Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) a :Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) a :str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) a :Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = FLAX_MODEL_MAPPING a :Union[str, Any] = auto_class_update(FlaxAutoModel) class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = FLAX_MODEL_FOR_PRETRAINING_MAPPING a :Dict = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING a :List[str] = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING a :Union[str, Any] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a :Optional[int] = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING a :str = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING a :Optional[int] = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING a :str = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[str] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING a :List[str] = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING a :Tuple = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING a :Dict = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING a :Optional[int] = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class __a (_BaseAutoModelClass): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[int] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING a :Optional[Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
704
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a :List[Any] = logging.get_logger(__name__) a :Optional[int] = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = """focalnet""" def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=False , _a=[192, 384, 768, 768] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1E-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1E-5 , _a=32 , _a=None , _a=None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE__ : str = patch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = embed_dim SCREAMING_SNAKE_CASE__ : List[str] = use_conv_embed SCREAMING_SNAKE_CASE__ : List[str] = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Any = focal_levels SCREAMING_SNAKE_CASE__ : Optional[Any] = focal_windows SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : str = use_layerscale SCREAMING_SNAKE_CASE__ : int = layerscale_value SCREAMING_SNAKE_CASE__ : Optional[int] = use_post_layernorm SCREAMING_SNAKE_CASE__ : Any = use_post_layernorm_in_modulation SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize_modulator SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = encoder_stride SCREAMING_SNAKE_CASE__ : Optional[int] = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
12
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer a :Dict = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a :int = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } a :Tuple = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } a :str = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class __a (__lowercase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Optional[int] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Optional[Any] = PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE :Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :List[str] = ElectraTokenizer def __init__( self , _a=None , _a=None , _a=True , _a="[UNK]" , _a="[SEP]" , _a="[PAD]" , _a="[CLS]" , _a="[MASK]" , _a=True , _a=None , **_a , ) -> str: """simple docstring""" super().__init__( _a , tokenizer_file=_a , do_lower_case=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , tokenize_chinese_chars=_a , strip_accents=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , _a ) != do_lower_case or normalizer_state.get("""strip_accents""" , _a ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , _a ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(_a , normalizer_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_lower_case SCREAMING_SNAKE_CASE__ : Optional[int] = strip_accents SCREAMING_SNAKE_CASE__ : str = tokenize_chinese_chars SCREAMING_SNAKE_CASE__ : List[str] = normalizer_class(**_a ) SCREAMING_SNAKE_CASE__ : List[str] = do_lower_case def _a ( self , _a , _a=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : 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 _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self._tokenizer.model.save(_a , name=_a ) return tuple(_a )
705
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __a (unittest.TestCase): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_attention_mask SCREAMING_SNAKE_CASE__ : Tuple = use_token_type_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = num_choices def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE__ : int = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Any = True _SCREAMING_SNAKE_CASE :Optional[Any] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerModelTester(self ) @slow def _a ( self ) -> int: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Tuple = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a ) @require_flax class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.array([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ : str = model(_a )[0] SCREAMING_SNAKE_CASE__ : List[Any] = 50_000 SCREAMING_SNAKE_CASE__ : Optional[Any] = (1, 6, vocab_size) self.assertEqual(output.shape , _a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
12
0
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel a :List[str] = { "text_branch": "text_model", "audio_branch": "audio_model.audio_encoder", "attn": "attention.self", "self.proj": "output.dense", "attention.self_mask": "attn_mask", "mlp.fc1": "intermediate.dense", "mlp.fc2": "output.dense", "norm1": "layernorm_before", "norm2": "layernorm_after", "bn0": "batch_norm", } a :List[str] = AutoFeatureExtractor.from_pretrained("laion/clap-htsat-unfused", truncation="rand_trunc") def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=False ) -> List[str]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = create_model( """HTSAT-tiny""" , """roberta""" , _SCREAMING_SNAKE_CASE , precision="""fp32""" , device="""cuda:0""" if torch.cuda.is_available() else """cpu""" , enable_fusion=_SCREAMING_SNAKE_CASE , fusion_type="""aff_2d""" if enable_fusion else None , ) return model, model_cfg def _lowercase ( __lowerCAmelCase ) -> Dict: SCREAMING_SNAKE_CASE__ : Optional[Any] = {} SCREAMING_SNAKE_CASE__ : Any = r""".*sequential.(\d+).*""" SCREAMING_SNAKE_CASE__ : Dict = r""".*_projection.(\d+).*""" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if re.match(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # replace sequential layers with list SCREAMING_SNAKE_CASE__ : Any = re.match(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).group(1 ) SCREAMING_SNAKE_CASE__ : int = key.replace(F'''sequential.{sequential_layer}.''' , F'''layers.{int(_SCREAMING_SNAKE_CASE )//3}.linear.''' ) elif re.match(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE__ : str = int(re.match(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 if projecton_layer == 0 else 2 SCREAMING_SNAKE_CASE__ : Dict = key.replace(F'''_projection.{projecton_layer}.''' , F'''_projection.linear{transformers_projection_layer}.''' ) if "audio" and "qkv" in key: # split qkv into query key and value SCREAMING_SNAKE_CASE__ : int = value SCREAMING_SNAKE_CASE__ : Dict = mixed_qkv.size(0 ) // 3 SCREAMING_SNAKE_CASE__ : int = mixed_qkv[:qkv_dim] SCREAMING_SNAKE_CASE__ : str = mixed_qkv[qkv_dim : qkv_dim * 2] SCREAMING_SNAKE_CASE__ : Optional[Any] = mixed_qkv[qkv_dim * 2 :] SCREAMING_SNAKE_CASE__ : Any = query_layer SCREAMING_SNAKE_CASE__ : Any = key_layer SCREAMING_SNAKE_CASE__ : Tuple = value_layer else: SCREAMING_SNAKE_CASE__ : Any = value return model_state_dict def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=False ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = init_clap(_SCREAMING_SNAKE_CASE , enable_fusion=_SCREAMING_SNAKE_CASE ) clap_model.eval() SCREAMING_SNAKE_CASE__ : Dict = clap_model.state_dict() SCREAMING_SNAKE_CASE__ : Any = rename_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE__ : int = ClapConfig() SCREAMING_SNAKE_CASE__ : int = enable_fusion SCREAMING_SNAKE_CASE__ : Optional[Any] = ClapModel(_SCREAMING_SNAKE_CASE ) # ignore the spectrogram embedding layer model.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) transformers_config.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument("--enable_fusion", action="store_true", help="Whether to enable fusion or not") a :int = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
706
"""simple docstring""" a :List[str] = [ (1_000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1000} SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 while place < len(__lowerCAmelCase ): if (place + 1 < len(__lowerCAmelCase )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = [] for arabic, roman in ROMAN: ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) : List[str] = divmod(__lowerCAmelCase , __lowerCAmelCase ) result.append(roman * factor ) if number == 0: break return "".join(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a :Optional[Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[Any] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Dict = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure)
707
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a :Any = { "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig", "RobertaPreLayerNormOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Union[str, Any] = [ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :Optional[Any] = [ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :List[Any] = [ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys a :Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
12
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a :Dict = logging.get_logger(__name__) a :Any = { "facebook/wav2vec2-base-960h": "https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json", # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class __a (__A): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = """wav2vec2""" def __init__( self , _a=32 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.0 , _a=0.1 , _a=0.1 , _a=0.02 , _a=1E-5 , _a="group" , _a="gelu" , _a=(512, 512, 512, 512, 512, 512, 512) , _a=(5, 2, 2, 2, 2, 2, 2) , _a=(10, 3, 3, 3, 3, 2, 2) , _a=False , _a=128 , _a=16 , _a=False , _a=True , _a=0.05 , _a=10 , _a=2 , _a=0.0 , _a=10 , _a=0 , _a=320 , _a=2 , _a=0.1 , _a=100 , _a=256 , _a=256 , _a=0.1 , _a="sum" , _a=False , _a=False , _a=256 , _a=(512, 512, 512, 512, 1_500) , _a=(5, 3, 3, 1, 1) , _a=(1, 2, 3, 1, 1) , _a=512 , _a=0 , _a=1 , _a=2 , _a=False , _a=3 , _a=2 , _a=3 , _a=None , _a=None , **_a , ) -> Tuple: """simple docstring""" super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = feat_extract_norm SCREAMING_SNAKE_CASE__ : Any = feat_extract_activation SCREAMING_SNAKE_CASE__ : List[str] = list(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = list(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = list(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = conv_bias SCREAMING_SNAKE_CASE__ : int = num_conv_pos_embeddings SCREAMING_SNAKE_CASE__ : str = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE__ : List[str] = len(self.conv_dim ) SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : Union[str, Any] = activation_dropout SCREAMING_SNAKE_CASE__ : Dict = feat_proj_dropout SCREAMING_SNAKE_CASE__ : List[str] = final_dropout SCREAMING_SNAKE_CASE__ : Tuple = layerdrop SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = do_stable_layer_norm SCREAMING_SNAKE_CASE__ : str = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE__ : int = apply_spec_augment SCREAMING_SNAKE_CASE__ : int = mask_time_prob SCREAMING_SNAKE_CASE__ : Dict = mask_time_length SCREAMING_SNAKE_CASE__ : Any = mask_time_min_masks SCREAMING_SNAKE_CASE__ : List[Any] = mask_feature_prob SCREAMING_SNAKE_CASE__ : int = mask_feature_length SCREAMING_SNAKE_CASE__ : int = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE__ : Optional[int] = num_codevectors_per_group SCREAMING_SNAKE_CASE__ : List[Any] = num_codevector_groups SCREAMING_SNAKE_CASE__ : Optional[Any] = contrastive_logits_temperature SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_quantizer_dropout SCREAMING_SNAKE_CASE__ : Dict = num_negatives SCREAMING_SNAKE_CASE__ : Optional[Any] = codevector_dim SCREAMING_SNAKE_CASE__ : List[Any] = proj_codevector_dim SCREAMING_SNAKE_CASE__ : Dict = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE__ : Dict = ctc_loss_reduction SCREAMING_SNAKE_CASE__ : Dict = ctc_zero_infinity # adapter SCREAMING_SNAKE_CASE__ : int = add_adapter SCREAMING_SNAKE_CASE__ : Tuple = adapter_kernel_size SCREAMING_SNAKE_CASE__ : Optional[Any] = adapter_stride SCREAMING_SNAKE_CASE__ : Optional[Any] = num_adapter_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = output_hidden_size or hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE__ : Optional[Any] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE__ : Union[str, Any] = list(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple = list(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str = list(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] = xvector_output_dim @property def _a ( self ) -> List[str]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
708
"""simple docstring""" 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 IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : Dict = 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__ : Optional[Any] = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073], """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711], } SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_a , _a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> List[Any]: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def _a ( self , **_a ) -> Any: """simple docstring""" return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **_a ) def _a ( self ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Optional[int] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=_a ) SCREAMING_SNAKE_CASE__ : int = AlignProcessor(tokenizer=_a , image_processor=_a ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = AlignProcessor.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 _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[str] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(images=_a , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Any = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(text=_a ) SCREAMING_SNAKE_CASE__ : Any = tokenizer(_a , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = 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 _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.batch_decode(_a ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = AlignProcessor(tokenizer=_a , image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = """lower newer""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[str] = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
12
0
"""simple docstring""" from collections.abc import Iterable from typing import Generic, TypeVar a :List[Any] = TypeVar("_T") class __a (Generic[_T]): '''simple docstring''' def __init__( self , _a = None ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = list(iterable or [] ) SCREAMING_SNAKE_CASE__ : Any = [] def __len__( self ) -> int: """simple docstring""" return len(self._stacka ) + len(self._stacka ) def __repr__( self ) -> str: """simple docstring""" return f'''Queue({tuple(self._stacka[::-1] + self._stacka )})''' def _a ( self , _a ) -> None: """simple docstring""" self._stacka.append(lowerCamelCase_ ) def _a ( self ) -> _T: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self._stacka.pop SCREAMING_SNAKE_CASE__ : Optional[Any] = self._stacka.append if not self._stacka: while self._stacka: stacka_append(stacka_pop() ) if not self._stacka: raise IndexError("""Queue is empty""" ) return self._stacka.pop() if __name__ == "__main__": from doctest import testmod testmod()
709
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging a :Optional[Any] = logging.get_logger(__name__) a :Union[str, Any] = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = """t5""" _SCREAMING_SNAKE_CASE :List[str] = ["""past_key_values"""] _SCREAMING_SNAKE_CASE :Any = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self , _a=32_128 , _a=512 , _a=64 , _a=2_048 , _a=6 , _a=None , _a=8 , _a=32 , _a=128 , _a=0.1 , _a=1E-6 , _a=1.0 , _a="relu" , _a=True , _a=True , _a=0 , _a=1 , **_a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = d_model SCREAMING_SNAKE_CASE__ : int = d_kv SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_ff SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_layers SCREAMING_SNAKE_CASE__ : int = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry SCREAMING_SNAKE_CASE__ : Tuple = num_heads SCREAMING_SNAKE_CASE__ : Dict = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : str = relative_attention_max_distance SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_factor SCREAMING_SNAKE_CASE__ : Tuple = feed_forward_proj SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : List[str] = self.feed_forward_proj.split("""-""" ) SCREAMING_SNAKE_CASE__ : Dict = act_info[-1] SCREAMING_SNAKE_CASE__ : str = act_info[0] == """gated""" if len(_a ) > 1 and act_info[0] != "gated" or len(_a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": SCREAMING_SNAKE_CASE__ : List[Any] = """gelu_new""" super().__init__( pad_token_id=_a , eos_token_id=_a , is_encoder_decoder=_a , **_a , ) class __a (UpperCamelCase_): '''simple docstring''' @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: SCREAMING_SNAKE_CASE__ : Tuple = """past_encoder_sequence + sequence""" SCREAMING_SNAKE_CASE__ : Optional[int] = {0: """batch"""} SCREAMING_SNAKE_CASE__ : Tuple = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : str = {0: """batch""", 1: """decoder_sequence"""} SCREAMING_SNAKE_CASE__ : Dict = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_a , direction="""inputs""" ) return common_inputs @property def _a ( self ) -> int: """simple docstring""" return 13
12
0
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule a :List[str] = {"tokenization_tapex": ["TapexTokenizer"]} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys a :Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure)
710
"""simple docstring""" from __future__ import annotations import time import numpy as np a :Optional[Any] = [8, 5, 9, 7] a :List[Any] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] a :int = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class __a : '''simple docstring''' def __init__( self , _a , _a , _a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = claim_vector SCREAMING_SNAKE_CASE__ : Any = allocated_resources_table SCREAMING_SNAKE_CASE__ : Any = maximum_claim_table def _a ( self ) -> list[int]: """simple docstring""" return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def _a ( self ) -> list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def _a ( self ) -> list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(_a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def _a ( self ) -> dict[int, list[int]]: """simple docstring""" return {self.__need().index(_a ): i for i in self.__need()} def _a ( self , **_a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.__need() SCREAMING_SNAKE_CASE__ : Any = self.__allocated_resources_table SCREAMING_SNAKE_CASE__ : Dict = self.__available_resources() SCREAMING_SNAKE_CASE__ : Dict = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 50 + """\n""" ) while need_list: SCREAMING_SNAKE_CASE__ : List[str] = False for each_need in need_list: SCREAMING_SNAKE_CASE__ : Dict = True for index, need in enumerate(_a ): if need > available_resources[index]: SCREAMING_SNAKE_CASE__ : Optional[int] = False break if execution: SCREAMING_SNAKE_CASE__ : Any = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: SCREAMING_SNAKE_CASE__ : Tuple = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(_a ) # update available/freed resources stack SCREAMING_SNAKE_CASE__ : Dict = np.array(_a ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(_a ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def _a ( self ) -> Any: """simple docstring""" print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(_a ) + 1}''' + """ """.join(f'''{it:>8}''' for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(_a ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(_a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
12
0
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> list[int]: if num <= 0: raise ValueError("""Input must be a positive integer""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = [True] * (num + 1) SCREAMING_SNAKE_CASE__ : Any = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() a :Optional[int] = int(input("Enter a positive integer: ").strip()) print(prime_sieve_eratosthenes(user_num))
711
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: a :List[Any] = None a :Optional[int] = logging.get_logger(__name__) a :Union[str, Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} a :Optional[int] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } a :Dict = { "xlnet-base-cased": None, "xlnet-large-cased": None, } a :int = "▁" # Segments (not really needed) a :Dict = 0 a :Optional[int] = 1 a :Tuple = 2 a :List[str] = 3 a :Optional[Any] = 4 class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :str = """left""" _SCREAMING_SNAKE_CASE :Optional[Any] = XLNetTokenizer def __init__( self , _a=None , _a=None , _a=False , _a=True , _a=False , _a="<s>" , _a="</s>" , _a="<unk>" , _a="<sep>" , _a="<pad>" , _a="<cls>" , _a="<mask>" , _a=["<eop>", "<eod>"] , **_a , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , additional_special_tokens=_a , **_a , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE__ : List[str] = remove_space SCREAMING_SNAKE_CASE__ : int = keep_accents SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_file SCREAMING_SNAKE_CASE__ : Tuple = False if not self.vocab_file else True def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Tuple = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
12
0
"""simple docstring""" import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy a :Union[str, Any] = logging.get_logger(__name__) a :int = { "artists_file": "artists.json", "lyrics_file": "lyrics.json", "genres_file": "genres.json", } a :List[str] = { "artists_file": { "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json", }, "genres_file": { "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json", }, "lyrics_file": { "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json", }, } a :List[str] = { "jukebox": 512, } class __a (_UpperCamelCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :List[str] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :int = PRETRAINED_LYRIC_TOKENS_SIZES _SCREAMING_SNAKE_CASE :List[str] = ["""input_ids""", """attention_mask"""] def __init__( self , _a , _a , _a , _a=["v3", "v2", "v2"] , _a=512 , _a=5 , _a="<|endoftext|>" , **_a , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = AddedToken(_UpperCAmelCase , lstrip=_UpperCAmelCase , rstrip=_UpperCAmelCase ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else unk_token super().__init__( unk_token=_UpperCAmelCase , n_genres=_UpperCAmelCase , version=_UpperCAmelCase , max_n_lyric_tokens=_UpperCAmelCase , **_UpperCAmelCase , ) SCREAMING_SNAKE_CASE__ : Dict = version SCREAMING_SNAKE_CASE__ : Dict = max_n_lyric_tokens SCREAMING_SNAKE_CASE__ : Dict = n_genres with open(_UpperCAmelCase , encoding="""utf-8""" ) as vocab_handle: SCREAMING_SNAKE_CASE__ : Tuple = json.load(_UpperCAmelCase ) with open(_UpperCAmelCase , encoding="""utf-8""" ) as vocab_handle: SCREAMING_SNAKE_CASE__ : str = json.load(_UpperCAmelCase ) with open(_UpperCAmelCase , encoding="""utf-8""" ) as vocab_handle: SCREAMING_SNAKE_CASE__ : Tuple = json.load(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = R'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: SCREAMING_SNAKE_CASE__ : Any = oov.replace(r"""\-\'""" , r"""\-+\'""" ) SCREAMING_SNAKE_CASE__ : str = regex.compile(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = {v: k for k, v in self.artists_encoder.items()} SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in self.genres_encoder.items()} SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in self.lyrics_encoder.items()} @property def _a ( self ) -> int: """simple docstring""" return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def _a ( self ) -> List[Any]: """simple docstring""" return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder ) def _a ( self , _a , _a , _a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = [self.artists_encoder.get(_UpperCAmelCase , 0 ) for artist in list_artists] for genres in range(len(_UpperCAmelCase ) ): SCREAMING_SNAKE_CASE__ : int = [self.genres_encoder.get(_UpperCAmelCase , 0 ) for genre in list_genres[genres]] SCREAMING_SNAKE_CASE__ : List[Any] = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) SCREAMING_SNAKE_CASE__ : str = [[self.lyrics_encoder.get(_UpperCAmelCase , 0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def _a ( self , _a ) -> Tuple: """simple docstring""" return list(_UpperCAmelCase ) def _a ( self , _a , _a , _a , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_for_tokenization(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self._tokenize(_UpperCAmelCase ) return artist, genre, lyrics def _a ( self , _a , _a , _a , _a = False ) -> Optional[int]: """simple docstring""" for idx in range(len(self.version ) ): if self.version[idx] == "v3": SCREAMING_SNAKE_CASE__ : Any = artists[idx].lower() SCREAMING_SNAKE_CASE__ : Optional[int] = [genres[idx].lower()] else: SCREAMING_SNAKE_CASE__ : int = self._normalize(artists[idx] ) + '''.v2''' SCREAMING_SNAKE_CASE__ : Tuple = [ self._normalize(_UpperCAmelCase ) + '''.v2''' for genre in genres[idx].split("""_""" ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": SCREAMING_SNAKE_CASE__ : Dict = regex.compile(r"""[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+""" ) SCREAMING_SNAKE_CASE__ : Dict = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n''' SCREAMING_SNAKE_CASE__ : List[Any] = {vocab[index]: index + 1 for index in range(len(_UpperCAmelCase ) )} SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(_UpperCAmelCase ) + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.vocab SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in self.vocab.items()} SCREAMING_SNAKE_CASE__ : Tuple = '''''' else: SCREAMING_SNAKE_CASE__ : int = regex.compile(r"""[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+""" ) SCREAMING_SNAKE_CASE__ : str = self._run_strip_accents(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str = lyrics.replace("""\\""" , """\n""" ) SCREAMING_SNAKE_CASE__ : Dict = self.out_of_vocab.sub("""""" , _UpperCAmelCase ), [], [] return artists, genres, lyrics def _a ( self , _a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = unicodedata.normalize("""NFD""" , _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = [] for char in text: SCREAMING_SNAKE_CASE__ : Dict = unicodedata.category(_UpperCAmelCase ) if cat == "Mn": continue output.append(_UpperCAmelCase ) return "".join(_UpperCAmelCase ) def _a ( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ( [chr(_UpperCAmelCase ) for i in range(ord("""a""" ) , ord("""z""" ) + 1 )] + [chr(_UpperCAmelCase ) for i in range(ord("""A""" ) , ord("""Z""" ) + 1 )] + [chr(_UpperCAmelCase ) for i in range(ord("""0""" ) , ord("""9""" ) + 1 )] + ['''.'''] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = frozenset(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = re.compile(r"""_+""" ) SCREAMING_SNAKE_CASE__ : Dict = ''''''.join([c if c in accepted else """_""" for c in text.lower()] ) SCREAMING_SNAKE_CASE__ : Optional[int] = pattern.sub("""_""" , _UpperCAmelCase ).strip("""_""" ) return text def _a ( self , _a ) -> Optional[int]: """simple docstring""" return " ".join(_UpperCAmelCase ) def _a ( self , _a , _a = None , _a = False ) -> Optional[Any]: """simple docstring""" if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Dict = TensorType(_UpperCAmelCase ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( """Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.""" ) import tensorflow as tf SCREAMING_SNAKE_CASE__ : int = tf.constant SCREAMING_SNAKE_CASE__ : str = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError("""Unable to convert output to PyTorch tensors format, PyTorch is not installed.""" ) import torch SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor SCREAMING_SNAKE_CASE__ : Any = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError("""Unable to convert output to JAX tensors format, JAX is not installed.""" ) import jax.numpy as jnp # noqa: F811 SCREAMING_SNAKE_CASE__ : Dict = jnp.array SCREAMING_SNAKE_CASE__ : Tuple = _is_jax else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.asarray SCREAMING_SNAKE_CASE__ : List[Any] = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [inputs] if not is_tensor(_UpperCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = as_tensor(_UpperCAmelCase ) except: # noqa E722 raise ValueError( """Unable to create tensor, you should probably activate truncation and/or padding """ """with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.""" ) return inputs def __call__( self , _a , _a , _a="" , _a="pt" ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [0, 0, 0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [artist] * len(self.version ) SCREAMING_SNAKE_CASE__ : List[str] = [genres] * len(self.version ) SCREAMING_SNAKE_CASE__ : Any = self.tokenize(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = self._convert_token_to_id(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = [-INFINITY] * len(full_tokens[-1] ) SCREAMING_SNAKE_CASE__ : str = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=_UpperCAmelCase ) for i in range(len(self.version ) ) ] return BatchEncoding({"""input_ids""": input_ids, """attention_masks""": attention_masks} ) def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if not os.path.isdir(_UpperCAmelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Any = os.path.join( _UpperCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""artists_file"""] ) with open(_UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.artists_encoder , ensure_ascii=_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : int = os.path.join( _UpperCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""genres_file"""] ) with open(_UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.genres_encoder , ensure_ascii=_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join( _UpperCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""lyrics_file"""] ) with open(_UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.lyrics_encoder , ensure_ascii=_UpperCAmelCase ) ) return (artists_file, genres_file, lyrics_file) def _a ( self , _a , _a , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.artists_decoder.get(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = [self.genres_decoder.get(_UpperCAmelCase ) for genre in genres_index] SCREAMING_SNAKE_CASE__ : Optional[Any] = [self.lyrics_decoder.get(_UpperCAmelCase ) for character in lyric_index] return artist, genres, lyrics
712
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ : Optional[Any] = len(__lowerCAmelCase ) + 1 SCREAMING_SNAKE_CASE__ : int = len(__lowerCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. SCREAMING_SNAKE_CASE__ : Dict = [[0 for i in range(__lowerCAmelCase )] for j in range(__lowerCAmelCase )] # since string of zero length match pattern of zero length SCREAMING_SNAKE_CASE__ : Dict = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : int = dp[0][j - 2] if pattern[j - 1] == """*""" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __lowerCAmelCase ): for j in range(1 , __lowerCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": SCREAMING_SNAKE_CASE__ : Any = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: SCREAMING_SNAKE_CASE__ : List[str] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): SCREAMING_SNAKE_CASE__ : List[Any] = dp[i - 1][j] else: SCREAMING_SNAKE_CASE__ : Optional[int] = 0 else: SCREAMING_SNAKE_CASE__ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") a :Any = "aab" a :Optional[Any] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f'{input_string} matches the given pattern {pattern}') else: print(f'{input_string} does not match with the given pattern {pattern}')
12
0