code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: __snake_case : Dict = [] __snake_case : Any = set({'(', '[', '{'} ) __snake_case : List[Any] = set({')', ']', '}'} ) __snake_case : List[Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(_UpperCAmelCase ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(_UpperCAmelCase ) == 0 or (len(_UpperCAmelCase ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(_UpperCAmelCase ) == 0 def a_ ( ) -> Optional[int]: __snake_case : Any = input('Enter sequence of brackets: ' ) if is_balanced(_UpperCAmelCase ): print(_UpperCAmelCase ,'is balanced' ) else: print(_UpperCAmelCase ,'is not balanced' ) if __name__ == "__main__": main()
0
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
1
'''simple docstring''' A__ : Any = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__ : Tuple = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __snake_case : str = year // 1_00 __snake_case : Tuple = (5 * (century % 4) + 2) % 7 __snake_case : Any = year % 1_00 __snake_case : Optional[int] = centurian % 12 __snake_case : List[Any] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __snake_case : Optional[int] = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) __snake_case : Dict = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
1
'''simple docstring''' from torch import nn def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function: {act_fn}''' )
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A__ : Tuple = {'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[Any] = ['''PLBartTokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''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__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
0
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
1
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list[int]: if num <= 0: raise ValueError('Input must be a positive integer' ) __snake_case : Tuple = [True] * (num + 1) __snake_case : Tuple = 2 while p * p <= num: if primes[p]: for i in range(p * p ,num + 1 ,_UpperCAmelCase ): __snake_case : str = False p += 1 return [prime for prime in range(2 ,num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() A__ : Any = int(input('''Enter a positive integer: ''').strip()) print(prime_sieve_eratosthenes(user_num))
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
1
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def a_ ( _UpperCAmelCase : str = "laptop" ) -> DataFrame: __snake_case : List[Any] = f'''https://www.amazon.in/laptop/s?k={product}''' __snake_case : Optional[Any] = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5', } __snake_case : List[str] = BeautifulSoup(requests.get(_UpperCAmelCase ,headers=_UpperCAmelCase ).text ) # Initialize a Pandas dataframe with the column titles __snake_case : Optional[int] = DataFrame( columns=[ 'Product Title', 'Product Link', 'Current Price of the product', 'Product Rating', 'MRP of the product', 'Discount', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( 'div' ,attrs={'class': 's-result-item', 'data-component-type': 's-search-result'} ,) ,soup.find_all('div' ,attrs={'class': 'a-row a-size-base a-color-base'} ) ,): try: __snake_case : List[Any] = item.ha.text __snake_case : Optional[int] = 'https://www.amazon.in/' + item.ha.a['href'] __snake_case : Optional[Any] = item.find('span' ,attrs={'class': 'a-offscreen'} ).text try: __snake_case : Any = item.find('span' ,attrs={'class': 'a-icon-alt'} ).text except AttributeError: __snake_case : Optional[Any] = 'Not available' try: __snake_case : Any = ( '₹' + item.find( 'span' ,attrs={'class': 'a-price a-text-price'} ).text.split('₹' )[1] ) except AttributeError: __snake_case : Optional[Any] = '' try: __snake_case : List[str] = float( ( ( float(product_mrp.strip('₹' ).replace(',' ,'' ) ) - float(product_price.strip('₹' ).replace(',' ,'' ) ) ) / float(product_mrp.strip('₹' ).replace(',' ,'' ) ) ) * 1_00 ) except ValueError: __snake_case : Optional[Any] = float('nan' ) except AttributeError: pass __snake_case : Tuple = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] __snake_case : Any = ' ' __snake_case : Tuple = ' ' data_frame.index += 1 return data_frame if __name__ == "__main__": A__ : List[Any] = '''headphones''' get_amazon_product_data(product).to_csv(F"""Amazon Product Data for {product}.csv""")
0
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def a_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : int ,_UpperCAmelCase : Tuple ) -> int: __snake_case : int = s.rsplit(_UpperCAmelCase ,_UpperCAmelCase ) return new.join(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if 'encoder.embeddings' not in key else 0 for key, param in state_dict.items() ) def a_ ( _UpperCAmelCase : Tuple ) -> int: __snake_case : Union[str, Any] = {} __snake_case : str = ['group_1', 'group_2', 'group_3', 'group_4'] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: __snake_case : Tuple = key.replace(f'''{group_key}.''' ,f'''{group_key}.group.''' ) if "res_path" in key: __snake_case : Optional[int] = key.replace('res_path.' ,'res_path.path.' ) if key.endswith('.w' ): __snake_case : Dict = rreplace(_UpperCAmelCase ,'.w' ,'.weight' ,1 ) if key.endswith('.b' ): __snake_case : List[Any] = rreplace(_UpperCAmelCase ,'.b' ,'.bias' ,1 ) __snake_case : List[str] = value.float() return upgrade @torch.no_grad() def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=None ,_UpperCAmelCase : List[str]=True ) -> List[Any]: from dall_e import Encoder __snake_case : List[str] = Encoder() if os.path.exists(_UpperCAmelCase ): __snake_case : str = torch.load(_UpperCAmelCase ) else: __snake_case : Any = torch.hub.load_state_dict_from_url(_UpperCAmelCase ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = ckpt.state_dict() encoder.load_state_dict(_UpperCAmelCase ) if config_path is not None: __snake_case : Union[str, Any] = FlavaImageCodebookConfig.from_pretrained(_UpperCAmelCase ) else: __snake_case : Tuple = FlavaImageCodebookConfig() __snake_case : str = FlavaImageCodebook(_UpperCAmelCase ).eval() __snake_case : int = encoder.state_dict() __snake_case : Dict = upgrade_state_dict(_UpperCAmelCase ) hf_model.load_state_dict(_UpperCAmelCase ) __snake_case : Optional[Any] = hf_model.state_dict() __snake_case : Union[str, Any] = count_parameters(_UpperCAmelCase ) __snake_case : List[str] = count_parameters(_UpperCAmelCase ) assert torch.allclose(_UpperCAmelCase ,_UpperCAmelCase ,atol=1E-3 ) if save_checkpoint: hf_model.save_pretrained(_UpperCAmelCase ) else: return hf_state_dict if __name__ == "__main__": A__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to flava checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') A__ : Union[str, Any] = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''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__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake A__ : Dict = numpy.array([0, 0]) A__ : Tuple = numpy.array([0.5, 0.8_66_02_54]) A__ : Any = numpy.array([1, 0]) A__ : Dict = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def a_ ( _UpperCAmelCase : list[numpy.ndarray] ,_UpperCAmelCase : int ) -> list[numpy.ndarray]: __snake_case : Tuple = initial_vectors for _ in range(_UpperCAmelCase ): __snake_case : Tuple = iteration_step(_UpperCAmelCase ) return vectors def a_ ( _UpperCAmelCase : list[numpy.ndarray] ) -> list[numpy.ndarray]: __snake_case : List[Any] = [] for i, start_vector in enumerate(vectors[:-1] ): __snake_case : Union[str, Any] = vectors[i + 1] new_vectors.append(_UpperCAmelCase ) __snake_case : Union[str, Any] = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 ,60 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def a_ ( _UpperCAmelCase : numpy.ndarray ,_UpperCAmelCase : float ) -> numpy.ndarray: __snake_case : int = numpy.radians(_UpperCAmelCase ) __snake_case , __snake_case : Tuple = numpy.cos(_UpperCAmelCase ), numpy.sin(_UpperCAmelCase ) __snake_case : Union[str, Any] = numpy.array(((c, -s), (s, c)) ) return numpy.dot(_UpperCAmelCase ,_UpperCAmelCase ) def a_ ( _UpperCAmelCase : list[numpy.ndarray] ) -> None: __snake_case : List[str] = plt.gca() axes.set_aspect('equal' ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() __snake_case , __snake_case : List[Any] = zip(*_UpperCAmelCase ) plt.plot(_UpperCAmelCase ,_UpperCAmelCase ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() A__ : Optional[Any] = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor A__ : Dict = logging.get_logger(__name__) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Tuple , *__a : List[Any] , **__a : Any ) -> None: '''simple docstring''' warnings.warn( 'The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use OwlViTImageProcessor instead.' , __a , ) super().__init__(*__a , **__a )
0
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __snake_case : Any = 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] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = 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 : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.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 , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, 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 self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class snake_case__ : # setable values A__ = None A__ = None A__ = None # sigma(t_i) @classmethod def A_ ( cls : Optional[int] ) -> List[str]: '''simple docstring''' return cls() @dataclass class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = 42 A__ = 42 A__ = 42 class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return True @register_to_config def __init__( self : Any , __a : float = 0.0_2 , __a : float = 100 , __a : float = 1.0_0_7 , __a : float = 80 , __a : float = 0.0_5 , __a : float = 50 , ) -> Dict: '''simple docstring''' pass def A_ ( self : int ) -> Union[str, Any]: '''simple docstring''' return KarrasVeSchedulerState.create() def A_ ( self : Dict , __a : KarrasVeSchedulerState , __a : int , __a : Tuple = () ) -> KarrasVeSchedulerState: '''simple docstring''' __snake_case : Dict = jnp.arange(0 , __a )[::-1].copy() __snake_case : List[Any] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=__a , schedule=jnp.array(__a , dtype=jnp.floataa ) , timesteps=__a , ) def A_ ( self : List[Any] , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : random.KeyArray , ) -> Tuple[jnp.ndarray, float]: '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: __snake_case : Union[str, Any] = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: __snake_case : Optional[Any] = 0 # sample eps ~ N(0, S_noise^2 * I) __snake_case : Optional[int] = random.split(__a , num=1 ) __snake_case : List[str] = self.config.s_noise * random.normal(key=__a , shape=sample.shape ) __snake_case : Optional[Any] = sigma + gamma * sigma __snake_case : Dict = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def A_ ( self : List[str] , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : float , __a : jnp.ndarray , __a : bool = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: '''simple docstring''' __snake_case : Union[str, Any] = sample_hat + sigma_hat * model_output __snake_case : str = (sample_hat - pred_original_sample) / sigma_hat __snake_case : int = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__a , derivative=__a , state=__a ) def A_ ( self : Tuple , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : float , __a : jnp.ndarray , __a : jnp.ndarray , __a : jnp.ndarray , __a : bool = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: '''simple docstring''' __snake_case : Union[str, Any] = sample_prev + sigma_prev * model_output __snake_case : Optional[int] = (sample_prev - pred_original_sample) / sigma_prev __snake_case : Tuple = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__a , derivative=__a , state=__a ) def A_ ( self : Dict , __a : KarrasVeSchedulerState , __a : Any , __a : Dict , __a : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError()
0
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
'''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__ : Optional[int] = '''bert-base-cased''' A__ : Optional[Any] = '''google/pegasus-xsum''' A__ : List[Any] = [''' Sam ate lunch today.''', '''Sams lunch ingredients.'''] A__ : str = ['''A very interesting story about what I ate for lunch.''', '''Avocado, celery, turkey, coffee'''] A__ : str = '''patrickvonplaten/t5-tiny-random''' A__ : Union[str, Any] = '''sshleifer/bart-tiny-random''' A__ : List[Any] = '''sshleifer/tiny-mbart''' A__ : Dict = '''sshleifer/tiny-marian-en-de''' def a_ ( _UpperCAmelCase : Path ,_UpperCAmelCase : list ) -> List[str]: __snake_case : Tuple = '\n'.join(_UpperCAmelCase ) Path(_UpperCAmelCase ).open('w' ).writelines(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str ) -> Any: 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 snake_case__ ( SCREAMING_SNAKE_CASE_ ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def A_ ( self : str , __a : Tuple ) -> str: '''simple docstring''' __snake_case : List[str] = AutoTokenizer.from_pretrained(__a ) __snake_case : int = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) __snake_case : int = max(len(tokenizer.encode(__a ) ) for a in ARTICLES ) __snake_case : Dict = max(len(tokenizer.encode(__a ) ) for a in SUMMARIES ) __snake_case : Any = 4 __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 __snake_case , __snake_case : Optional[int] = 'ro_RO', 'de_DE' # ignored for all but mbart, but never causes error. __snake_case : Any = SeqaSeqDataset( __a , data_dir=__a , type_path='train' , max_source_length=__a , max_target_length=__a , src_lang=__a , tgt_lang=__a , ) __snake_case : Union[str, Any] = DataLoader(__a , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(__a , __a ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place __snake_case : Tuple = 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 : Optional[Any] , __a : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : int = AutoTokenizer.from_pretrained(__a ) __snake_case : Optional[Any] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) __snake_case : str = max(len(tokenizer.encode(__a ) ) for a in ARTICLES ) __snake_case : Union[str, Any] = max(len(tokenizer.encode(__a ) ) for a in SUMMARIES ) __snake_case : Any = 4 __snake_case : Dict = LegacySeqaSeqDataset( __a , data_dir=__a , type_path='train' , max_source_length=20 , max_target_length=__a , ) __snake_case : str = DataLoader(__a , 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] ) -> str: '''simple docstring''' __snake_case : str = AutoTokenizer.from_pretrained('facebook/mbart-large-cc25' ) __snake_case : Dict = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) __snake_case : Any = tmp_dir.joinpath('train.source' ).open().readlines() __snake_case : List[str] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(__a , __a , 128 , __a ) __snake_case : int = {x.name for x in tmp_dir.iterdir()} __snake_case : int = {x.name for x in save_dir.iterdir()} __snake_case : Dict = 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(__a ) < len(__a ) assert len(__a ) == 1 assert len(packed_examples[0] ) == sum(len(__a ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason='This test requires fairseq' ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' if not FAIRSEQ_AVAILABLE: return __snake_case , __snake_case , __snake_case : str = self._get_dataset(max_len=64 ) __snake_case : Union[str, Any] = 64 __snake_case : Union[str, Any] = ds.make_dynamic_sampler(__a , required_batch_size_multiple=__a ) __snake_case : Any = [len(__a ) for x in batch_sampler] assert len(set(__a ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(__a ) == len(__a ) # no dropped or added examples __snake_case : Union[str, Any] = DataLoader(__a , batch_sampler=__a , collate_fn=ds.collate_fn , num_workers=2 ) __snake_case : Optional[Any] = [] __snake_case : Dict = [] for batch in data_loader: __snake_case : int = batch['input_ids'].shape __snake_case : List[Any] = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple __snake_case : Tuple = np.product(batch['input_ids'].shape ) num_src_per_batch.append(__a ) if num_src_tokens > (max_tokens * 1.1): failures.append(__a ) assert num_src_per_batch[0] == max(__a ) if failures: raise AssertionError(f'''too many tokens in {len(__a )} batches''' ) def A_ ( self : Tuple ) -> Dict: '''simple docstring''' __snake_case , __snake_case , __snake_case : Union[str, Any] = self._get_dataset(max_len=512 ) __snake_case : Any = 2 __snake_case : Dict = ds.make_sortish_sampler(__a , shuffle=__a ) __snake_case : List[Any] = DataLoader(__a , batch_size=__a , collate_fn=ds.collate_fn , num_workers=2 ) __snake_case : int = DataLoader(__a , batch_size=__a , collate_fn=ds.collate_fn , num_workers=2 , sampler=__a ) __snake_case : Any = tokenizer.pad_token_id def count_pad_tokens(__a : Tuple , __a : Optional[int]="input_ids" ): return [batch[k].eq(__a ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(__a , k='labels' ) ) < sum(count_pad_tokens(__a , k='labels' ) ) assert sum(count_pad_tokens(__a ) ) < sum(count_pad_tokens(__a ) ) assert len(__a ) == len(__a ) def A_ ( self : Optional[Any] , __a : int=1000 , __a : int=128 ) -> str: '''simple docstring''' if os.getenv('USE_REAL_DATA' , __a ): __snake_case : str = 'examples/seq2seq/wmt_en_ro' __snake_case : Union[str, Any] = max_len * 2 * 64 if not Path(__a ).joinpath('train.len' ).exists(): save_len_file(__a , __a ) else: __snake_case : List[Any] = 'examples/seq2seq/test_data/wmt_en_ro' __snake_case : List[Any] = max_len * 4 save_len_file(__a , __a ) __snake_case : Optional[Any] = AutoTokenizer.from_pretrained(__a ) __snake_case : Optional[Any] = SeqaSeqDataset( __a , data_dir=__a , type_path='train' , max_source_length=__a , max_target_length=__a , n_obs=__a , ) return ds, max_tokens, tokenizer def A_ ( self : Any ) -> Dict: '''simple docstring''' __snake_case , __snake_case , __snake_case : List[str] = self._get_dataset() __snake_case : Dict = set(DistributedSortishSampler(__a , 256 , num_replicas=2 , rank=0 , add_extra_examples=__a ) ) __snake_case : str = set(DistributedSortishSampler(__a , 256 , num_replicas=2 , rank=1 , add_extra_examples=__a ) ) assert idsa.intersection(__a ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def A_ ( self : int , __a : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Any = AutoTokenizer.from_pretrained(__a , use_fast=__a ) if tok_name == MBART_TINY: __snake_case : Union[str, Any] = SeqaSeqDataset( __a , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='train' , max_source_length=4 , max_target_length=8 , src_lang='EN' , tgt_lang='FR' , ) __snake_case : List[Any] = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: __snake_case : Optional[Any] = SeqaSeqDataset( __a , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='train' , max_source_length=4 , max_target_length=8 , ) __snake_case : Dict = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(__a ) == 1 if tok_name == BART_TINY else len(__a ) == 0
0
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Any = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys A__ : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
1
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A__ : Any = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2Config'''], '''feature_extraction_wav2vec2''': ['''Wav2Vec2FeatureExtractor'''], '''processing_wav2vec2''': ['''Wav2Vec2Processor'''], '''tokenization_wav2vec2''': ['''Wav2Vec2CTCTokenizer''', '''Wav2Vec2Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Wav2Vec2ForAudioFrameClassification''', '''Wav2Vec2ForCTC''', '''Wav2Vec2ForMaskedLM''', '''Wav2Vec2ForPreTraining''', '''Wav2Vec2ForSequenceClassification''', '''Wav2Vec2ForXVector''', '''Wav2Vec2Model''', '''Wav2Vec2PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWav2Vec2ForCTC''', '''TFWav2Vec2Model''', '''TFWav2Vec2PreTrainedModel''', '''TFWav2Vec2ForSequenceClassification''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''FlaxWav2Vec2ForCTC''', '''FlaxWav2Vec2ForPreTraining''', '''FlaxWav2Vec2Model''', '''FlaxWav2Vec2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
1
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets A__ : List[str] = '''\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } ''' A__ : Optional[int] = '''\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy. ''' A__ : Dict = R''' Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting "1/2" to "\\frac{1}{2}") Examples: >>> metric = datasets.load_metric("competition_math") >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"]) >>> print(results) {\'accuracy\': 1.0} ''' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): def A_ ( self : str ) -> Tuple: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' ), 'references': datasets.Value('string' ), } ) , homepage='https://github.com/hendrycks/math' , codebase_urls=['https://github.com/hendrycks/math'] , ) def A_ ( self : str , __a : List[str] , __a : Optional[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = 0.0 for i, j in zip(__a , __a ): n_correct += 1.0 if math_equivalence.is_equiv(__a , __a ) else 0.0 __snake_case : Optional[Any] = n_correct / len(__a ) return { "accuracy": accuracy, }
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
1
'''simple docstring''' from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def a_ ( _UpperCAmelCase : Namespace ) -> Union[str, Any]: return ConvertCommand( args.model_type ,args.tf_checkpoint ,args.pytorch_dump_output ,args.config ,args.finetuning_task_name ) A__ : Optional[int] = ''' transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. ''' class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @staticmethod def A_ ( __a : ArgumentParser ) -> str: '''simple docstring''' __snake_case : List[str] = 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=__a , required=__a , help='Model\'s type.' ) train_parser.add_argument( '--tf_checkpoint' , type=__a , required=__a , help='TensorFlow checkpoint path or folder.' ) train_parser.add_argument( '--pytorch_dump_output' , type=__a , required=__a , help='Path to the PyTorch saved model output.' ) train_parser.add_argument('--config' , type=__a , default='' , help='Configuration file path or folder.' ) train_parser.add_argument( '--finetuning_task_name' , type=__a , default=__a , help='Optional fine-tuning task name if the TF model was a finetuned model.' , ) train_parser.set_defaults(func=__a ) def __init__( self : Tuple , __a : str , __a : str , __a : str , __a : str , __a : str , *__a : int , ) -> List[str]: '''simple docstring''' __snake_case : Dict = logging.get_logger('transformers-cli/converting' ) self._logger.info(f'''Loading model {model_type}''' ) __snake_case : Dict = model_type __snake_case : Optional[Any] = tf_checkpoint __snake_case : str = pytorch_dump_output __snake_case : Dict = config __snake_case : str = finetuning_task_name def A_ ( self : List[str] ) -> List[Any]: '''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(__a ) 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(__a ) 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(__a ) 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(__a ) 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(__a ) if "ckpt" in self._tf_checkpoint.lower(): __snake_case : Optional[int] = self._tf_checkpoint __snake_case : List[str] = '' else: __snake_case : int = self._tf_checkpoint __snake_case : Tuple = '' convert_transfo_xl_checkpoint_to_pytorch( __a , self._config , self._pytorch_dump_output , __a ) 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(__a ) 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(__a ) 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]' )
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
1
'''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[str] = logging.get_logger(__name__) A__ : Dict = { '''facebook/convnextv2-tiny-1k-224''': '''https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A__ = '''convnextv2''' def __init__( self : Union[str, Any] , __a : Tuple=3 , __a : str=4 , __a : Any=4 , __a : Optional[Any]=None , __a : int=None , __a : int="gelu" , __a : Optional[int]=0.0_2 , __a : List[Any]=1e-12 , __a : Tuple=0.0 , __a : str=224 , __a : Any=None , __a : List[str]=None , **__a : List[str] , ) -> str: '''simple docstring''' super().__init__(**__a ) __snake_case : Dict = num_channels __snake_case : List[Any] = patch_size __snake_case : Dict = num_stages __snake_case : Optional[Any] = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __snake_case : Dict = [3, 3, 9, 3] if depths is None else depths __snake_case : Union[str, Any] = hidden_act __snake_case : List[Any] = initializer_range __snake_case : Optional[Any] = layer_norm_eps __snake_case : Optional[int] = drop_path_rate __snake_case : str = image_size __snake_case : str = ['stem'] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] __snake_case , __snake_case : Optional[int] = get_aligned_output_features_output_indices( out_features=__a , out_indices=__a , stage_names=self.stage_names )
0
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> 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 : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> 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 : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = 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: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, 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: __snake_case : str = 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 __snake_case : Union[str, Any] = 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 : List[str] ) -> Optional[int]: '''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()
0
1

Dataset Card for "python_codestyles-single-500"

This dataset contains negative and positive examples with python code of compliance with a code style. A positive example represents compliance with the code style (label is 1). Each example is composed of two components, the first component consists of a code that either conforms to the code style or violates it and the second component corresponding to an example code that already conforms to a code style. In total, the dataset contains 500 completely different code styles. The code styles differ in exactly one codestyle rule, which is called a single codestyle dataset variant. The dataset consists of a training and test group, with none of the code styles overlapping between groups. In addition, both groups contain completely different underlying codes.

The examples contain source code from the following repositories:

repository tag or commit
TheAlgorithms/Python f614ed72170011d2d439f7901e1c8daa7deac8c4
huggingface/transformers v4.31.0
huggingface/datasets 2.13.1
huggingface/diffusers v0.18.2
huggingface/accelerate v0.21.0

You can find the corresponding code styles of the examples in the file additional_data.json. The code styles in the file are split by training and test group and the index corresponds to the class for the columns code_codestyle and style_context_codestyle in the dataset.

There are 182.184 samples in total and 91.084 positive and 91.100 negative samples.

Downloads last month
0
Edit dataset card

Models trained or fine-tuned on infinityofspace/python_codestyles-single-500