code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
def _a ( a :int ) -> Tuple: a = [] a = set({'''(''', '''[''', '''{'''} ) a = set({''')''', ''']''', '''}'''} ) a = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(a ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(a ) == 0 or (len(a ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(a ) == 0 def _a ( ) -> int: a = input('''Enter sequence of brackets: ''' ) if is_balanced(a ): print(a , '''is balanced''' ) else: print(a , '''is not balanced''' ) if __name__ == "__main__": main()
0
from __future__ import annotations UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "MIT" UpperCAmelCase__ = "1.0.0" UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "[email protected]" UpperCAmelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : str ) ->None: """simple docstring""" super().__init__() a = [] a = domain def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : list[tuple[str, str | None]] ) ->None: """simple docstring""" 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: a = parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _a ( a :str ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def _a ( a :str ) -> str: return parse.urlparse(a ).netloc def _a ( a :str = "https://github.com" ) -> list[str]: a = get_domain_name(a ) # Initialize the parser a = Parser(a ) try: # Open URL a = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a = requests.get(a ) # Get the valid email. a = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
0
1
UpperCAmelCase__ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase__ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase__ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def _a ( a :int , a :int , a :int ) -> str: assert len(str(a ) ) > 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: a = year // 100 a = (5 * (century % 4) + 2) % 7 a = year % 100 a = centurian % 12 a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
0
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) UpperCAmelCase__ = logging.getLogger() def _a ( ) -> Optional[int]: a = argparse.ArgumentParser() parser.add_argument('''-f''' ) a = parser.parse_args() return args.f def _a ( a :Any ) -> Tuple: a = {} a = os.path.join(a , '''all_results.json''' ) if os.path.exists(a ): with open(a , '''r''' ) as f: a = json.load(a ) else: raise ValueError(F"""can't find {path}""" ) return results def _a ( ) -> int: a = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() UpperCAmelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase_ ( lowercase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : str ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) a = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __lowerCAmelCase ( cls : Optional[int] ) ->Union[str, Any]: """simple docstring""" shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 100 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = 7 if get_gpu_count() > 1 else 2 a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''translation_no_trainer''' ) ) ) @slow def __lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" a = logging.StreamHandler(sys.stdout ) logger.addHandler(__UpperCAmelCase ) a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''image_classification_no_trainer''' ) ) )
0
1
from torch import nn def _a ( a :List[str] ) -> 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
import math def _a ( a :int ) -> list: a = [True] * n a = False a = False a = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): a = i * 2 while index < n: a = False a = index + i a = [2] for i in range(3 , a , 2 ): if is_prime[i]: primes.append(a ) return primes def _a ( a :int = 999_966_663_333 ) -> int: a = math.floor(math.sqrt(a ) ) + 100 a = prime_sieve(a ) a = 0 a = 0 a = primes[prime_index] while (last_prime**2) <= limit: a = primes[prime_index + 1] a = last_prime**2 a = next_prime**2 # Get numbers divisible by lps(current) a = 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) a = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps a = 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 a = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ = {"configuration_plbart": ["PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "PLBartConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["PLBartTokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "PLBART_PRETRAINED_MODEL_ARCHIVE_LIST", "PLBartForCausalLM", "PLBartForConditionalGeneration", "PLBartForSequenceClassification", "PLBartModel", "PLBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure)
0
def _a ( a :float , a :float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(f"""{price_plus_tax(100, 0.25) = }""") print(f"""{price_plus_tax(125.50, 0.05) = }""")
0
1
def _a ( a :int ) -> list[int]: if num <= 0: raise ValueError('''Input must be a positive integer''' ) a = [True] * (num + 1) a = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , a ): a = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase__ = int(input("Enter a positive integer: ").strip()) print(prime_sieve_eratosthenes(user_num))
0
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 lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" a = SMALL_MODEL_IDENTIFIER a = '''pt''' a = '''tf''' def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[str, Any] ) ->List[str]: """simple docstring""" a = TFAutoModel.from_pretrained(self.test_model , from_pt=__UpperCAmelCase ) model_tf.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = '''mock_framework''' # Framework provided - return whatever the user provides a = FeaturesManager.determine_framework(self.test_model , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Both in environment -> use PyTorch a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # Both not in environment -> raise error a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model )
0
1
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def _a ( a :str = "laptop" ) -> DataFrame: a = F"""https://www.amazon.in/laptop/s?k={product}""" a = { '''User-Agent''': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36''', '''Accept-Language''': '''en-US, en;q=0.5''', } a = BeautifulSoup(requests.get(a , headers=a ).text ) # Initialize a Pandas dataframe with the column titles a = 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: a = item.ha.text a = '''https://www.amazon.in/''' + item.ha.a['''href'''] a = item.find('''span''' , attrs={'''class''': '''a-offscreen'''} ).text try: a = item.find('''span''' , attrs={'''class''': '''a-icon-alt'''} ).text except AttributeError: a = '''Not available''' try: a = ( '''₹''' + item.find( '''span''' , attrs={'''class''': '''a-price a-text-price'''} ).text.split('''₹''' )[1] ) except AttributeError: a = '''''' try: a = float( ( ( float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) - float(product_price.strip('''₹''' ).replace(''',''' , '''''' ) ) ) / float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) ) ) * 100 ) except ValueError: a = float('''nan''' ) except AttributeError: pass a = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] a = ''' ''' a = ''' ''' data_frame.index += 1 return data_frame if __name__ == "__main__": UpperCAmelCase__ = "headphones" get_amazon_product_data(product).to_csv(f"""Amazon Product Data for {product}.csv""")
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ProphetNetTokenizer __snake_case = False def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" super().setUp() a = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a = 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 __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str ) ->Dict: """simple docstring""" a = '''UNwant\u00E9d,running''' a = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" a = self.tokenizer_class(self.vocab_file ) a = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__UpperCAmelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [9, 6, 7, 12, 10, 11] ) def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" a = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a = {} for i, token in enumerate(__UpperCAmelCase ): a = i a = WordpieceTokenizer(vocab=__UpperCAmelCase , 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 __lowerCAmelCase ( self : int ) ->int: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] a = [1_037, 2_146, 20_423, 2_005, 7_680, 7_849, 3_989, 1_012, 102] a = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors='''pt''' ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : Any ) ->List[str]: """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 __lowerCAmelCase ( self : List[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = tokenizer.encode('''sequence builders''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def _a ( a :Optional[Any] , a :int , a :List[str] , a :List[str] ) -> Tuple: a = s.rsplit(a , a ) return new.join(a ) def _a ( a :Any ) -> List[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 ( a :Any ) -> List[Any]: a = {} a = ['''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: a = key.replace(F"""{group_key}.""" , F"""{group_key}.group.""" ) if "res_path" in key: a = key.replace('''res_path.''' , '''res_path.path.''' ) if key.endswith('''.w''' ): a = rreplace(a , '''.w''' , '''.weight''' , 1 ) if key.endswith('''.b''' ): a = rreplace(a , '''.b''' , '''.bias''' , 1 ) a = value.float() return upgrade @torch.no_grad() def _a ( a :Union[str, Any] , a :Optional[Any] , a :Optional[int]=None , a :str=True ) -> Tuple: from dall_e import Encoder a = Encoder() if os.path.exists(a ): a = torch.load(a ) else: a = torch.hub.load_state_dict_from_url(a ) if isinstance(a , a ): a = ckpt.state_dict() encoder.load_state_dict(a ) if config_path is not None: a = FlavaImageCodebookConfig.from_pretrained(a ) else: a = FlavaImageCodebookConfig() a = FlavaImageCodebook(a ).eval() a = encoder.state_dict() a = upgrade_state_dict(a ) hf_model.load_state_dict(a ) a = hf_model.state_dict() a = count_parameters(a ) a = count_parameters(a ) assert torch.allclose(a , a , atol=1e-3 ) if save_checkpoint: hf_model.save_pretrained(a ) else: return hf_state_dict if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to flava checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") UpperCAmelCase__ = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake UpperCAmelCase__ = numpy.array([0, 0]) UpperCAmelCase__ = numpy.array([0.5, 0.866_0254]) UpperCAmelCase__ = numpy.array([1, 0]) UpperCAmelCase__ = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def _a ( a :list[numpy.ndarray] , a :int ) -> list[numpy.ndarray]: a = initial_vectors for _ in range(a ): a = iteration_step(a ) return vectors def _a ( a :list[numpy.ndarray] ) -> list[numpy.ndarray]: a = [] for i, start_vector in enumerate(vectors[:-1] ): a = vectors[i + 1] new_vectors.append(a ) a = 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 ( a :numpy.ndarray , a :float ) -> numpy.ndarray: a = numpy.radians(a ) a , a = numpy.cos(a ), numpy.sin(a ) a = numpy.array(((c, -s), (s, c)) ) return numpy.dot(a , a ) def _a ( a :list[numpy.ndarray] ) -> None: a = 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() a , a = zip(*a ) plt.plot(a , a ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase__ = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
0
def _a ( a :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 a = gray_code_sequence_string(a ) # # convert them to integers for i in range(len(a ) ): a = int(sequence[i] , 2 ) return sequence def _a ( a :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"] a = 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 a = gray_code_sequence_string(bit_count - 1 ) a = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): a = '''0''' + smaller_sequence[i] sequence.append(a ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): a = '''1''' + smaller_sequence[i] sequence.append(a ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , *__UpperCAmelCase : str , **__UpperCAmelCase : Tuple ) ->None: """simple docstring""" warnings.warn( '''The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use OwlViTImageProcessor instead.''' , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
0
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 lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() # fmt: off a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on a = 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] ) ) a = { '''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], } a = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , **__UpperCAmelCase : List[Any] ) ->int: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , **__UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = self.get_tokenizer() a = self.get_image_processor() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) a = 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) 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(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
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 lowercase_ : '''simple docstring''' __snake_case = None __snake_case = None __snake_case = None # sigma(t_i) @classmethod def __lowerCAmelCase ( cls : Optional[int] ) ->Optional[int]: """simple docstring""" return cls() @dataclass class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = 42 __snake_case = 42 __snake_case = 42 class lowercase_ ( lowercase , lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return True @register_to_config def __init__( self : Optional[int] , __UpperCAmelCase : float = 0.02 , __UpperCAmelCase : float = 100 , __UpperCAmelCase : float = 1.007 , __UpperCAmelCase : float = 80 , __UpperCAmelCase : float = 0.05 , __UpperCAmelCase : float = 50 , ) ->int: """simple docstring""" pass def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" return KarrasVeSchedulerState.create() def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : KarrasVeSchedulerState , __UpperCAmelCase : int , __UpperCAmelCase : Tuple = () ) ->KarrasVeSchedulerState: """simple docstring""" a = jnp.arange(0 , __UpperCAmelCase )[::-1].copy() a = [ ( 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=__UpperCAmelCase , schedule=jnp.array(__UpperCAmelCase , dtype=jnp.floataa ) , timesteps=__UpperCAmelCase , ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : KarrasVeSchedulerState , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : float , __UpperCAmelCase : random.KeyArray , ) ->Tuple[jnp.ndarray, float]: """simple docstring""" if self.config.s_min <= sigma <= self.config.s_max: a = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: a = 0 # sample eps ~ N(0, S_noise^2 * I) a = random.split(__UpperCAmelCase , num=1 ) a = self.config.s_noise * random.normal(key=__UpperCAmelCase , shape=sample.shape ) a = sigma + gamma * sigma a = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : KarrasVeSchedulerState , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : float , __UpperCAmelCase : float , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : bool = True , ) ->Union[FlaxKarrasVeOutput, Tuple]: """simple docstring""" a = sample_hat + sigma_hat * model_output a = (sample_hat - pred_original_sample) / sigma_hat a = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__UpperCAmelCase , derivative=__UpperCAmelCase , state=__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : KarrasVeSchedulerState , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : float , __UpperCAmelCase : float , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : jnp.ndarray , __UpperCAmelCase : bool = True , ) ->Union[FlaxKarrasVeOutput, Tuple]: """simple docstring""" a = sample_prev + sigma_prev * model_output a = (sample_prev - pred_original_sample) / sigma_prev a = 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=__UpperCAmelCase , derivative=__UpperCAmelCase , state=__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : KarrasVeSchedulerState , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : int ) ->Union[str, Any]: """simple docstring""" raise NotImplementedError()
0
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 ( a :List[Any] ) -> Optional[int]: a = [] 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 ( a :List[Any] , a :Optional[int] ) -> Dict: a = [] 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 ( a :Any ) -> List[Any]: a = [] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", '''stage2.cls_token''') ) return token def _a ( ) -> Optional[int]: a = [] 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 ( a :Tuple , a :Optional[int] , a :List[Any] , a :Union[str, Any] ) -> Optional[int]: a = '''imagenet-1k-id2label.json''' a = 1_000 a = '''huggingface/label-files''' a = num_labels a = json.load(open(cached_download(hf_hub_url(a , a , repo_type='''dataset''' ) ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} a = a = CvtConfig(num_labels=a , idalabel=a , labelaid=a ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13": a = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21": a = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: a = [2, 2, 20] a = [3, 12, 16] a = [192, 768, 1_024] a = CvtForImageClassification(a ) a = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) a = image_size a = torch.load(a , map_location=torch.device('''cpu''' ) ) a = OrderedDict() a = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: a = list_of_state_dict + cls_token(a ) a = list_of_state_dict + embeddings(a ) for cnt in range(config.depth[idx] ): a = list_of_state_dict + attention(a , a ) a = list_of_state_dict + final() for gg in list_of_state_dict: print(a ) for i in range(len(a ) ): a = original_weights[list_of_state_dict[i][1]] model.load_state_dict(a ) model.save_pretrained(a ) image_processor.save_pretrained(a ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": UpperCAmelCase__ = 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=384, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=R"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase__ = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
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 UpperCAmelCase__ = "bert-base-cased" UpperCAmelCase__ = "google/pegasus-xsum" UpperCAmelCase__ = [" Sam ate lunch today.", "Sams lunch ingredients."] UpperCAmelCase__ = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"] UpperCAmelCase__ = "patrickvonplaten/t5-tiny-random" UpperCAmelCase__ = "sshleifer/bart-tiny-random" UpperCAmelCase__ = "sshleifer/tiny-mbart" UpperCAmelCase__ = "sshleifer/tiny-marian-en-de" def _a ( a :Path , a :list ) -> Optional[int]: a = '''\n'''.join(a ) Path(a ).open('''w''' ).writelines(a ) def _a ( a :Dict ) -> Dict: for split in ["train", "val", "test"]: _dump_articles(os.path.join(a , F"""{split}.source""" ) , a ) _dump_articles(os.path.join(a , F"""{split}.target""" ) , a ) return tmp_dir class lowercase_ ( lowercase ): '''simple docstring''' @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def __lowerCAmelCase ( self : int , __UpperCAmelCase : List[str] ) ->Tuple: """simple docstring""" a = AutoTokenizer.from_pretrained(__UpperCAmelCase ) a = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) a = max(len(tokenizer.encode(__UpperCAmelCase ) ) for a in ARTICLES ) a = max(len(tokenizer.encode(__UpperCAmelCase ) ) for a in SUMMARIES ) a = 4 a = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated a , a = '''ro_RO''', '''de_DE''' # ignored for all but mbart, but never causes error. a = SeqaSeqDataset( __UpperCAmelCase , data_dir=__UpperCAmelCase , type_path='''train''' , max_source_length=__UpperCAmelCase , max_target_length=__UpperCAmelCase , src_lang=__UpperCAmelCase , tgt_lang=__UpperCAmelCase , ) a = DataLoader(__UpperCAmelCase , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(__UpperCAmelCase , __UpperCAmelCase ) 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 a = 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 __lowerCAmelCase ( self : int , __UpperCAmelCase : str ) ->Optional[int]: """simple docstring""" a = AutoTokenizer.from_pretrained(__UpperCAmelCase ) a = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) a = max(len(tokenizer.encode(__UpperCAmelCase ) ) for a in ARTICLES ) a = max(len(tokenizer.encode(__UpperCAmelCase ) ) for a in SUMMARIES ) a = 4 a = LegacySeqaSeqDataset( __UpperCAmelCase , data_dir=__UpperCAmelCase , type_path='''train''' , max_source_length=20 , max_target_length=__UpperCAmelCase , ) a = DataLoader(__UpperCAmelCase , 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 __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = AutoTokenizer.from_pretrained('''facebook/mbart-large-cc25''' ) a = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) a = tmp_dir.joinpath('''train.source''' ).open().readlines() a = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(__UpperCAmelCase , __UpperCAmelCase , 128 , __UpperCAmelCase ) a = {x.name for x in tmp_dir.iterdir()} a = {x.name for x in save_dir.iterdir()} a = 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(__UpperCAmelCase ) < len(__UpperCAmelCase ) assert len(__UpperCAmelCase ) == 1 assert len(packed_examples[0] ) == sum(len(__UpperCAmelCase ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason='''This test requires fairseq''' ) def __lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" if not FAIRSEQ_AVAILABLE: return a , a , a = self._get_dataset(max_len=64 ) a = 64 a = ds.make_dynamic_sampler(__UpperCAmelCase , required_batch_size_multiple=__UpperCAmelCase ) a = [len(__UpperCAmelCase ) for x in batch_sampler] assert len(set(__UpperCAmelCase ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(__UpperCAmelCase ) == len(__UpperCAmelCase ) # no dropped or added examples a = DataLoader(__UpperCAmelCase , batch_sampler=__UpperCAmelCase , collate_fn=ds.collate_fn , num_workers=2 ) a = [] a = [] for batch in data_loader: a = batch['''input_ids'''].shape a = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple a = np.product(batch['''input_ids'''].shape ) num_src_per_batch.append(__UpperCAmelCase ) if num_src_tokens > (max_tokens * 1.1): failures.append(__UpperCAmelCase ) assert num_src_per_batch[0] == max(__UpperCAmelCase ) if failures: raise AssertionError(F"""too many tokens in {len(__UpperCAmelCase )} batches""" ) def __lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" a , a , a = self._get_dataset(max_len=512 ) a = 2 a = ds.make_sortish_sampler(__UpperCAmelCase , shuffle=__UpperCAmelCase ) a = DataLoader(__UpperCAmelCase , batch_size=__UpperCAmelCase , collate_fn=ds.collate_fn , num_workers=2 ) a = DataLoader(__UpperCAmelCase , batch_size=__UpperCAmelCase , collate_fn=ds.collate_fn , num_workers=2 , sampler=__UpperCAmelCase ) a = tokenizer.pad_token_id def count_pad_tokens(__UpperCAmelCase : Any , __UpperCAmelCase : Dict="input_ids" ): return [batch[k].eq(__UpperCAmelCase ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(__UpperCAmelCase , k='''labels''' ) ) < sum(count_pad_tokens(__UpperCAmelCase , k='''labels''' ) ) assert sum(count_pad_tokens(__UpperCAmelCase ) ) < sum(count_pad_tokens(__UpperCAmelCase ) ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Tuple=1_000 , __UpperCAmelCase : Dict=128 ) ->Any: """simple docstring""" if os.getenv('''USE_REAL_DATA''' , __UpperCAmelCase ): a = '''examples/seq2seq/wmt_en_ro''' a = max_len * 2 * 64 if not Path(__UpperCAmelCase ).joinpath('''train.len''' ).exists(): save_len_file(__UpperCAmelCase , __UpperCAmelCase ) else: a = '''examples/seq2seq/test_data/wmt_en_ro''' a = max_len * 4 save_len_file(__UpperCAmelCase , __UpperCAmelCase ) a = AutoTokenizer.from_pretrained(__UpperCAmelCase ) a = SeqaSeqDataset( __UpperCAmelCase , data_dir=__UpperCAmelCase , type_path='''train''' , max_source_length=__UpperCAmelCase , max_target_length=__UpperCAmelCase , n_obs=__UpperCAmelCase , ) return ds, max_tokens, tokenizer def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" a , a , a = self._get_dataset() a = set(DistributedSortishSampler(__UpperCAmelCase , 256 , num_replicas=2 , rank=0 , add_extra_examples=__UpperCAmelCase ) ) a = set(DistributedSortishSampler(__UpperCAmelCase , 256 , num_replicas=2 , rank=1 , add_extra_examples=__UpperCAmelCase ) ) assert idsa.intersection(__UpperCAmelCase ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = AutoTokenizer.from_pretrained(__UpperCAmelCase , use_fast=__UpperCAmelCase ) if tok_name == MBART_TINY: a = SeqaSeqDataset( __UpperCAmelCase , 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''' , ) a = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: a = SeqaSeqDataset( __UpperCAmelCase , 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 , ) a = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(__UpperCAmelCase ) == 1 if tok_name == BART_TINY else len(__UpperCAmelCase ) == 0
0
from __future__ import annotations UpperCAmelCase__ = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ = [ [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 UpperCAmelCase__ = [ [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 ( a :Matrix , a :int , a :int , a :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 ( a :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 ( a :Matrix ) -> Matrix | None: if location := find_empty_location(a ): a , a = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): a = digit if sudoku(a ) is not None: return grid a = 0 return None def _a ( a :Matrix ) -> None: for row in grid: for cell in row: print(a , 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" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") UpperCAmelCase__ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
0
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_megatron_bert": ["MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegatronBertConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = KandinskyVaaPriorPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt''', '''negative_prompt'''] __snake_case = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" return 100 @property def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''num_attention_heads''': 2, '''attention_head_dim''': 12, '''embedding_dim''': self.text_embedder_hidden_size, '''num_layers''': 1, } a = PriorTransformer(**__UpperCAmelCase ) # 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 a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def __lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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 , ) a = CLIPVisionModelWithProjection(__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" a = CLIPImageProcessor( crop_size=224 , do_center_crop=__UpperCAmelCase , do_normalize=__UpperCAmelCase , do_resize=__UpperCAmelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = self.dummy_prior a = self.dummy_image_encoder a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_image_processor a = UnCLIPScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1_000 , clip_sample=__UpperCAmelCase , clip_sample_range=10.0 , ) a = { '''prior''': prior, '''image_encoder''': image_encoder, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''scheduler''': scheduler, '''image_processor''': image_processor, } return components def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : str=0 ) ->int: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.image_embeds a = pipe( **self.get_dummy_inputs(__UpperCAmelCase ) , return_dict=__UpperCAmelCase , )[0] a = image[0, -10:] a = image_from_tuple[0, -10:] assert image.shape == (1, 32) a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) 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 __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = torch_device == '''cpu''' a = True a = False self._test_inference_batch_single_identical( test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , ) @skip_mps def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = torch_device == '''cpu''' a = False self._test_attention_slicing_forward_pass( test_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , )
0
1
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) UpperCAmelCase__ = logging.getLogger() def _a ( ) -> Optional[int]: a = argparse.ArgumentParser() parser.add_argument('''-f''' ) a = parser.parse_args() return args.f def _a ( a :Any ) -> Tuple: a = {} a = os.path.join(a , '''all_results.json''' ) if os.path.exists(a ): with open(a , '''r''' ) as f: a = json.load(a ) else: raise ValueError(F"""can't find {path}""" ) return results def _a ( ) -> int: a = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() UpperCAmelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase_ ( lowercase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : str ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) a = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __lowerCAmelCase ( cls : Optional[int] ) ->Union[str, Any]: """simple docstring""" shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 100 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = 7 if get_gpu_count() > 1 else 2 a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''translation_no_trainer''' ) ) ) @slow def __lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" a = logging.StreamHandler(sys.stdout ) logger.addHandler(__UpperCAmelCase ) a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''image_classification_no_trainer''' ) ) )
0
from math import factorial UpperCAmelCase__ = {str(digit): factorial(digit) for digit in range(10)} def _a ( a :int ) -> int: if not isinstance(a , a ): 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(a ) ) def _a ( a :int = 60 , a :int = 1_000_000 ) -> int: if not isinstance(a , a ) or not isinstance(a , a ): 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 a = 0 # the cached sizes of the previous chains a = {} for start_chain_element in range(1 , a ): # The temporary set will contain the elements of the chain a = set() a = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. a = 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(a ) chain_set_length += 1 a = digit_factorial_sum(a ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] a = 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
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase__ = { "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: UpperCAmelCase__ = [ "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: UpperCAmelCase__ = [ "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: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
def _a ( a :int = 100 ) -> int: a = n * (n + 1) * (2 * n + 1) / 6 a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
0
1
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets UpperCAmelCase__ = "\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n" UpperCAmelCase__ = "\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.\n" UpperCAmelCase__ = R"\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting \"1/2\" to \"\\frac{1}{2}\")\n\nExamples:\n >>> metric = datasets.load_metric(\"competition_math\")\n >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])\n >>> print(results)\n {'accuracy': 1.0}\n" @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase_ ( datasets.Metric ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """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 __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : int , __UpperCAmelCase : List[Any] ) ->Tuple: """simple docstring""" a = 0.0 for i, j in zip(__UpperCAmelCase , __UpperCAmelCase ): n_correct += 1.0 if math_equivalence.is_equiv(__UpperCAmelCase , __UpperCAmelCase ) else 0.0 a = n_correct / len(__UpperCAmelCase ) return { "accuracy": accuracy, }
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def _a ( a :Namespace ) -> Optional[int]: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) UpperCAmelCase__ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class lowercase_ ( lowercase ): '''simple docstring''' @staticmethod def __lowerCAmelCase ( __UpperCAmelCase : ArgumentParser ) ->List[str]: """simple docstring""" a = 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=__UpperCAmelCase , required=__UpperCAmelCase , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=__UpperCAmelCase , required=__UpperCAmelCase , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=__UpperCAmelCase , required=__UpperCAmelCase , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=__UpperCAmelCase , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=__UpperCAmelCase , default=__UpperCAmelCase , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=__UpperCAmelCase ) def __init__( self : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : str , *__UpperCAmelCase : Optional[Any] , ) ->Optional[Any]: """simple docstring""" a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(F"""Loading model {model_type}""" ) a = model_type a = tf_checkpoint a = pytorch_dump_output a = config a = finetuning_task_name def __lowerCAmelCase ( self : List[str] ) ->Optional[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(__UpperCAmelCase ) 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(__UpperCAmelCase ) 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(__UpperCAmelCase ) 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(__UpperCAmelCase ) 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(__UpperCAmelCase ) if "ckpt" in self._tf_checkpoint.lower(): a = self._tf_checkpoint a = '''''' else: a = self._tf_checkpoint a = '''''' convert_transfo_xl_checkpoint_to_pytorch( __UpperCAmelCase , self._config , self._pytorch_dump_output , __UpperCAmelCase ) 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(__UpperCAmelCase ) 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(__UpperCAmelCase ) 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
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ShapEPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt'''] __snake_case = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" return 8 @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, } a = PriorTransformer(**__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, ), } a = ShapERenderer(**__UpperCAmelCase ) return model def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" a = self.dummy_prior a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_renderer a = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_024 , prediction_type='''sample''' , use_karras_sigmas=__UpperCAmelCase , clip_sample=__UpperCAmelCase , clip_sample_range=1.0 , ) a = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str=0 ) ->Optional[int]: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.images[0] a = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = torch_device == '''cpu''' a = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , ) def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = 1 a = 2 a = self.get_dummy_inputs(__UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: a = batch_size * [inputs[key]] a = pipe(**__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''' ) a = ShapEPipeline.from_pretrained('''openai/shap-e''' ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) a = pipe( '''a shark''' , generator=__UpperCAmelCase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
0
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class lowercase_ ( lowercase , lowercase ): '''simple docstring''' __snake_case = '''convnextv2''' def __init__( self : Any , __UpperCAmelCase : Tuple=3 , __UpperCAmelCase : Dict=4 , __UpperCAmelCase : Optional[Any]=4 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Union[str, Any]="gelu" , __UpperCAmelCase : Optional[Any]=0.02 , __UpperCAmelCase : List[str]=1e-1_2 , __UpperCAmelCase : Tuple=0.0 , __UpperCAmelCase : Any=224 , __UpperCAmelCase : Any=None , __UpperCAmelCase : List[Any]=None , **__UpperCAmelCase : str , ) ->Union[str, Any]: """simple docstring""" super().__init__(**__UpperCAmelCase ) a = num_channels a = patch_size a = num_stages a = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes a = [3, 3, 9, 3] if depths is None else depths a = hidden_act a = initializer_range a = layer_norm_eps a = drop_path_rate a = image_size a = ['''stem'''] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] a , a = get_aligned_output_features_output_indices( out_features=__UpperCAmelCase , out_indices=__UpperCAmelCase , stage_names=self.stage_names )
0
from __future__ import annotations import time import numpy as np UpperCAmelCase__ = [8, 5, 9, 7] UpperCAmelCase__ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCAmelCase__ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[list[int]] , ) ->None: """simple docstring""" a = claim_vector a = allocated_resources_table a = maximum_claim_table def __lowerCAmelCase ( self : Any ) ->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 __lowerCAmelCase ( self : Optional[int] ) ->list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def __lowerCAmelCase ( self : Union[str, Any] ) ->list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__UpperCAmelCase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def __lowerCAmelCase ( self : Tuple ) ->dict[int, list[int]]: """simple docstring""" return {self.__need().index(__UpperCAmelCase ): i for i in self.__need()} def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" a = self.__need() a = self.__allocated_resources_table a = self.__available_resources() a = 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: a = False for each_need in need_list: a = True for index, need in enumerate(__UpperCAmelCase ): if need > available_resources[index]: a = False break if execution: a = 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: a = original_need_index print(F"""Process {process_number + 1} is executing.""" ) # remove the process run from stack need_list.remove(__UpperCAmelCase ) # update available/freed resources stack a = np.array(__UpperCAmelCase ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(__UpperCAmelCase ) 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 __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(__UpperCAmelCase ) + 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(__UpperCAmelCase ) + 1}""" + ''' '''.join(F"""{it:>8}""" for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1

Dataset Card for "python_codestyles-random-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 at least one codestyle rule, which is called a random 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.198 samples in total and 91.098 positive and 91.100 negative samples.

Downloads last month
67
Edit dataset card

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