code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
def __snake_case ( lowerCAmelCase_ ) -> int: SCREAMING_SNAKE_CASE__ = 0 while num > 0: digit_sum += num % 1_0 num //= 1_0 return digit_sum def __snake_case ( lowerCAmelCase_ = 1_0_0 ) -> int: SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 for i in range(2 , max_n + 1 ): SCREAMING_SNAKE_CASE__ = pre_numerator SCREAMING_SNAKE_CASE__ = 2 * i // 3 if i % 3 == 0 else 1 SCREAMING_SNAKE_CASE__ = cur_numerator SCREAMING_SNAKE_CASE__ = e_cont * pre_numerator + temp return sum_digits(lowerCAmelCase_ ) if __name__ == "__main__": print(F'{solution() = }')
100
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 __a =42 class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : int ): _a = [[] for _ in range(__a )] _a = size def __getitem__( self : int , __a : int ): return iter(self._graph[vertex] ) @property def UpperCamelCase__ ( self : Dict ): return self._size def UpperCamelCase__ ( self : Union[str, Any] , __a : int , __a : int , __a : int ): if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(__a , __a ) ) def UpperCamelCase__ ( self : Tuple , __a : int , __a : int ): _a = deque([start_vertex] ) _a = [None] * self.size _a = 0 while queue: _a = queue.popleft() _a = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _a = current_distance + edge.weight _a = distances[edge.destination_vertex] if ( isinstance(__a , __a ) and new_distance >= dest_vertex_distance ): continue _a = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
692
0
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort lowerCAmelCase__ : List[Any] =logging.get_logger(__name__) lowerCAmelCase__ : List[str] ={ 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class __lowercase : """simple docstring""" def __init__( self , lowerCAmelCase__=None , **lowerCAmelCase__ ): """simple docstring""" logger.info('`diffusers.OnnxRuntimeModel` is experimental and might change in the future.' ) SCREAMING_SNAKE_CASE_ : Any = model SCREAMING_SNAKE_CASE_ : int = kwargs.get('model_save_dir' , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.get('latest_model_name' , lowerCAmelCase__ ) def __call__( self , **lowerCAmelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {k: np.array(lowerCAmelCase__ ) for k, v in kwargs.items()} return self.model.run(lowerCAmelCase__ , lowerCAmelCase__ ) @staticmethod def UpperCamelCase__ ( lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None ): """simple docstring""" if provider is None: logger.info('No onnxruntime provider specified, using CPUExecutionProvider' ) SCREAMING_SNAKE_CASE_ : Any = 'CPUExecutionProvider' return ort.InferenceSession(lowerCAmelCase__ , providers=[provider] , sess_options=lowerCAmelCase__ ) def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , **lowerCAmelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = file_name if file_name is not None else ONNX_WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_save_dir.joinpath(self.latest_model_name ) SCREAMING_SNAKE_CASE_ : List[str] = Path(lowerCAmelCase__ ).joinpath(lowerCAmelCase__ ) try: shutil.copyfile(lowerCAmelCase__ , lowerCAmelCase__ ) except shutil.SameFileError: pass # copy external weights (for models >2GB) SCREAMING_SNAKE_CASE_ : int = self.model_save_dir.joinpath(lowerCAmelCase__ ) if src_path.exists(): SCREAMING_SNAKE_CASE_ : Dict = Path(lowerCAmelCase__ ).joinpath(lowerCAmelCase__ ) try: shutil.copyfile(lowerCAmelCase__ , lowerCAmelCase__ ) except shutil.SameFileError: pass def UpperCamelCase__ ( self , lowerCAmelCase__ , **lowerCAmelCase__ , ): """simple docstring""" if os.path.isfile(lowerCAmelCase__ ): logger.error(F'''Provided path ({save_directory}) should be a directory, not a file''' ) return os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) # saving model weights/files self._save_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) @classmethod def UpperCamelCase__ ( cls , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , **lowerCAmelCase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = OnnxRuntimeModel.load_model( os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) , provider=lowerCAmelCase__ , sess_options=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : List[str] = Path(lowerCAmelCase__ ) # load model from hub else: # download model SCREAMING_SNAKE_CASE_ : int = hf_hub_download( repo_id=lowerCAmelCase__ , filename=lowerCAmelCase__ , use_auth_token=lowerCAmelCase__ , revision=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , force_download=lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE_ : Any = Path(lowerCAmelCase__ ).parent SCREAMING_SNAKE_CASE_ : str = Path(lowerCAmelCase__ ).name SCREAMING_SNAKE_CASE_ : Union[str, Any] = OnnxRuntimeModel.load_model(lowerCAmelCase__ , provider=lowerCAmelCase__ , sess_options=lowerCAmelCase__ ) return cls(model=lowerCAmelCase__ , **lowerCAmelCase__ ) @classmethod def UpperCamelCase__ ( cls , lowerCAmelCase__ , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = None , **lowerCAmelCase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = None if len(str(lowerCAmelCase__ ).split('@' ) ) == 2: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = model_id.split('@' ) return cls._from_pretrained( model_id=lowerCAmelCase__ , revision=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , force_download=lowerCAmelCase__ , use_auth_token=lowerCAmelCase__ , **lowerCAmelCase__ , )
101
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =FlaxAutoencoderKL @property def UpperCamelCase__ ( self : str ): _a = 4 _a = 3 _a = (32, 32) _a = jax.random.PRNGKey(0 ) _a = jax.random.uniform(__a , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCamelCase__ ( self : List[Any] ): _a = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } _a = self.dummy_input return init_dict, inputs_dict
692
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor __magic_name__ : List[Any] = logging.get_logger(__name__) class lowercase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *_A , **_A ): '''simple docstring''' warnings.warn( """The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use PoolFormerImageProcessor instead.""" , _A , ) super().__init__(*_A , **_A )
102
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration lowerCAmelCase_ : List[Any] = [ # tf -> hf ('/', '.'), ('layer_', 'layers.'), ('kernel', 'weight'), ('beta', 'bias'), ('gamma', 'weight'), ('pegasus', 'model'), ] lowerCAmelCase_ : Optional[int] = [ ('.output.dense', '.fc2'), ('intermediate.LayerNorm', 'final_layer_norm'), ('intermediate.dense', 'fc1'), ] lowerCAmelCase_ : Any = ( INIT_COMMON + [ ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.out_proj'), ('attention.self', 'self_attn'), ('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'), ('attention.encdec_output.dense', 'encoder_attn.out_proj'), ('attention.encdec', 'encoder_attn'), ('key', 'k_proj'), ('value', 'v_proj'), ('query', 'q_proj'), ('decoder.LayerNorm', 'decoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Tuple = ( INIT_COMMON + [ ('embeddings.word_embeddings', 'shared.weight'), ('embeddings.position_embeddings', 'embed_positions.weight'), ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.output'), ('attention.self', 'self_attn.self'), ('encoder.LayerNorm', 'encoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Optional[int] = [ 'encdec/key/bias', 'encdec/query/bias', 'encdec/value/bias', 'self/key/bias', 'self/query/bias', 'self/value/bias', 'encdec_output/dense/bias', 'attention/output/dense/bias', ] def _lowerCamelCase ( lowercase : Any , lowercase : Any ) -> Optional[Any]: for tf_name, hf_name in patterns: _a = k.replace(lowercase , lowercase ) return k def _lowerCamelCase ( lowercase : dict , lowercase : dict ) -> BigBirdPegasusForConditionalGeneration: _a = BigBirdPegasusConfig(**lowercase ) _a = BigBirdPegasusForConditionalGeneration(lowercase ) _a = torch_model.state_dict() _a = {} # separating decoder weights _a = {k: tf_weights[k] for k in tf_weights if k.startswith("pegasus/decoder" )} _a = {k: tf_weights[k] for k in tf_weights if not k.startswith("pegasus/decoder" )} for k, v in tqdm(decoder_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = DECODER_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict: raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' for k, v in tqdm(remaining_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = REMAINING_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' _a = mapping["model.embed_positions.weight"] _a = mapping.pop("model.embed_positions.weight" ) _a , _a = torch_model.load_state_dict(lowercase , strict=lowercase ) _a = [ k for k in missing if k not in [ "final_logits_bias", "model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight", ] ] assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}' assert extra == [], F'no matches found for the following tf keys {extra}' return torch_model def _lowerCamelCase ( lowercase : List[Any] ) -> Dict: _a = tf.train.list_variables(lowercase ) _a = {} _a = ["global_step"] for name, shape in tqdm(lowercase , desc="converting tf checkpoint to dict" ): _a = any(pat in name for pat in ignore_name ) if skip_key: continue _a = tf.train.load_variable(lowercase , lowercase ) _a = array return tf_weights def _lowerCamelCase ( lowercase : str , lowercase : str , lowercase : dict ) -> Union[str, Any]: _a = get_tf_weights_as_numpy(lowercase ) _a = convert_bigbird_pegasus(lowercase , lowercase ) torch_model.save_pretrained(lowercase ) if __name__ == "__main__": lowerCAmelCase_ : str = argparse.ArgumentParser() parser.add_argument('--tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('--save_dir', default=None, type=str, help='Path to the output PyTorch model.') lowerCAmelCase_ : Optional[Any] = parser.parse_args() lowerCAmelCase_ : Optional[Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
0
"""simple docstring""" from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" _snake_case = SMALL_MODEL_IDENTIFIER _snake_case = '''pt''' _snake_case = '''tf''' def __UpperCAmelCase ( self : int , __lowerCamelCase : Any ): """simple docstring""" _snake_case = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__lowerCamelCase ) def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : int ): """simple docstring""" _snake_case = TFAutoModel.from_pretrained(self.test_model , from_pt=__lowerCamelCase ) model_tf.save_pretrained(__lowerCamelCase ) def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" _snake_case = '''mock_framework''' # Framework provided - return whatever the user provides _snake_case = FeaturesManager.determine_framework(self.test_model , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__lowerCamelCase ) _snake_case = FeaturesManager.determine_framework(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__lowerCamelCase ) _snake_case = FeaturesManager.determine_framework(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__lowerCamelCase ) _snake_case = FeaturesManager.determine_framework(__lowerCamelCase ) self.assertEqual(__lowerCamelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__lowerCamelCase ) _snake_case = FeaturesManager.determine_framework(__lowerCamelCase ) self.assertEqual(__lowerCamelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__lowerCamelCase ): _snake_case = FeaturesManager.determine_framework(__lowerCamelCase ) def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case = MagicMock(return_value=__lowerCamelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCamelCase ): _snake_case = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCamelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow _snake_case = MagicMock(return_value=__lowerCamelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __lowerCamelCase ): _snake_case = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCamelCase , self.framework_tf ) # Both in environment -> use PyTorch _snake_case = MagicMock(return_value=__lowerCamelCase ) _snake_case = MagicMock(return_value=__lowerCamelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCamelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __lowerCamelCase ): _snake_case = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCamelCase , self.framework_pt ) # Both not in environment -> raise error _snake_case = MagicMock(return_value=__lowerCamelCase ) _snake_case = MagicMock(return_value=__lowerCamelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCamelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __lowerCamelCase ): with self.assertRaises(__lowerCamelCase ): _snake_case = FeaturesManager.determine_framework(self.test_model )
103
'''simple docstring''' def _lowerCamelCase ( lowercase : str , lowercase : list[str] ) -> str: _a = "" for word_or_phrase in separated: if not isinstance(lowercase , lowercase ): raise Exception("join() accepts only strings to be joined" ) joined += word_or_phrase + separator return joined.strip(lowercase ) if __name__ == "__main__": from doctest import testmod testmod()
692
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { """google/canine-s""": """https://huggingface.co/google/canine-s/resolve/main/config.json""", # See all CANINE models at https://huggingface.co/models?filter=canine } class UpperCamelCase__ ( _lowerCAmelCase ): """simple docstring""" A__ : Union[str, Any] = "canine" def __init__( self , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=16384 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=0.0_2 , SCREAMING_SNAKE_CASE__=1e-12 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=0xE000 , SCREAMING_SNAKE_CASE__=0xE001 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=8 , SCREAMING_SNAKE_CASE__=16384 , SCREAMING_SNAKE_CASE__=128 , **SCREAMING_SNAKE_CASE__ , ) -> Union[str, Any]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A__ = max_position_embeddings A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = initializer_range A__ = type_vocab_size A__ = layer_norm_eps # Character config: A__ = downsampling_rate A__ = upsampling_kernel_size A__ = num_hash_functions A__ = num_hash_buckets A__ = local_transformer_stride
104
'''simple docstring''' lowerCAmelCase_ : Optional[Any] = '\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' lowerCAmelCase_ : List[Any] = [{'type': 'code', 'content': INSTALL_CONTENT}] lowerCAmelCase_ : Dict = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
692
0
from __future__ import annotations import math def __UpperCAmelCase ( lowerCamelCase_ : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True UpperCamelCase__ : List[str] = [num for num in range(3, 10_00_01, 2) if not is_prime(num)] def __UpperCAmelCase ( lowerCamelCase_ : int ) -> list[int]: """simple docstring""" if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise ValueError('n must be an integer' ) if n <= 0: raise ValueError('n must be >= 0' ) SCREAMING_SNAKE_CASE_ : Dict = [] for num in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE_ : List[Any] = 0 while 2 * i * i <= odd_composites[num]: SCREAMING_SNAKE_CASE_ : Dict = odd_composites[num] - 2 * i * i if is_prime(lowerCamelCase_ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(lowerCamelCase_ ) == n: return list_nums return [] def __UpperCAmelCase ( ) -> int: """simple docstring""" return compute_nums(1 )[0] if __name__ == "__main__": print(F"""{solution() = }""")
105
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') lowerCAmelCase_ : Optional[Any] = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) lowerCAmelCase_ : Dict = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) lowerCAmelCase_ : Dict = BeautifulSoup(res.text, 'html.parser') lowerCAmelCase_ : Optional[int] = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f"""https://google.com{link.get('href')}""")
692
0
import random from typing import Any def lowerCamelCase_ ( lowerCAmelCase__ : list ) -> list[Any]: '''simple docstring''' for _ in range(len(lowerCAmelCase__ ) ): A = random.randint(0 , len(lowerCAmelCase__ ) - 1 ) A = random.randint(0 , len(lowerCAmelCase__ ) - 1 ) A , A = data[b], data[a] return data if __name__ == "__main__": __snake_case :List[str] =[0, 1, 2, 3, 4, 5, 6, 7] __snake_case :List[Any] =['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List', integers, strings) print('FY Shuffle', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
106
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets lowerCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) lowerCAmelCase_ : Tuple = '\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n author = "Moosavi, Nafise Sadat and\n Strube, Michael",\n booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/P16-1060",\n doi = "10.18653/v1/P16-1060",\n pages = "632--642",\n}\n\n' lowerCAmelCase_ : Union[str, Any] = '\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n' lowerCAmelCase_ : Union[str, Any] = '\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting \'keep_singletons=False\', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n \'mentions\': mentions\n \'muc\': MUC metric [Vilain et al, 1995]\n \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n \'ceafe\': CEAFe [Luo et al., 2005]\n \'lea\': LEA [Moosavi and Strube, 2016]\n \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric(\'coval\')\n >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\',\n ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\',\n ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\',\n ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\',\n ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\',\n ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n' def _lowerCamelCase ( lowercase : Tuple , lowercase : List[Any] , lowercase : Optional[int]=False , lowercase : Dict=False , lowercase : Optional[int]=True , lowercase : Union[str, Any]=False , lowercase : int="dummy_doc" ) -> Union[str, Any]: _a = {doc: key_lines} _a = {doc: sys_lines} _a = {} _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a , _a = reader.get_doc_mentions(lowercase , key_doc_lines[doc] , lowercase ) key_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) _a , _a = reader.get_doc_mentions(lowercase , sys_doc_lines[doc] , lowercase ) sys_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) if remove_nested: _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters _a = reader.get_mention_assignments(lowercase , lowercase ) _a = reader.get_mention_assignments(lowercase , lowercase ) _a = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( "Number of removed nested coreferring mentions in the key " F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( "Number of resulting singleton clusters in the key " F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' "files, respectively" ) return doc_coref_infos def _lowerCamelCase ( lowercase : List[Any] , lowercase : Any , lowercase : Optional[Any] , lowercase : Union[str, Any] , lowercase : Any , lowercase : List[str] , lowercase : Dict ) -> str: _a = get_coref_infos(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) _a = {} _a = 0 _a = 0 for name, metric in metrics: _a , _a , _a = evaluator.evaluate_documents(lowercase , lowercase , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} ) logger.info( name.ljust(10 ) , F'Recall: {recall * 100:.2f}' , F' Precision: {precision * 100:.2f}' , F' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: _a = (conll / 3) * 100 logger.info(F'CoNLL score: {conll:.2f}' ) output_scores.update({"conll_score": conll} ) return output_scores def _lowerCamelCase ( lowercase : Any ) -> str: _a = False for line in key_lines: if not line.startswith("#" ): if len(line.split() ) > 6: _a = line.split()[5] if not parse_col == "-": _a = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE (datasets.Metric ): """simple docstring""" def UpperCamelCase__ ( self : str ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Sequence(datasets.Value("string" ) ), } ) , codebase_urls=["https://github.com/ns-moosavi/coval"] , reference_urls=[ "https://github.com/ns-moosavi/coval", "https://www.aclweb.org/anthology/P16-1060", "http://www.conll.cemantix.org/2012/data.html", ] , ) def UpperCamelCase__ ( self : int , __a : Any , __a : int , __a : Optional[Any]=True , __a : Optional[Any]=False , __a : str=False , __a : List[str]=False ): _a = [ ("mentions", evaluator.mentions), ("muc", evaluator.muc), ("bcub", evaluator.b_cubed), ("ceafe", evaluator.ceafe), ("lea", evaluator.lea), ] if min_span: _a = util.check_gold_parse_annotation(__a ) if not has_gold_parse: raise NotImplementedError("References should have gold parse annotation to use 'min_span'." ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" _a = evaluate( key_lines=__a , sys_lines=__a , metrics=__a , NP_only=__a , remove_nested=__a , keep_singletons=__a , min_span=__a , ) return score
692
0
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''') _UpperCAmelCase : List[Any] = logging.getLogger(__name__) @dataclass class lowercase_ : """simple docstring""" __lowerCAmelCase = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) @dataclass class lowercase_ : """simple docstring""" __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Train language if it is different from the evaluation language."} ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"} , ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __lowerCAmelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) __lowerCAmelCase = field( default=_UpperCamelCase , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def _SCREAMING_SNAKE_CASE ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _A , _A , _A = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_xnli' , __snake_case ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _A = training_args.get_process_log_level() logger.setLevel(__snake_case ) datasets.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _A = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _A = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: _A = load_dataset( 'xnli' , model_args.language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: _A = load_dataset( 'xnli' , model_args.train_language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) _A = train_dataset.features['label'].names if training_args.do_eval: _A = load_dataset( 'xnli' , model_args.language , split='validation' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) _A = eval_dataset.features['label'].names if training_args.do_predict: _A = load_dataset( 'xnli' , model_args.language , split='test' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) _A = predict_dataset.features['label'].names # Labels _A = len(__snake_case ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _A = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__snake_case , idalabel={str(__snake_case ): label for i, label in enumerate(__snake_case )} , labelaid={label: i for i, label in enumerate(__snake_case )} , finetuning_task='xnli' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) _A = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) _A = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: _A = 'max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch _A = False def preprocess_function(__snake_case : List[Any] ): # Tokenize the texts return tokenizer( examples['premise'] , examples['hypothesis'] , padding=__snake_case , max_length=data_args.max_seq_length , truncation=__snake_case , ) if training_args.do_train: if data_args.max_train_samples is not None: _A = min(len(__snake_case ) , data_args.max_train_samples ) _A = train_dataset.select(range(__snake_case ) ) with training_args.main_process_first(desc='train dataset map pre-processing' ): _A = train_dataset.map( __snake_case , batched=__snake_case , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on train dataset' , ) # Log a few random samples from the training set: for index in random.sample(range(len(__snake_case ) ) , 3 ): logger.info(F'Sample {index} of the training set: {train_dataset[index]}.' ) if training_args.do_eval: if data_args.max_eval_samples is not None: _A = min(len(__snake_case ) , data_args.max_eval_samples ) _A = eval_dataset.select(range(__snake_case ) ) with training_args.main_process_first(desc='validation dataset map pre-processing' ): _A = eval_dataset.map( __snake_case , batched=__snake_case , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on validation dataset' , ) if training_args.do_predict: if data_args.max_predict_samples is not None: _A = min(len(__snake_case ) , data_args.max_predict_samples ) _A = predict_dataset.select(range(__snake_case ) ) with training_args.main_process_first(desc='prediction dataset map pre-processing' ): _A = predict_dataset.map( __snake_case , batched=__snake_case , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on prediction dataset' , ) # Get the metric function _A = evaluate.load('xnli' ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__snake_case : EvalPrediction ): _A = p.predictions[0] if isinstance(p.predictions , __snake_case ) else p.predictions _A = np.argmax(__snake_case , axis=1 ) return metric.compute(predictions=__snake_case , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: _A = default_data_collator elif training_args.fpaa: _A = DataCollatorWithPadding(__snake_case , pad_to_multiple_of=8 ) else: _A = None # Initialize our Trainer _A = Trainer( model=__snake_case , args=__snake_case , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__snake_case , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _A = None if training_args.resume_from_checkpoint is not None: _A = training_args.resume_from_checkpoint elif last_checkpoint is not None: _A = last_checkpoint _A = trainer.train(resume_from_checkpoint=__snake_case ) _A = train_result.metrics _A = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__snake_case ) ) _A = min(__snake_case , len(__snake_case ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , __snake_case ) trainer.save_metrics('train' , __snake_case ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) _A = trainer.evaluate(eval_dataset=__snake_case ) _A = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__snake_case ) _A = min(__snake_case , len(__snake_case ) ) trainer.log_metrics('eval' , __snake_case ) trainer.save_metrics('eval' , __snake_case ) # Prediction if training_args.do_predict: logger.info('*** Predict ***' ) _A , _A , _A = trainer.predict(__snake_case , metric_key_prefix='predict' ) _A = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__snake_case ) ) _A = min(__snake_case , len(__snake_case ) ) trainer.log_metrics('predict' , __snake_case ) trainer.save_metrics('predict' , __snake_case ) _A = np.argmax(__snake_case , axis=1 ) _A = os.path.join(training_args.output_dir , 'predictions.txt' ) if trainer.is_world_process_zero(): with open(__snake_case , 'w' ) as writer: writer.write('index\tprediction\n' ) for index, item in enumerate(__snake_case ): _A = label_list[item] writer.write(F'{index}\t{item}\n' ) if __name__ == "__main__": main()
107
'''simple docstring''' import math def _lowerCamelCase ( lowercase : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowercase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCamelCase ( lowercase : float = 0.1 ) -> int: _a = 3 _a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowercase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __a: Dict = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' _lowerCamelCase = ['''pixel_values'''] def __init__( self : Any , lowerCamelCase : bool = True , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 255 , lowerCamelCase : bool = True , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : bool = True , **lowerCamelCase : List[Any] , ) -> None: """simple docstring""" super().__init__(**lowerCamelCase ) _UpperCAmelCase = size if size is not None else {"""height""": 384, """width""": 384} _UpperCAmelCase = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = resample _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _UpperCAmelCase = image_std if image_std is not None else OPENAI_CLIP_STD _UpperCAmelCase = do_convert_rgb def lowerCamelCase ( self : Any , lowerCamelCase : np.ndarray , lowerCamelCase : Dict[str, int] , lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : str , ) -> np.ndarray: """simple docstring""" _UpperCAmelCase = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" ) _UpperCAmelCase = (size["""height"""], size["""width"""]) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowerCamelCase ( self : Tuple , lowerCamelCase : np.ndarray , lowerCamelCase : Union[int, float] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Dict , ) -> Union[str, Any]: """simple docstring""" return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowerCamelCase ( self : Tuple , lowerCamelCase : np.ndarray , lowerCamelCase : Union[float, List[float]] , lowerCamelCase : Union[float, List[float]] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : List[Any] , ) -> np.ndarray: """simple docstring""" return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowerCamelCase ( self : Dict , lowerCamelCase : ImageInput , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[Dict[str, int]] = None , lowerCamelCase : PILImageResampling = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[float] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : bool = None , lowerCamelCase : ChannelDimension = ChannelDimension.FIRST , **lowerCamelCase : List[str] , ) -> PIL.Image.Image: """simple docstring""" _UpperCAmelCase = do_resize if do_resize is not None else self.do_resize _UpperCAmelCase = resample if resample is not None else self.resample _UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale _UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize _UpperCAmelCase = image_mean if image_mean is not None else self.image_mean _UpperCAmelCase = image_std if image_std is not None else self.image_std _UpperCAmelCase = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _UpperCAmelCase = size if size is not None else self.size _UpperCAmelCase = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) _UpperCAmelCase = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: _UpperCAmelCase = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. _UpperCAmelCase = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: _UpperCAmelCase = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_rescale: _UpperCAmelCase = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: _UpperCAmelCase = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] _UpperCAmelCase = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] _UpperCAmelCase = BatchFeature(data={"""pixel_values""": images} , tensor_type=lowerCamelCase ) return encoded_outputs
108
'''simple docstring''' import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(CMStochasticIterativeScheduler,) __a =10 def UpperCamelCase__ ( self : Union[str, Any] , **__a : str ): _a = { "num_train_timesteps": 2_01, "sigma_min": 0.002, "sigma_max": 80.0, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[Any] ): _a = 10 _a = self.get_scheduler_config() _a = self.scheduler_classes[0](**__a ) scheduler.set_timesteps(__a ) _a = scheduler.timesteps[0] _a = scheduler.timesteps[1] _a = self.dummy_sample _a = 0.1 * sample _a = scheduler.step(__a , __a , __a ).prev_sample _a = scheduler.step(__a , __a , __a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase__ ( self : Any ): for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : int ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = 1 scheduler.set_timesteps(__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(__a ): # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [1_06, 0] scheduler.set_timesteps(timesteps=__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCamelCase__ ( self : List[Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 15, 0] with self.assertRaises(__a , msg="`timesteps` must be in descending order." ): scheduler.set_timesteps(timesteps=__a ) def UpperCamelCase__ ( self : Tuple ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 1, 0] _a = len(__a ) with self.assertRaises(__a , msg="Can only pass one of `num_inference_steps` or `timesteps`." ): scheduler.set_timesteps(num_inference_steps=__a , timesteps=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [scheduler.config.num_train_timesteps] with self.assertRaises( __a , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=__a )
692
0
'''simple docstring''' import math def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 while num > 0: __SCREAMING_SNAKE_CASE = num % 8 __SCREAMING_SNAKE_CASE = octal + (remainder * math.floor(math.pow(10 , __UpperCAmelCase ) )) counter += 1 __SCREAMING_SNAKE_CASE = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"""0o{int(__UpperCAmelCase )}""" def __magic_name__ ( ) -> None: '''simple docstring''' print("""\n2 in octal is:""" ) print(decimal_to_octal(2 ) ) # = 2 print("""\n8 in octal is:""" ) print(decimal_to_octal(8 ) ) # = 10 print("""\n65 in octal is:""" ) print(decimal_to_octal(65 ) ) # = 101 print("""\n216 in octal is:""" ) print(decimal_to_octal(216 ) ) # = 330 print("""\n512 in octal is:""" ) print(decimal_to_octal(512 ) ) # = 1000 print("""\n""" ) if __name__ == "__main__": main()
109
'''simple docstring''' import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : int , **__a : Optional[Any] ): warnings.warn( "The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use YolosImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowercase_ ( lowerCamelCase_ , unittest.TestCase ): A_ = ConsistencyModelPipeline A_ = UNCONDITIONAL_IMAGE_GENERATION_PARAMS A_ = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt A_ = frozenset( [ "num_inference_steps", "generator", "latents", "output_type", "return_dict", "callback", "callback_steps", ] ) @property def _lowerCAmelCase ( self : Tuple ): snake_case__ : Any = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _lowerCAmelCase ( self : int ): snake_case__ : List[Any] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _lowerCAmelCase ( self : Union[str, Any] , __lowerCamelCase : str=False ): if class_cond: snake_case__ : List[Any] = self.dummy_cond_unet else: snake_case__ : Optional[int] = self.dummy_uncond_unet # Default to CM multistep sampler snake_case__ : List[str] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) snake_case__ : List[str] = { 'unet': unet, 'scheduler': scheduler, } return components def _lowerCAmelCase ( self : Dict , __lowerCamelCase : int , __lowerCamelCase : List[str]=0 ): if str(__a ).startswith('mps' ): snake_case__ : int = torch.manual_seed(__a ) else: snake_case__ : Tuple = torch.Generator(device=__a ).manual_seed(__a ) snake_case__ : str = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _lowerCAmelCase ( self : Tuple ): snake_case__ : List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case__ : str = self.get_dummy_components() snake_case__ : Any = ConsistencyModelPipeline(**__a ) snake_case__ : Union[str, Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) snake_case__ : Optional[Any] = self.get_dummy_inputs(__a ) snake_case__ : int = pipe(**__a ).images assert image.shape == (1, 32, 32, 3) snake_case__ : int = image[0, -3:, -3:, -1] snake_case__ : List[Any] = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _lowerCAmelCase ( self : List[Any] ): snake_case__ : Optional[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case__ : List[str] = self.get_dummy_components(class_cond=__a ) snake_case__ : List[Any] = ConsistencyModelPipeline(**__a ) snake_case__ : List[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) snake_case__ : Optional[int] = self.get_dummy_inputs(__a ) snake_case__ : Optional[Any] = 0 snake_case__ : Any = pipe(**__a ).images assert image.shape == (1, 32, 32, 3) snake_case__ : int = image[0, -3:, -3:, -1] snake_case__ : List[str] = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _lowerCAmelCase ( self : int ): snake_case__ : List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case__ : List[str] = self.get_dummy_components() snake_case__ : Union[str, Any] = ConsistencyModelPipeline(**__a ) snake_case__ : Union[str, Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) snake_case__ : Optional[int] = self.get_dummy_inputs(__a ) snake_case__ : Optional[int] = 1 snake_case__ : Optional[Any] = None snake_case__ : Optional[int] = pipe(**__a ).images assert image.shape == (1, 32, 32, 3) snake_case__ : Optional[Any] = image[0, -3:, -3:, -1] snake_case__ : List[str] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _lowerCAmelCase ( self : str ): snake_case__ : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case__ : Dict = self.get_dummy_components(class_cond=__a ) snake_case__ : Optional[Any] = ConsistencyModelPipeline(**__a ) snake_case__ : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) snake_case__ : Tuple = self.get_dummy_inputs(__a ) snake_case__ : Optional[int] = 1 snake_case__ : List[str] = None snake_case__ : int = 0 snake_case__ : Optional[int] = pipe(**__a ).images assert image.shape == (1, 32, 32, 3) snake_case__ : Dict = image[0, -3:, -3:, -1] snake_case__ : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): def _lowerCAmelCase ( self : int ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCAmelCase ( self : Union[str, Any] , __lowerCamelCase : Tuple=0 , __lowerCamelCase : int=False , __lowerCamelCase : List[Any]="cpu" , __lowerCamelCase : List[Any]=torch.floataa , __lowerCamelCase : Union[str, Any]=(1, 3, 64, 64) ): snake_case__ : Tuple = torch.manual_seed(__a ) snake_case__ : Any = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: snake_case__ : List[Any] = self.get_fixed_latents(seed=__a , device=__a , dtype=__a , shape=__a ) snake_case__ : Optional[int] = latents return inputs def _lowerCAmelCase ( self : List[str] , __lowerCamelCase : Any=0 , __lowerCamelCase : Dict="cpu" , __lowerCamelCase : Union[str, Any]=torch.floataa , __lowerCamelCase : List[Any]=(1, 3, 64, 64) ): if type(__a ) == str: snake_case__ : Tuple = torch.device(__a ) snake_case__ : int = torch.Generator(device=__a ).manual_seed(__a ) snake_case__ : Dict = randn_tensor(__a , generator=__a , device=__a , dtype=__a ) return latents def _lowerCAmelCase ( self : List[str] ): snake_case__ : List[str] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) snake_case__ : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) snake_case__ : Any = ConsistencyModelPipeline(unet=__a , scheduler=__a ) pipe.to(torch_device=__a ) pipe.set_progress_bar_config(disable=__a ) snake_case__ : int = self.get_inputs() snake_case__ : Tuple = pipe(**__a ).images assert image.shape == (1, 64, 64, 3) snake_case__ : int = image[0, -3:, -3:, -1] snake_case__ : Tuple = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _lowerCAmelCase ( self : Union[str, Any] ): snake_case__ : str = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) snake_case__ : Optional[int] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) snake_case__ : Any = ConsistencyModelPipeline(unet=__a , scheduler=__a ) pipe.to(torch_device=__a ) pipe.set_progress_bar_config(disable=__a ) snake_case__ : int = self.get_inputs() snake_case__ : List[str] = 1 snake_case__ : Optional[Any] = None snake_case__ : str = pipe(**__a ).images assert image.shape == (1, 64, 64, 3) snake_case__ : Any = image[0, -3:, -3:, -1] snake_case__ : Dict = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 @require_torch_a def _lowerCAmelCase ( self : Union[str, Any] ): snake_case__ : List[str] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) snake_case__ : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) snake_case__ : Dict = ConsistencyModelPipeline(unet=__a , scheduler=__a ) pipe.to(torch_device=__a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__a ) snake_case__ : List[str] = self.get_inputs(get_fixed_latents=__a , device=__a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__a , enable_math=__a , enable_mem_efficient=__a ): snake_case__ : Dict = pipe(**__a ).images assert image.shape == (1, 64, 64, 3) snake_case__ : Any = image[0, -3:, -3:, -1] snake_case__ : str = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @require_torch_a def _lowerCAmelCase ( self : Optional[Any] ): snake_case__ : Any = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) snake_case__ : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) snake_case__ : Optional[int] = ConsistencyModelPipeline(unet=__a , scheduler=__a ) pipe.to(torch_device=__a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__a ) snake_case__ : Optional[Any] = self.get_inputs(get_fixed_latents=__a , device=__a ) snake_case__ : List[str] = 1 snake_case__ : str = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__a , enable_math=__a , enable_mem_efficient=__a ): snake_case__ : str = pipe(**__a ).images assert image.shape == (1, 64, 64, 3) snake_case__ : List[str] = image[0, -3:, -3:, -1] snake_case__ : Union[str, Any] = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
270
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) lowerCAmelCase_ : str = { 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='timesformer' def __init__( self : Optional[int] , __a : Optional[int]=2_24 , __a : Tuple=16 , __a : int=3 , __a : Union[str, Any]=8 , __a : Union[str, Any]=7_68 , __a : List[str]=12 , __a : Union[str, Any]=12 , __a : Optional[Any]=30_72 , __a : Tuple="gelu" , __a : str=0.0 , __a : List[Any]=0.0 , __a : Any=0.02 , __a : List[str]=1e-6 , __a : Any=True , __a : Union[str, Any]="divided_space_time" , __a : str=0 , **__a : Tuple , ): super().__init__(**__a ) _a = image_size _a = patch_size _a = num_channels _a = num_frames _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = initializer_range _a = layer_norm_eps _a = qkv_bias _a = attention_type _a = drop_path_rate
692
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCamelCase = { 'configuration_m2m_100': ['M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP', 'M2M100Config', 'M2M100OnnxConfig'], 'tokenization_m2m_100': ['M2M100Tokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ 'M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST', 'M2M100ForConditionalGeneration', 'M2M100Model', 'M2M100PreTrainedModel', ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
96
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase__ ( self : Dict ): _a = 1 _a = 3 _a = (32, 32) _a = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__a ) return image @property def UpperCamelCase__ ( self : Dict ): torch.manual_seed(0 ) _a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def UpperCamelCase__ ( self : Optional[int] ): torch.manual_seed(0 ) _a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def UpperCamelCase__ ( self : Optional[Any] ): torch.manual_seed(0 ) _a = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=50_06 , ) return RobertaSeriesModelWithTransformation(__a ) @property def UpperCamelCase__ ( self : str ): def extract(*__a : Tuple , **__a : str ): class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict ): _a = torch.ones([0] ) def UpperCamelCase__ ( self : List[str] , __a : Dict ): self.pixel_values.to(__a ) return self return Out() return extract def UpperCamelCase__ ( self : Optional[int] ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) _a = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , ) _a = output.images _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , return_dict=__a , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) # put models in fp16 _a = unet.half() _a = vae.half() _a = bert.half() # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , num_inference_steps=2 , output_type="np" , image=__a , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 _a = init_image.resize((7_60, 5_04) ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] _a = image[2_55:2_58, 3_83:3_86, -1] assert image.shape == (5_04, 7_60, 3) _a = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : Union[str, Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) _a = init_image.resize((7_68, 5_12) ) _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] assert image.shape == (5_12, 7_68, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
692
0
"""simple docstring""" import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class UpperCAmelCase_ (lowerCamelCase_ ): """simple docstring""" def __get__( self : Dict , a_ : List[str] , a_ : Dict=None )-> Union[str, Any]: """simple docstring""" if obj is None: return self if self.fget is None: raise AttributeError("""unreadable attribute""" ) UpperCAmelCase_ : str = """__cached_""" + self.fget.__name__ UpperCAmelCase_ : List[Any] = getattr(__a , __a , __a ) if cached is None: UpperCAmelCase_ : int = self.fget(__a ) setattr(__a , __a , __a ) return cached def A_ ( lowercase ) -> Dict: """simple docstring""" UpperCAmelCase_ : int = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f'''invalid truth value {val!r}''' ) def A_ ( lowercase ) -> Optional[Any]: """simple docstring""" if is_torch_fx_proxy(lowercase ): return True if is_torch_available(): import torch if isinstance(lowercase , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(lowercase , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(lowercase , (jnp.ndarray, Tracer) ): return True return isinstance(lowercase , np.ndarray ) def A_ ( lowercase ) -> str: """simple docstring""" return isinstance(lowercase , np.ndarray ) def A_ ( lowercase ) -> Optional[int]: """simple docstring""" return _is_numpy(lowercase ) def A_ ( lowercase ) -> List[str]: """simple docstring""" import torch return isinstance(lowercase , torch.Tensor ) def A_ ( lowercase ) -> int: """simple docstring""" return False if not is_torch_available() else _is_torch(lowercase ) def A_ ( lowercase ) -> str: """simple docstring""" import torch return isinstance(lowercase , torch.device ) def A_ ( lowercase ) -> str: """simple docstring""" return False if not is_torch_available() else _is_torch_device(lowercase ) def A_ ( lowercase ) -> Any: """simple docstring""" import torch if isinstance(lowercase , lowercase ): if hasattr(lowercase , lowercase ): UpperCAmelCase_ : Optional[Any] = getattr(lowercase , lowercase ) else: return False return isinstance(lowercase , torch.dtype ) def A_ ( lowercase ) -> Dict: """simple docstring""" return False if not is_torch_available() else _is_torch_dtype(lowercase ) def A_ ( lowercase ) -> Tuple: """simple docstring""" import tensorflow as tf return isinstance(lowercase , tf.Tensor ) def A_ ( lowercase ) -> List[str]: """simple docstring""" return False if not is_tf_available() else _is_tensorflow(lowercase ) def A_ ( lowercase ) -> Tuple: """simple docstring""" import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(lowercase , """is_symbolic_tensor""" ): return tf.is_symbolic_tensor(lowercase ) return type(lowercase ) == tf.Tensor def A_ ( lowercase ) -> Any: """simple docstring""" return False if not is_tf_available() else _is_tf_symbolic_tensor(lowercase ) def A_ ( lowercase ) -> str: """simple docstring""" import jax.numpy as jnp # noqa: F811 return isinstance(lowercase , jnp.ndarray ) def A_ ( lowercase ) -> Optional[Any]: """simple docstring""" return False if not is_flax_available() else _is_jax(lowercase ) def A_ ( lowercase ) -> Any: """simple docstring""" if isinstance(lowercase , (dict, UserDict) ): return {k: to_py_obj(lowercase ) for k, v in obj.items()} elif isinstance(lowercase , (list, tuple) ): return [to_py_obj(lowercase ) for o in obj] elif is_tf_tensor(lowercase ): return obj.numpy().tolist() elif is_torch_tensor(lowercase ): return obj.detach().cpu().tolist() elif is_jax_tensor(lowercase ): return np.asarray(lowercase ).tolist() elif isinstance(lowercase , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def A_ ( lowercase ) -> List[str]: """simple docstring""" if isinstance(lowercase , (dict, UserDict) ): return {k: to_numpy(lowercase ) for k, v in obj.items()} elif isinstance(lowercase , (list, tuple) ): return np.array(lowercase ) elif is_tf_tensor(lowercase ): return obj.numpy() elif is_torch_tensor(lowercase ): return obj.detach().cpu().numpy() elif is_jax_tensor(lowercase ): return np.asarray(lowercase ) else: return obj class UpperCAmelCase_ (lowerCamelCase_ ): """simple docstring""" def a ( self : Optional[int] )-> Dict: """simple docstring""" UpperCAmelCase_ : List[str] = fields(self ) # Safety and consistency checks if not len(__a ): raise ValueError(f'''{self.__class__.__name__} has no fields.''' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.''' ) UpperCAmelCase_ : int = getattr(self , class_fields[0].name ) UpperCAmelCase_ : Dict = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(__a ): if isinstance(__a , __a ): UpperCAmelCase_ : str = first_field.items() UpperCAmelCase_ : Optional[int] = True else: try: UpperCAmelCase_ : Optional[Any] = iter(__a ) UpperCAmelCase_ : Tuple = True except TypeError: UpperCAmelCase_ : Optional[int] = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(__a ): if ( not isinstance(__a , (list, tuple) ) or not len(__a ) == 2 or not isinstance(element[0] , __a ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute UpperCAmelCase_ : Optional[Any] = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).''' ) break setattr(self , element[0] , element[1] ) if element[1] is not None: UpperCAmelCase_ : Tuple = element[1] elif first_field is not None: UpperCAmelCase_ : List[Any] = first_field else: for field in class_fields: UpperCAmelCase_ : Dict = getattr(self , field.name ) if v is not None: UpperCAmelCase_ : Tuple = v def __delitem__( self : Optional[Any] , *a_ : Optional[int] , **a_ : Tuple )-> str: """simple docstring""" raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.''' ) def a ( self : Any , *a_ : Optional[Any] , **a_ : int )-> Optional[Any]: """simple docstring""" raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.''' ) def a ( self : Optional[int] , *a_ : Union[str, Any] , **a_ : Dict )-> Tuple: """simple docstring""" raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.''' ) def a ( self : Tuple , *a_ : Union[str, Any] , **a_ : Any )-> Any: """simple docstring""" raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.''' ) def __getitem__( self : Tuple , a_ : Any )-> str: """simple docstring""" if isinstance(__a , __a ): UpperCAmelCase_ : List[str] = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : List[Any] , a_ : int , a_ : str )-> List[str]: """simple docstring""" if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(__a , __a ) super().__setattr__(__a , __a ) def __setitem__( self : List[str] , a_ : Dict , a_ : Optional[int] )-> Optional[int]: """simple docstring""" super().__setitem__(__a , __a ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(__a , __a ) def a ( self : Optional[Any] )-> Dict: """simple docstring""" return tuple(self[k] for k in self.keys() ) class UpperCAmelCase_ (lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" @classmethod def a ( cls : Dict , a_ : str )-> Dict: """simple docstring""" raise ValueError( f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}''' ) class UpperCAmelCase_ (lowerCamelCase_ ): """simple docstring""" UpperCamelCase_ : str = """longest""" UpperCamelCase_ : str = """max_length""" UpperCamelCase_ : int = """do_not_pad""" class UpperCAmelCase_ (lowerCamelCase_ ): """simple docstring""" UpperCamelCase_ : Union[str, Any] = """pt""" UpperCamelCase_ : Optional[Any] = """tf""" UpperCamelCase_ : Union[str, Any] = """np""" UpperCamelCase_ : int = """jax""" class UpperCAmelCase_ : """simple docstring""" def __init__( self : List[str] , a_ : List[ContextManager] )-> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = context_managers UpperCAmelCase_ : Dict = ExitStack() def __enter__( self : int )-> int: """simple docstring""" for context_manager in self.context_managers: self.stack.enter_context(__a ) def __exit__( self : List[Any] , *a_ : Optional[int] , **a_ : Union[str, Any] )-> Dict: """simple docstring""" self.stack.__exit__(*__a , **__a ) def A_ ( lowercase ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = infer_framework(lowercase ) if framework == "tf": UpperCAmelCase_ : str = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": UpperCAmelCase_ : str = inspect.signature(model_class.forward ) # PyTorch models else: UpperCAmelCase_ : Tuple = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def A_ ( lowercase ) -> Any: """simple docstring""" UpperCAmelCase_ : List[Any] = model_class.__name__ UpperCAmelCase_ : Any = infer_framework(lowercase ) if framework == "tf": UpperCAmelCase_ : str = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": UpperCAmelCase_ : Union[str, Any] = inspect.signature(model_class.forward ) # PyTorch models else: UpperCAmelCase_ : Optional[Any] = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def A_ ( lowercase , lowercase = "" , lowercase = "." ) -> Tuple: """simple docstring""" def _flatten_dict(lowercase , lowercase="" , lowercase="." ): for k, v in d.items(): UpperCAmelCase_ : str = str(lowercase ) + delimiter + str(lowercase ) if parent_key else k if v and isinstance(lowercase , lowercase ): yield from flatten_dict(lowercase , lowercase , delimiter=lowercase ).items() else: yield key, v return dict(_flatten_dict(lowercase , lowercase , lowercase ) ) @contextmanager def A_ ( lowercase , lowercase = False ) -> Dict: """simple docstring""" if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def A_ ( lowercase , lowercase=None ) -> Optional[int]: """simple docstring""" if is_numpy_array(lowercase ): return np.transpose(lowercase , axes=lowercase ) elif is_torch_tensor(lowercase ): return array.T if axes is None else array.permute(*lowercase ) elif is_tf_tensor(lowercase ): import tensorflow as tf return tf.transpose(lowercase , perm=lowercase ) elif is_jax_tensor(lowercase ): return jnp.transpose(lowercase , axes=lowercase ) else: raise ValueError(f'''Type not supported for transpose: {type(lowercase )}.''' ) def A_ ( lowercase , lowercase ) -> str: """simple docstring""" if is_numpy_array(lowercase ): return np.reshape(lowercase , lowercase ) elif is_torch_tensor(lowercase ): return array.reshape(*lowercase ) elif is_tf_tensor(lowercase ): import tensorflow as tf return tf.reshape(lowercase , lowercase ) elif is_jax_tensor(lowercase ): return jnp.reshape(lowercase , lowercase ) else: raise ValueError(f'''Type not supported for reshape: {type(lowercase )}.''' ) def A_ ( lowercase , lowercase=None ) -> Union[str, Any]: """simple docstring""" if is_numpy_array(lowercase ): return np.squeeze(lowercase , axis=lowercase ) elif is_torch_tensor(lowercase ): return array.squeeze() if axis is None else array.squeeze(dim=lowercase ) elif is_tf_tensor(lowercase ): import tensorflow as tf return tf.squeeze(lowercase , axis=lowercase ) elif is_jax_tensor(lowercase ): return jnp.squeeze(lowercase , axis=lowercase ) else: raise ValueError(f'''Type not supported for squeeze: {type(lowercase )}.''' ) def A_ ( lowercase , lowercase ) -> Tuple: """simple docstring""" if is_numpy_array(lowercase ): return np.expand_dims(lowercase , lowercase ) elif is_torch_tensor(lowercase ): return array.unsqueeze(dim=lowercase ) elif is_tf_tensor(lowercase ): import tensorflow as tf return tf.expand_dims(lowercase , axis=lowercase ) elif is_jax_tensor(lowercase ): return jnp.expand_dims(lowercase , axis=lowercase ) else: raise ValueError(f'''Type not supported for expand_dims: {type(lowercase )}.''' ) def A_ ( lowercase ) -> Any: """simple docstring""" if is_numpy_array(lowercase ): return np.size(lowercase ) elif is_torch_tensor(lowercase ): return array.numel() elif is_tf_tensor(lowercase ): import tensorflow as tf return tf.size(lowercase ) elif is_jax_tensor(lowercase ): return array.size else: raise ValueError(f'''Type not supported for expand_dims: {type(lowercase )}.''' ) def A_ ( lowercase , lowercase ) -> Any: """simple docstring""" for key, value in auto_map.items(): if isinstance(lowercase , (tuple, list) ): UpperCAmelCase_ : Dict = [f'''{repo_id}--{v}''' if (v is not None and """--""" not in v) else v for v in value] elif value is not None and "--" not in value: UpperCAmelCase_ : str = f'''{repo_id}--{value}''' return auto_map def A_ ( lowercase ) -> str: """simple docstring""" for base_class in inspect.getmro(lowercase ): UpperCAmelCase_ : Union[str, Any] = base_class.__module__ UpperCAmelCase_ : Dict = base_class.__name__ if module.startswith("""tensorflow""" ) or module.startswith("""keras""" ) or name == "TFPreTrainedModel": return "tf" elif module.startswith("""torch""" ) or name == "PreTrainedModel": return "pt" elif module.startswith("""flax""" ) or module.startswith("""jax""" ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f'''Could not infer framework from class {model_class}.''' )
470
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , *__a : Tuple , **__a : Optional[Any] ): warnings.warn( "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DPTImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass A : Optional[int] = (3, 9, -11, 0, 7, 5, 1, -1) A : int = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class a_ : a : Optional[Any] = 4_2 a : Any = 4_2 class a_ : def __init__( self , __UpperCamelCase ): _lowercase = None for i in sorted(__a , reverse=__a ): _lowercase = Node(__a , self.head ) def __iter__( self ): _lowercase = self.head while node: yield node.data _lowercase = node.next_node def __len__( self ): return sum(1 for _ in self ) def __str__( self ): return " -> ".join([str(__a ) for node in self] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ : SortedLinkedList , SCREAMING_SNAKE_CASE_ : SortedLinkedList ) -> SortedLinkedList: return SortedLinkedList(list(SCREAMING_SNAKE_CASE_ ) + list(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": import doctest doctest.testmod() A : Optional[int] = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
287
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Any ) -> Tuple: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : str = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Dict: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] ) -> Dict: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Optional[Any] , __a : Dict , __a : Optional[int] ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Optional[int]=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : List[str] , __a : Optional[Any] , __a : List[str] ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Dict , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : Optional[int] ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
692
0
"""simple docstring""" import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class _UpperCAmelCase ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase): _lowerCAmelCase : Optional[Any] = IFPipeline _lowerCAmelCase : Dict = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} _lowerCAmelCase : int = TEXT_TO_IMAGE_BATCH_PARAMS _lowerCAmelCase : Tuple = PipelineTesterMixin.required_optional_params - {"""latents"""} def _snake_case ( self : Optional[int] ): return self._get_dummy_components() def _snake_case ( self : Any , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any]=0 ): if str(__a ).startswith('''mps''' ): snake_case_ : Dict = torch.manual_seed(__a ) else: snake_case_ : int = torch.Generator(device=__a ).manual_seed(__a ) snake_case_ : Dict = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def _snake_case ( self : List[str] ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def _snake_case ( self : List[Any] ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def _snake_case ( self : List[Any] ): self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def _snake_case ( self : Dict ): self._test_save_load_local() def _snake_case ( self : int ): self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def _snake_case ( self : Dict ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase): def _snake_case ( self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self : int ): # if snake_case_ : int = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) snake_case_ : Optional[int] = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=__a , tokenizer=__a ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) snake_case_, snake_case_ : str = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() snake_case_ : List[Any] = None snake_case_ : Dict = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(__a , __a , __a , __a ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img snake_case_ : Any = IFImgaImgPipeline(**pipe_a.components ) snake_case_ : Dict = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(__a , __a , __a , __a ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting snake_case_ : Any = IFInpaintingPipeline(**pipe_a.components ) snake_case_ : Optional[int] = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(__a , __a , __a , __a ) def _snake_case ( self : Optional[int] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : str , lowercase_ : Optional[int] ): # pipeline 1 _start_torch_memory_measurement() snake_case_ : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case_ : Union[str, Any] = pipe_a( prompt_embeds=__a , negative_prompt_embeds=__a , num_inference_steps=2 , generator=__a , output_type='''np''' , ) snake_case_ : Union[str, Any] = output.images[0] assert image.shape == (64, 64, 3) snake_case_ : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 snake_case_ : Dict = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(__a , __a ) # pipeline 2 _start_torch_memory_measurement() snake_case_ : List[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case_ : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__a ) snake_case_ : Any = pipe_a( prompt_embeds=__a , negative_prompt_embeds=__a , image=__a , generator=__a , num_inference_steps=2 , output_type='''np''' , ) snake_case_ : List[str] = output.images[0] assert image.shape == (256, 256, 3) snake_case_ : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case_ : Optional[int] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(__a , __a ) def _snake_case ( self : List[Any] , lowercase_ : List[Any] , lowercase_ : Union[str, Any] , lowercase_ : int , lowercase_ : Union[str, Any] ): # pipeline 1 _start_torch_memory_measurement() snake_case_ : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__a ) snake_case_ : int = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case_ : Optional[int] = pipe_a( prompt_embeds=__a , negative_prompt_embeds=__a , image=__a , num_inference_steps=2 , generator=__a , output_type='''np''' , ) snake_case_ : Optional[int] = output.images[0] assert image.shape == (64, 64, 3) snake_case_ : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 snake_case_ : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(__a , __a ) # pipeline 2 _start_torch_memory_measurement() snake_case_ : List[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case_ : Any = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(__a ) snake_case_ : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__a ) snake_case_ : Any = pipe_a( prompt_embeds=__a , negative_prompt_embeds=__a , image=__a , original_image=__a , generator=__a , num_inference_steps=2 , output_type='''np''' , ) snake_case_ : List[Any] = output.images[0] assert image.shape == (256, 256, 3) snake_case_ : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case_ : str = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(__a , __a ) def _snake_case ( self : Dict , lowercase_ : Dict , lowercase_ : Optional[Any] , lowercase_ : Dict , lowercase_ : Tuple ): # pipeline 1 _start_torch_memory_measurement() snake_case_ : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__a ) snake_case_ : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(__a ) snake_case_ : Optional[int] = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case_ : List[Any] = pipe_a( prompt_embeds=__a , negative_prompt_embeds=__a , image=__a , mask_image=__a , num_inference_steps=2 , generator=__a , output_type='''np''' , ) snake_case_ : Optional[Any] = output.images[0] assert image.shape == (64, 64, 3) snake_case_ : Optional[int] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 snake_case_ : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(__a , __a ) # pipeline 2 _start_torch_memory_measurement() snake_case_ : Tuple = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case_ : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__a ) snake_case_ : Union[str, Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(__a ) snake_case_ : Union[str, Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(__a ) snake_case_ : Tuple = pipe_a( prompt_embeds=__a , negative_prompt_embeds=__a , image=__a , mask_image=__a , original_image=__a , generator=__a , num_inference_steps=2 , output_type='''np''' , ) snake_case_ : Any = output.images[0] assert image.shape == (256, 256, 3) snake_case_ : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case_ : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(__a , __a ) def __lowercase ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
123
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase_ : Any = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys lowerCAmelCase_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
692
0
import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants A = Mapping[str, np.ndarray] A = Mapping[str, Any] # Is a nested dict. A = 0.01 @dataclasses.dataclass(frozen=lowerCamelCase_ ) class lowerCAmelCase__ : '''simple docstring''' lowerCAmelCase_ = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowerCAmelCase_ = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowerCAmelCase_ = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowerCAmelCase_ = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowerCAmelCase_ = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowerCAmelCase_ = None # Optional remark about the protein. Included as a comment in output PDB # files lowerCAmelCase_ = None # Templates used to generate this protein (prediction-only) lowerCAmelCase_ = None # Chain corresponding to each parent lowerCAmelCase_ = None def lowerCamelCase ( UpperCamelCase : str ) -> Protein: _lowerCamelCase = R'(\[[A-Z]+\]\n)' _lowerCamelCase = [tag.strip() for tag in re.split(UpperCamelCase , UpperCamelCase ) if len(UpperCamelCase ) > 0] _lowerCamelCase = zip(tags[0::2] , [l.split('\n' ) for l in tags[1::2]] ) _lowerCamelCase = ['N', 'CA', 'C'] _lowerCamelCase = None _lowerCamelCase = None _lowerCamelCase = None for g in groups: if "[PRIMARY]" == g[0]: _lowerCamelCase = g[1][0].strip() for i in range(len(UpperCamelCase ) ): if seq[i] not in residue_constants.restypes: _lowerCamelCase = 'X' # FIXME: strings are immutable _lowerCamelCase = np.array( [residue_constants.restype_order.get(UpperCamelCase , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: _lowerCamelCase = [] for axis in range(3 ): tertiary.append(list(map(UpperCamelCase , g[1][axis].split() ) ) ) _lowerCamelCase = np.array(UpperCamelCase ) _lowerCamelCase = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(UpperCamelCase ): _lowerCamelCase = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: _lowerCamelCase = np.array(list(map({'-': 0, '+': 1}.get , g[1][0].strip() ) ) ) _lowerCamelCase = np.zeros( ( len(UpperCamelCase ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(UpperCamelCase ): _lowerCamelCase = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=UpperCamelCase , atom_mask=UpperCamelCase , aatype=UpperCamelCase , residue_index=np.arange(len(UpperCamelCase ) ) , b_factors=UpperCamelCase , ) def lowerCamelCase ( UpperCamelCase : Protein , UpperCamelCase : int = 0 ) -> List[str]: _lowerCamelCase = [] _lowerCamelCase = prot.remark if remark is not None: pdb_headers.append(F"""REMARK {remark}""" ) _lowerCamelCase = prot.parents _lowerCamelCase = prot.parents_chain_index if parents is not None and parents_chain_index is not None: _lowerCamelCase = [p for i, p in zip(UpperCamelCase , UpperCamelCase ) if i == chain_id] if parents is None or len(UpperCamelCase ) == 0: _lowerCamelCase = ['N/A'] pdb_headers.append(F"""PARENT {" ".join(UpperCamelCase )}""" ) return pdb_headers def lowerCamelCase ( UpperCamelCase : Protein , UpperCamelCase : str ) -> str: _lowerCamelCase = [] _lowerCamelCase = pdb_str.split('\n' ) _lowerCamelCase = prot.remark if remark is not None: out_pdb_lines.append(F"""REMARK {remark}""" ) _lowerCamelCase = 42 if prot.parents is not None and len(prot.parents ) > 0: _lowerCamelCase = [] if prot.parents_chain_index is not None: _lowerCamelCase = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(UpperCamelCase ) , [] ) parent_dict[str(UpperCamelCase )].append(UpperCamelCase ) _lowerCamelCase = max([int(UpperCamelCase ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): _lowerCamelCase = parent_dict.get(str(UpperCamelCase ) , ['N/A'] ) parents_per_chain.append(UpperCamelCase ) else: parents_per_chain.append(list(prot.parents ) ) else: _lowerCamelCase = [['N/A']] def make_parent_line(UpperCamelCase : Sequence[str] ) -> str: return F"""PARENT {" ".join(UpperCamelCase )}""" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) _lowerCamelCase = 0 for i, l in enumerate(UpperCamelCase ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(UpperCamelCase ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(UpperCamelCase ): _lowerCamelCase = parents_per_chain[chain_counter] else: _lowerCamelCase = ['N/A'] out_pdb_lines.append(make_parent_line(UpperCamelCase ) ) return "\n".join(UpperCamelCase ) def lowerCamelCase ( UpperCamelCase : Protein ) -> str: _lowerCamelCase = residue_constants.restypes + ['X'] def res_atoa(UpperCamelCase : int ) -> str: return residue_constants.restype_atoa.get(restypes[r] , 'UNK' ) _lowerCamelCase = residue_constants.atom_types _lowerCamelCase = [] _lowerCamelCase = prot.atom_mask _lowerCamelCase = prot.aatype _lowerCamelCase = prot.atom_positions _lowerCamelCase = prot.residue_index.astype(np.intaa ) _lowerCamelCase = prot.b_factors _lowerCamelCase = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('Invalid aatypes.' ) _lowerCamelCase = get_pdb_headers(UpperCamelCase ) if len(UpperCamelCase ) > 0: pdb_lines.extend(UpperCamelCase ) _lowerCamelCase = aatype.shape[0] _lowerCamelCase = 1 _lowerCamelCase = 0 _lowerCamelCase = string.ascii_uppercase _lowerCamelCase = None # Add all atom sites. for i in range(UpperCamelCase ): _lowerCamelCase = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(UpperCamelCase , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue _lowerCamelCase = 'ATOM' _lowerCamelCase = atom_name if len(UpperCamelCase ) == 4 else F""" {atom_name}""" _lowerCamelCase = '' _lowerCamelCase = '' _lowerCamelCase = 1.00 _lowerCamelCase = atom_name[0] # Protein supports only C, N, O, S, this works. _lowerCamelCase = '' _lowerCamelCase = 'A' if chain_index is not None: _lowerCamelCase = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! _lowerCamelCase = ( F"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}""" F"""{res_name_a:>3} {chain_tag:>1}""" F"""{residue_index[i]:>4}{insertion_code:>1} """ F"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}""" F"""{occupancy:>6.2f}{b_factor:>6.2f} """ F"""{element:>2}{charge:>2}""" ) pdb_lines.append(UpperCamelCase ) atom_index += 1 _lowerCamelCase = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: _lowerCamelCase = True _lowerCamelCase = chain_index[i + 1] if should_terminate: # Close the chain. _lowerCamelCase = 'TER' _lowerCamelCase = ( F"""{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}""" ) pdb_lines.append(UpperCamelCase ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(UpperCamelCase , UpperCamelCase ) ) pdb_lines.append('END' ) pdb_lines.append('' ) return "\n".join(UpperCamelCase ) def lowerCamelCase ( UpperCamelCase : Protein ) -> np.ndarray: return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def lowerCamelCase ( UpperCamelCase : FeatureDict , UpperCamelCase : ModelOutput , UpperCamelCase : Optional[np.ndarray] = None , UpperCamelCase : Optional[np.ndarray] = None , UpperCamelCase : Optional[str] = None , UpperCamelCase : Optional[Sequence[str]] = None , UpperCamelCase : Optional[Sequence[int]] = None , ) -> Protein: return Protein( aatype=features['aatype'] , atom_positions=result['final_atom_positions'] , atom_mask=result['final_atom_mask'] , residue_index=features['residue_index'] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['final_atom_mask'] ) , chain_index=UpperCamelCase , remark=UpperCamelCase , parents=UpperCamelCase , parents_chain_index=UpperCamelCase , )
544
'''simple docstring''' import gc import threading import time import psutil import torch class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] ): _a = psutil.Process() _a = False def UpperCamelCase__ ( self : Tuple ): _a = -1 while True: _a = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def UpperCamelCase__ ( self : List[Any] ): _a = True _a = threading.Thread(target=self.peak_monitor ) _a = True self.thread.start() def UpperCamelCase__ ( self : Optional[int] ): _a = False self.thread.join() return self.cpu_memory_peak lowerCAmelCase_ : List[Any] = PeakCPUMemory() def _lowerCamelCase ( ) -> Tuple: # Time _a = {"time": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem _a = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): _a = torch.cuda.memory_allocated(lowercase ) torch.cuda.reset_peak_memory_stats() return measures def _lowerCamelCase ( lowercase : Any ) -> int: # Time _a = {"time": time.time() - start_measures["time"]} gc.collect() torch.cuda.empty_cache() # CPU mem _a = (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20 _a = (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): _a = (torch.cuda.memory_allocated(lowercase ) - start_measures[str(lowercase )]) / 2**20 _a = (torch.cuda.max_memory_allocated(lowercase ) - start_measures[str(lowercase )]) / 2**20 return measures def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Dict ) -> str: print(F'{description}:' ) print(F'- Time: {measures["time"]:.2f}s' ) for i in range(torch.cuda.device_count() ): print(F'- GPU {i} allocated: {measures[str(lowercase )]:.2f}MiB' ) _a = measures[F'{i}-peak'] print(F'- GPU {i} peak: {peak:.2f}MiB' ) print(F'- CPU RAM allocated: {measures["cpu"]:.2f}MiB' ) print(F'- CPU RAM peak: {measures["cpu-peak"]:.2f}MiB' )
692
0
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase( lowerCamelCase_ ): def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Tuple=1_3 , SCREAMING_SNAKE_CASE : Optional[int]=7 , SCREAMING_SNAKE_CASE : Tuple=True , SCREAMING_SNAKE_CASE : Union[str, Any]=True , SCREAMING_SNAKE_CASE : List[Any]=True , SCREAMING_SNAKE_CASE : Union[str, Any]=True , SCREAMING_SNAKE_CASE : List[str]=True , SCREAMING_SNAKE_CASE : Union[str, Any]=False , SCREAMING_SNAKE_CASE : Dict=False , SCREAMING_SNAKE_CASE : Optional[Any]=False , SCREAMING_SNAKE_CASE : Tuple=2 , SCREAMING_SNAKE_CASE : List[str]=9_9 , SCREAMING_SNAKE_CASE : Union[str, Any]=0 , SCREAMING_SNAKE_CASE : int=3_2 , SCREAMING_SNAKE_CASE : Optional[Any]=5 , SCREAMING_SNAKE_CASE : Optional[Any]=4 , SCREAMING_SNAKE_CASE : str=0.1 , SCREAMING_SNAKE_CASE : str=0.1 , SCREAMING_SNAKE_CASE : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE : int=1_2 , SCREAMING_SNAKE_CASE : str=2 , SCREAMING_SNAKE_CASE : List[str]=0.02 , SCREAMING_SNAKE_CASE : Dict=3 , SCREAMING_SNAKE_CASE : List[Any]=4 , SCREAMING_SNAKE_CASE : Union[str, Any]="last" , SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : str=None , ) -> Optional[int]: '''simple docstring''' __snake_case = parent __snake_case = batch_size __snake_case = seq_length __snake_case = is_training __snake_case = use_input_lengths __snake_case = use_token_type_ids __snake_case = use_labels __snake_case = gelu_activation __snake_case = sinusoidal_embeddings __snake_case = causal __snake_case = asm __snake_case = n_langs __snake_case = vocab_size __snake_case = n_special __snake_case = hidden_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = max_position_embeddings __snake_case = type_vocab_size __snake_case = type_sequence_label_size __snake_case = initializer_range __snake_case = num_labels __snake_case = num_choices __snake_case = summary_type __snake_case = use_proj __snake_case = scope def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case = None if self.use_input_lengths: __snake_case = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __snake_case = None if self.use_token_type_ids: __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __snake_case = None __snake_case = None __snake_case = None if self.use_labels: __snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case = ids_tensor([self.batch_size] , 2 ).float() __snake_case = ids_tensor([self.batch_size] , self.num_choices ) __snake_case = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[Any] , ) -> str: '''simple docstring''' __snake_case = FlaubertModel(config=__a ) model.to(__a ) model.eval() __snake_case = model(__a , lengths=__a , langs=__a ) __snake_case = model(__a , langs=__a ) __snake_case = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Optional[Any]: '''simple docstring''' __snake_case = FlaubertWithLMHeadModel(__a ) model.to(__a ) model.eval() __snake_case = model(__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : str , ) -> Optional[Any]: '''simple docstring''' __snake_case = FlaubertForQuestionAnsweringSimple(__a ) model.to(__a ) model.eval() __snake_case = model(__a ) __snake_case = model(__a , start_positions=__a , end_positions=__a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Optional[int] , ) -> Union[str, Any]: '''simple docstring''' __snake_case = FlaubertForQuestionAnswering(__a ) model.to(__a ) model.eval() __snake_case = model(__a ) __snake_case = model( __a , start_positions=__a , end_positions=__a , cls_index=__a , is_impossible=__a , p_mask=__a , ) __snake_case = model( __a , start_positions=__a , end_positions=__a , cls_index=__a , is_impossible=__a , ) ((__snake_case ) , ) = result_with_labels.to_tuple() __snake_case = model(__a , start_positions=__a , end_positions=__a ) ((__snake_case ) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : List[Any] , ) -> str: '''simple docstring''' __snake_case = FlaubertForSequenceClassification(__a ) model.to(__a ) model.eval() __snake_case = model(__a ) __snake_case = model(__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Any , ) -> Dict: '''simple docstring''' __snake_case = self.num_labels __snake_case = FlaubertForTokenClassification(__a ) model.to(__a ) model.eval() __snake_case = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[Any] , ) -> List[str]: '''simple docstring''' __snake_case = self.num_choices __snake_case = FlaubertForMultipleChoice(config=__a ) model.to(__a ) model.eval() __snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case = self.prepare_config_and_inputs() ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) = config_and_inputs __snake_case = { "input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths, "attention_mask": input_mask, } return config, inputs_dict @require_torch class UpperCamelCase( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): snake_case_ : Dict = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) snake_case_ : List[Any] = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[str] ) -> Union[str, Any]: '''simple docstring''' if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Dict=False ) -> List[Any]: '''simple docstring''' __snake_case = super()._prepare_for_class(__a , __a , return_labels=__a ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": __snake_case = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) __snake_case = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) return inputs_dict def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case = FlaubertModelTester(self ) __snake_case = ConfigTester(self , config_class=__a , emb_dim=3_7 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__a ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__a ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__a ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__a ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> str: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__a ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__a ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: '''simple docstring''' __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__a ) @slow def SCREAMING_SNAKE_CASE_ ( self : str ) -> Any: '''simple docstring''' for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case = FlaubertModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @slow @require_torch_gpu def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return __snake_case = True __snake_case = model_class(config=__a ) __snake_case = self._prepare_for_class(__a , __a ) __snake_case = torch.jit.trace( __a , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__a , os.path.join(__a , "traced_model.pt" ) ) __snake_case = torch.jit.load(os.path.join(__a , "traced_model.pt" ) , map_location=__a ) loaded(inputs_dict["input_ids"].to(__a ) , inputs_dict["attention_mask"].to(__a ) ) @require_torch class UpperCamelCase( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' __snake_case = FlaubertModel.from_pretrained("flaubert/flaubert_base_cased" ) __snake_case = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) with torch.no_grad(): __snake_case = model(__a )[0] __snake_case = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape , __a ) __snake_case = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1e-4 ) )
371
'''simple docstring''' import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(DDIMParallelScheduler,) __a =(('eta', 0.0), ('num_inference_steps', 50)) def UpperCamelCase__ ( self : Optional[int] , **__a : Any ): _a = { "num_train_timesteps": 10_00, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[str] , **__a : Optional[int] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config(**__a ) _a = scheduler_class(**__a ) _a , _a = 10, 0.0 _a = self.dummy_model() _a = self.dummy_sample_deter scheduler.set_timesteps(__a ) for t in scheduler.timesteps: _a = model(__a , __a ) _a = scheduler.step(__a , __a , __a , __a ).prev_sample return sample def UpperCamelCase__ ( self : str ): for timesteps in [1_00, 5_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : Dict ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__a ) _a = self.scheduler_classes[0] _a = self.get_scheduler_config(steps_offset=1 ) _a = scheduler_class(**__a ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_01, 6_01, 4_01, 2_01, 1] ) ) def UpperCamelCase__ ( self : Tuple ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def UpperCamelCase__ ( self : Dict ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__a ) def UpperCamelCase__ ( self : Tuple ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def UpperCamelCase__ ( self : Dict ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__a ) def UpperCamelCase__ ( self : Optional[int] ): for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__a ) def UpperCamelCase__ ( self : Optional[Any] ): for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__a ) def UpperCamelCase__ ( self : List[Any] ): self.check_over_configs(thresholding=__a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__a , prediction_type=__a , sample_max_value=__a , ) def UpperCamelCase__ ( self : List[Any] ): for t in [1, 10, 49]: self.check_over_forward(time_step=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 5_00] ): self.check_over_forward(time_step=__a , num_inference_steps=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__a , eta=__a ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_20 , 4_00 ) - 0.14771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_80 , 9_60 ) - 0.32460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 , 4_86 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 , 9_98 ) - 0.02 ) ) < 1e-5 def UpperCamelCase__ ( self : List[str] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a , _a = 10, 0.0 scheduler.set_timesteps(__a ) _a = self.dummy_model() _a = self.dummy_sample_deter _a = self.dummy_sample_deter + 0.1 _a = self.dummy_sample_deter - 0.1 _a = samplea.shape[0] _a = torch.stack([samplea, samplea, samplea] , dim=0 ) _a = torch.arange(__a )[0:3, None].repeat(1 , __a ) _a = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _a = scheduler.batch_step_no_noise(__a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __a ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1147.7904 ) < 1e-2 assert abs(result_mean.item() - 0.4982 ) < 1e-3 def UpperCamelCase__ ( self : List[str] ): _a = self.full_loop() _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 172.0067 ) < 1e-2 assert abs(result_mean.item() - 0.223967 ) < 1e-3 def UpperCamelCase__ ( self : str ): _a = self.full_loop(prediction_type="v_prediction" ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 52.5302 ) < 1e-2 assert abs(result_mean.item() - 0.0684 ) < 1e-3 def UpperCamelCase__ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _a = self.full_loop(set_alpha_to_one=__a , beta_start=0.01 ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 149.8295 ) < 1e-2 assert abs(result_mean.item() - 0.1951 ) < 1e-3 def UpperCamelCase__ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _a = self.full_loop(set_alpha_to_one=__a , beta_start=0.01 ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 149.0784 ) < 1e-2 assert abs(result_mean.item() - 0.1941 ) < 1e-3
692
0
def A__( __lowerCAmelCase ): return "".join(chr(ord(__lowerCAmelCase ) - 32 ) if 'a' <= char <= 'z' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
304
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _lowerCamelCase ( lowercase : Any ) -> List[str]: return getitem, k def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Any: return setitem, k, v def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: return delitem, k def _lowerCamelCase ( lowercase : Tuple , lowercase : Dict , *lowercase : Union[str, Any] ) -> int: try: return fun(lowercase , *lowercase ), None except Exception as e: return None, e lowerCAmelCase_ : Optional[Any] = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) lowerCAmelCase_ : Optional[int] = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] lowerCAmelCase_ : int = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] lowerCAmelCase_ : List[Any] = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('key_a', 'val_b'), ] @pytest.mark.parametrize( "operations" , ( pytest.param(_add_items , id="add items" ), pytest.param(_overwrite_items , id="overwrite items" ), pytest.param(_delete_items , id="delete items" ), pytest.param(_access_absent_items , id="access absent items" ), pytest.param(_add_with_resize_up , id="add with resize up" ), pytest.param(_add_with_resize_down , id="add with resize down" ), ) , ) def _lowerCamelCase ( lowercase : Optional[int] ) -> Optional[int]: _a = HashMap(initial_block_size=4 ) _a = {} for _, (fun, *args) in enumerate(lowercase ): _a , _a = _run_operation(lowercase , lowercase , *lowercase ) _a , _a = _run_operation(lowercase , lowercase , *lowercase ) assert my_res == py_res assert str(lowercase ) == str(lowercase ) assert set(lowercase ) == set(lowercase ) assert len(lowercase ) == len(lowercase ) assert set(my.items() ) == set(py.items() ) def _lowerCamelCase ( ) -> str: def is_public(lowercase : str ) -> bool: return not name.startswith("_" ) _a = {name for name in dir({} ) if is_public(lowercase )} _a = {name for name in dir(HashMap() ) if is_public(lowercase )} assert dict_public_names > hash_public_names
692
0
from __future__ import annotations SCREAMING_SNAKE_CASE__ : List[Any] = '#' class UpperCAmelCase_ : def __init__( self ): UpperCAmelCase__ : Any = {} def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : List[str] = self._trie for char in text: if char not in trie: UpperCAmelCase__ : Optional[Any] = {} UpperCAmelCase__ : str = trie[char] UpperCAmelCase__ : List[Any] = True def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : str = self._trie for char in prefix: if char in trie: UpperCAmelCase__ : Optional[Any] = trie[char] else: return [] return self._elements(__a ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = [] for c, v in d.items(): UpperCAmelCase__ : Optional[int] = [""" """] if c == END else [(c + s) for s in self._elements(__a )] result.extend(__a ) return tuple(__a ) SCREAMING_SNAKE_CASE__ : Optional[int] = Trie() SCREAMING_SNAKE_CASE__ : Tuple = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _lowerCamelCase ( __lowerCamelCase ) -> tuple: '''simple docstring''' UpperCAmelCase__ : List[str] = trie.find_word(__lowerCamelCase ) return tuple(string + word for word in suffixes ) def _lowerCamelCase ( ) -> None: '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
79
'''simple docstring''' import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =PhobertTokenizer __a =False def UpperCamelCase__ ( self : int ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _a = ["T@@", "i", "I", "R@@", "r", "e@@"] _a = dict(zip(__a , range(len(__a ) ) ) ) _a = ["#version: 0.2", "l à</w>"] _a = {"unk_token": "<unk>"} _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(f'{token} {vocab_tokens[token]}\n' ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__a ) ) def UpperCamelCase__ ( self : str , **__a : List[str] ): kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ): _a = "Tôi là VinAI Research" _a = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>" return input_text, output_text def UpperCamelCase__ ( self : Dict ): _a = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _a = "Tôi là VinAI Research" _a = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split() _a = tokenizer.tokenize(__a ) print(__a ) self.assertListEqual(__a , __a ) _a = tokens + [tokenizer.unk_token] _a = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a )
692
0
"""simple docstring""" import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class _lowerCAmelCase : """simple docstring""" def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Union[str, Any] = TaEncoderModel.from_pretrained('hf-internal-testing/tiny-random-t5' ) torch.manual_seed(0 ) lowerCAmelCase__ :Optional[int] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-t5' ) torch.manual_seed(0 ) lowerCAmelCase__ :Optional[int] = UNetaDConditionModel( sample_size=3_2 , layers_per_block=1 , block_out_channels=[3_2, 6_4] , down_block_types=[ 'ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D', ] , mid_block_type='UNetMidBlock2DSimpleCrossAttn' , up_block_types=['SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'] , in_channels=3 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type='text' , addition_embed_type_num_heads=2 , cross_attention_norm='group_norm' , resnet_time_scale_shift='scale_shift' , act_fn='gelu' , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) lowerCAmelCase__ :List[str] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='squaredcos_cap_v2' , beta_start=0.00_01 , beta_end=0.02 , thresholding=__a , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='epsilon' , variance_type='learned_range' , ) torch.manual_seed(0 ) lowerCAmelCase__ :Optional[int] = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :Any = TaEncoderModel.from_pretrained('hf-internal-testing/tiny-random-t5' ) torch.manual_seed(0 ) lowerCAmelCase__ :Union[str, Any] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-t5' ) torch.manual_seed(0 ) lowerCAmelCase__ :str = UNetaDConditionModel( sample_size=3_2 , layers_per_block=[1, 2] , block_out_channels=[3_2, 6_4] , down_block_types=[ 'ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D', ] , mid_block_type='UNetMidBlock2DSimpleCrossAttn' , up_block_types=['SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'] , in_channels=6 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type='text' , addition_embed_type_num_heads=2 , cross_attention_norm='group_norm' , resnet_time_scale_shift='scale_shift' , act_fn='gelu' , class_embed_type='timestep' , mid_block_scale_factor=1.4_14 , time_embedding_act_fn='gelu' , time_embedding_dim=3_2 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) lowerCAmelCase__ :Union[str, Any] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='squaredcos_cap_v2' , beta_start=0.00_01 , beta_end=0.02 , thresholding=__a , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='epsilon' , variance_type='learned_range' , ) torch.manual_seed(0 ) lowerCAmelCase__ :List[Any] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='squaredcos_cap_v2' , beta_start=0.00_01 , beta_end=0.02 , ) torch.manual_seed(0 ) lowerCAmelCase__ :Tuple = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.get_dummy_components() lowerCAmelCase__ :Optional[int] = self.pipeline_class(**__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__a ) lowerCAmelCase__ :List[Any] = inputs['prompt'] lowerCAmelCase__ :Any = inputs['generator'] lowerCAmelCase__ :Any = inputs['num_inference_steps'] lowerCAmelCase__ :int = inputs['output_type'] if "image" in inputs: lowerCAmelCase__ :Optional[Any] = inputs['image'] else: lowerCAmelCase__ :Tuple = None if "mask_image" in inputs: lowerCAmelCase__ :str = inputs['mask_image'] else: lowerCAmelCase__ :Dict = None if "original_image" in inputs: lowerCAmelCase__ :str = inputs['original_image'] else: lowerCAmelCase__ :Dict = None lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = pipe.encode_prompt(__a ) # inputs with prompt converted to embeddings lowerCAmelCase__ :List[str] = { 'prompt_embeds': prompt_embeds, 'negative_prompt_embeds': negative_prompt_embeds, 'generator': generator, 'num_inference_steps': num_inference_steps, 'output_type': output_type, } if image is not None: lowerCAmelCase__ :Union[str, Any] = image if mask_image is not None: lowerCAmelCase__ :List[str] = mask_image if original_image is not None: lowerCAmelCase__ :Tuple = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(__a , __a , __a ) lowerCAmelCase__ :Dict = pipe(**__a )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(__a ) lowerCAmelCase__ :int = self.pipeline_class.from_pretrained(__a ) pipe_loaded.to(__a ) pipe_loaded.set_progress_bar_config(disable=__a ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(__a , __a ) is None , F"`{optional_component}` did not stay set to None after loading." , ) lowerCAmelCase__ :Any = self.get_dummy_inputs(__a ) lowerCAmelCase__ :int = inputs['generator'] lowerCAmelCase__ :Optional[Any] = inputs['num_inference_steps'] lowerCAmelCase__ :str = inputs['output_type'] # inputs with prompt converted to embeddings lowerCAmelCase__ :str = { 'prompt_embeds': prompt_embeds, 'negative_prompt_embeds': negative_prompt_embeds, 'generator': generator, 'num_inference_steps': num_inference_steps, 'output_type': output_type, } if image is not None: lowerCAmelCase__ :Any = image if mask_image is not None: lowerCAmelCase__ :Optional[Any] = mask_image if original_image is not None: lowerCAmelCase__ :Optional[int] = original_image lowerCAmelCase__ :List[Any] = pipe_loaded(**__a )[0] lowerCAmelCase__ :Dict = np.abs(to_np(__a ) - to_np(__a ) ).max() self.assertLess(__a , 1E-4 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = self.get_dummy_components() lowerCAmelCase__ :Any = self.pipeline_class(**__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) lowerCAmelCase__ :str = self.get_dummy_inputs(__a ) lowerCAmelCase__ :Any = pipe(**__a )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(__a ) lowerCAmelCase__ :List[str] = self.pipeline_class.from_pretrained(__a ) pipe_loaded.to(__a ) pipe_loaded.set_progress_bar_config(disable=__a ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests lowerCAmelCase__ :Optional[Any] = self.get_dummy_inputs(__a ) lowerCAmelCase__ :int = pipe_loaded(**__a )[0] lowerCAmelCase__ :int = np.abs(to_np(__a ) - to_np(__a ) ).max() self.assertLess(__a , 1E-4 )
93
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : str , *__a : Any , __a : str=None , __a : Union[str, Any]=None , **__a : Any ): super().__init__(*__a , **__a ) _a = eval_examples _a = post_process_function def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : Any=None , __a : str=None , __a : str = "eval" ): _a = self.eval_dataset if eval_dataset is None else eval_dataset _a = self.get_eval_dataloader(__a ) _a = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _a = self.compute_metrics _a = None _a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _a = time.time() try: _a = eval_loop( __a , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__a , metric_key_prefix=__a , ) finally: _a = compute_metrics _a = self.args.eval_batch_size * self.args.world_size if f'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( __a , __a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default _a = self.post_process_function(__a , __a , output.predictions ) _a = self.compute_metrics(__a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'{metric_key_prefix}_' ): _a = metrics.pop(__a ) metrics.update(output.metrics ) else: _a = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__a ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _a = self.callback_handler.on_evaluate(self.args , self.state , self.control , __a ) return metrics def UpperCamelCase__ ( self : Tuple , __a : Dict , __a : Optional[Any] , __a : Optional[Any]=None , __a : str = "test" ): _a = self.get_test_dataloader(__a ) # Temporarily disable metric computation, we will do it in the loop here. _a = self.compute_metrics _a = None _a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _a = time.time() try: _a = eval_loop( __a , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__a , metric_key_prefix=__a , ) finally: _a = compute_metrics _a = self.args.eval_batch_size * self.args.world_size if f'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( __a , __a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output _a = self.post_process_function(__a , __a , output.predictions , "predict" ) _a = self.compute_metrics(__a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'{metric_key_prefix}_' ): _a = metrics.pop(__a ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__a )
692
0
"""simple docstring""" import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : int , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : Optional[Any] = jnp.ones((batch_size, length) ) / length return scores def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Union[str, Any] = None _lowerCamelCase : Dict = 2_0 _lowerCamelCase : Union[str, Any] = self._get_uniform_logits(batch_size=2 , length=__a ) # tweak scores to not be uniform anymore _lowerCamelCase : Dict = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch _lowerCamelCase : Any = scores.at[1, 1_0].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax _lowerCamelCase : Tuple = jax.nn.softmax(__a , axis=-1 ) _lowerCamelCase : Optional[Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) _lowerCamelCase : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=1.3 ) _lowerCamelCase : List[Any] = jax.nn.softmax(temp_dist_warper_sharper(__a , scores.copy() , cur_len=__a ) , axis=-1 ) _lowerCamelCase : Union[str, Any] = jax.nn.softmax(temp_dist_warper_smoother(__a , scores.copy() , cur_len=__a ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1E-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1E-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : List[str] = None _lowerCamelCase : Dict = 1_0 _lowerCamelCase : Optional[Any] = 2 # create ramp distribution _lowerCamelCase : Tuple = np.broadcast_to(np.arange(__a )[None, :] , (batch_size, vocab_size) ).copy() _lowerCamelCase : Dict = ramp_logits[1:, : vocab_size // 2] + vocab_size _lowerCamelCase : Any = FlaxTopKLogitsWarper(3 ) _lowerCamelCase : int = top_k_warp(__a , __a , cur_len=__a ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case _lowerCamelCase : Union[str, Any] = 5 _lowerCamelCase : Any = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) _lowerCamelCase : int = np.broadcast_to(np.arange(__a )[None, :] , (batch_size, length) ).copy() _lowerCamelCase : Dict = top_k_warp_safety_check(__a , __a , cur_len=__a ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Dict = None _lowerCamelCase : str = 1_0 _lowerCamelCase : int = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) _lowerCamelCase : Optional[Any] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) _lowerCamelCase : Optional[int] = FlaxTopPLogitsWarper(0.8 ) _lowerCamelCase : List[str] = np.exp(top_p_warp(__a , __a , cur_len=__a ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 _lowerCamelCase : List[str] = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(__a , __a , atol=1E-3 ) ) # check edge cases with negative and extreme logits _lowerCamelCase : Any = np.broadcast_to(np.arange(__a )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme _lowerCamelCase : Tuple = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept _lowerCamelCase : List[Any] = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) _lowerCamelCase : Any = top_p_warp(__a , __a , cur_len=__a ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Any = 2_0 _lowerCamelCase : Union[str, Any] = 4 _lowerCamelCase : int = 0 _lowerCamelCase : List[str] = FlaxMinLengthLogitsProcessor(min_length=1_0 , eos_token_id=__a ) # check that min length is applied at length 5 _lowerCamelCase : str = ids_tensor((batch_size, 2_0) , vocab_size=2_0 ) _lowerCamelCase : Optional[int] = 5 _lowerCamelCase : Union[str, Any] = self._get_uniform_logits(__a , __a ) _lowerCamelCase : Optional[int] = min_dist_processor(__a , __a , cur_len=__a ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 _lowerCamelCase : str = self._get_uniform_logits(__a , __a ) _lowerCamelCase : Optional[Any] = 1_5 _lowerCamelCase : Any = min_dist_processor(__a , __a , cur_len=__a ) self.assertFalse(jnp.isinf(__a ).any() ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Any = 2_0 _lowerCamelCase : Dict = 4 _lowerCamelCase : List[Any] = 0 _lowerCamelCase : List[Any] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__a ) # check that all scores are -inf except the bos_token_id score _lowerCamelCase : List[str] = ids_tensor((batch_size, 1) , vocab_size=2_0 ) _lowerCamelCase : List[str] = 1 _lowerCamelCase : Optional[int] = self._get_uniform_logits(__a , __a ) _lowerCamelCase : Any = logits_processor(__a , __a , cur_len=__a ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 _lowerCamelCase : int = 3 _lowerCamelCase : Optional[int] = self._get_uniform_logits(__a , __a ) _lowerCamelCase : Optional[int] = logits_processor(__a , __a , cur_len=__a ) self.assertFalse(jnp.isinf(__a ).any() ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : List[str] = 2_0 _lowerCamelCase : Dict = 4 _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : int = 5 _lowerCamelCase : str = FlaxForcedEOSTokenLogitsProcessor(max_length=__a , eos_token_id=__a ) # check that all scores are -inf except the eos_token_id when max_length is reached _lowerCamelCase : Dict = ids_tensor((batch_size, 4) , vocab_size=2_0 ) _lowerCamelCase : Dict = 4 _lowerCamelCase : int = self._get_uniform_logits(__a , __a ) _lowerCamelCase : Union[str, Any] = logits_processor(__a , __a , cur_len=__a ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached _lowerCamelCase : Any = 3 _lowerCamelCase : Any = self._get_uniform_logits(__a , __a ) _lowerCamelCase : Dict = logits_processor(__a , __a , cur_len=__a ) self.assertFalse(jnp.isinf(__a ).any() ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : int = 4 _lowerCamelCase : Tuple = 1_0 _lowerCamelCase : Union[str, Any] = 1_5 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : Tuple = 1 _lowerCamelCase : Dict = 1_5 # dummy input_ids and scores _lowerCamelCase : Any = ids_tensor((batch_size, sequence_length) , __a ) _lowerCamelCase : Dict = input_ids.copy() _lowerCamelCase : List[str] = self._get_uniform_logits(__a , __a ) _lowerCamelCase : int = scores.copy() # instantiate all dist processors _lowerCamelCase : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) _lowerCamelCase : Tuple = FlaxTopKLogitsWarper(3 ) _lowerCamelCase : Any = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors _lowerCamelCase : Optional[int] = FlaxMinLengthLogitsProcessor(min_length=1_0 , eos_token_id=__a ) _lowerCamelCase : Dict = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__a ) _lowerCamelCase : str = FlaxForcedEOSTokenLogitsProcessor(max_length=__a , eos_token_id=__a ) _lowerCamelCase : str = 1_0 # no processor list _lowerCamelCase : Any = temp_dist_warp(__a , __a , cur_len=__a ) _lowerCamelCase : Union[str, Any] = top_k_warp(__a , __a , cur_len=__a ) _lowerCamelCase : Any = top_p_warp(__a , __a , cur_len=__a ) _lowerCamelCase : List[str] = min_dist_proc(__a , __a , cur_len=__a ) _lowerCamelCase : Dict = bos_dist_proc(__a , __a , cur_len=__a ) _lowerCamelCase : str = eos_dist_proc(__a , __a , cur_len=__a ) # with processor list _lowerCamelCase : Optional[Any] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) _lowerCamelCase : str = processor(__a , __a , cur_len=__a ) # scores should be equal self.assertTrue(jnp.allclose(__a , __a , atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Union[str, Any] = 4 _lowerCamelCase : List[str] = 1_0 _lowerCamelCase : Any = 1_5 _lowerCamelCase : Optional[int] = 2 _lowerCamelCase : int = 1 _lowerCamelCase : str = 1_5 # dummy input_ids and scores _lowerCamelCase : Optional[int] = ids_tensor((batch_size, sequence_length) , __a ) _lowerCamelCase : Optional[Any] = input_ids.copy() _lowerCamelCase : List[str] = self._get_uniform_logits(__a , __a ) _lowerCamelCase : Tuple = scores.copy() # instantiate all dist processors _lowerCamelCase : str = FlaxTemperatureLogitsWarper(temperature=0.5 ) _lowerCamelCase : Union[str, Any] = FlaxTopKLogitsWarper(3 ) _lowerCamelCase : int = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors _lowerCamelCase : List[Any] = FlaxMinLengthLogitsProcessor(min_length=1_0 , eos_token_id=__a ) _lowerCamelCase : Tuple = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__a ) _lowerCamelCase : str = FlaxForcedEOSTokenLogitsProcessor(max_length=__a , eos_token_id=__a ) _lowerCamelCase : Tuple = 1_0 # no processor list def run_no_processor_list(__lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ): _lowerCamelCase : Any = temp_dist_warp(__a , __a , cur_len=__a ) _lowerCamelCase : Any = top_k_warp(__a , __a , cur_len=__a ) _lowerCamelCase : Dict = top_p_warp(__a , __a , cur_len=__a ) _lowerCamelCase : Optional[int] = min_dist_proc(__a , __a , cur_len=__a ) _lowerCamelCase : Tuple = bos_dist_proc(__a , __a , cur_len=__a ) _lowerCamelCase : int = eos_dist_proc(__a , __a , cur_len=__a ) return scores # with processor list def run_processor_list(__lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : Any ): _lowerCamelCase : Union[str, Any] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) _lowerCamelCase : int = processor(__a , __a , cur_len=__a ) return scores _lowerCamelCase : Tuple = jax.jit(__a ) _lowerCamelCase : List[str] = jax.jit(__a ) _lowerCamelCase : Dict = jitted_run_no_processor_list(__a , __a , __a ) _lowerCamelCase : str = jitted_run_processor_list(__a , __a , __a ) # scores should be equal self.assertTrue(jnp.allclose(__a , __a , atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
83
'''simple docstring''' import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : Dict , **__a : List[Any] ): warnings.warn( "The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ChineseCLIPImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class lowercase_ ( unittest.TestCase ): def _lowerCAmelCase ( self : List[str] ): snake_case__ : Union[str, Any] = tempfile.mkdtemp() snake_case__ : List[str] = SamImageProcessor() snake_case__ : Tuple = SamProcessor(__a ) processor.save_pretrained(self.tmpdirname ) def _lowerCAmelCase ( self : Union[str, Any] , **__lowerCamelCase : Optional[Any] ): return AutoProcessor.from_pretrained(self.tmpdirname , **__a ).image_processor def _lowerCAmelCase ( self : Optional[Any] ): shutil.rmtree(self.tmpdirname ) def _lowerCAmelCase ( self : List[Any] ): snake_case__ : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case__ : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowerCAmelCase ( self : List[str] ): snake_case__ : Optional[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case__ : List[Any] = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) snake_case__ : Union[str, Any] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def _lowerCAmelCase ( self : Any ): snake_case__ : Union[str, Any] = self.get_image_processor() snake_case__ : Optional[Any] = SamProcessor(image_processor=__a ) snake_case__ : int = self.prepare_image_inputs() snake_case__ : Optional[Any] = image_processor(__a , return_tensors='np' ) snake_case__ : Union[str, Any] = processor(images=__a , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _lowerCAmelCase ( self : Optional[Any] ): snake_case__ : List[Any] = self.get_image_processor() snake_case__ : Tuple = SamProcessor(image_processor=__a ) snake_case__ : Dict = [torch.ones((1, 3, 5, 5) )] snake_case__ : Union[str, Any] = [[1764, 2646]] snake_case__ : Optional[int] = [[683, 1024]] snake_case__ : Optional[int] = processor.post_process_masks(__a , __a , __a ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) snake_case__ : Optional[int] = processor.post_process_masks( __a , torch.tensor(__a ) , torch.tensor(__a ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np snake_case__ : Optional[Any] = [np.ones((1, 3, 5, 5) )] snake_case__ : str = processor.post_process_masks(__a , np.array(__a ) , np.array(__a ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) snake_case__ : Union[str, Any] = [[1, 0], [0, 1]] with self.assertRaises(__a ): snake_case__ : Any = processor.post_process_masks(__a , np.array(__a ) , np.array(__a ) ) @require_vision @require_tf class lowercase_ ( unittest.TestCase ): def _lowerCAmelCase ( self : Optional[Any] ): snake_case__ : Union[str, Any] = tempfile.mkdtemp() snake_case__ : Tuple = SamImageProcessor() snake_case__ : Optional[Any] = SamProcessor(__a ) processor.save_pretrained(self.tmpdirname ) def _lowerCAmelCase ( self : Union[str, Any] , **__lowerCamelCase : Optional[int] ): return AutoProcessor.from_pretrained(self.tmpdirname , **__a ).image_processor def _lowerCAmelCase ( self : List[str] ): shutil.rmtree(self.tmpdirname ) def _lowerCAmelCase ( self : List[str] ): snake_case__ : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case__ : Optional[int] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowerCAmelCase ( self : Optional[Any] ): snake_case__ : Optional[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case__ : Optional[int] = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) snake_case__ : List[str] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def _lowerCAmelCase ( self : List[Any] ): snake_case__ : int = self.get_image_processor() snake_case__ : Any = SamProcessor(image_processor=__a ) snake_case__ : Dict = self.prepare_image_inputs() snake_case__ : Optional[int] = image_processor(__a , return_tensors='np' ) snake_case__ : Optional[int] = processor(images=__a , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _lowerCAmelCase ( self : Optional[int] ): snake_case__ : Union[str, Any] = self.get_image_processor() snake_case__ : int = SamProcessor(image_processor=__a ) snake_case__ : Dict = [tf.ones((1, 3, 5, 5) )] snake_case__ : Union[str, Any] = [[1764, 2646]] snake_case__ : List[Any] = [[683, 1024]] snake_case__ : List[str] = processor.post_process_masks(__a , __a , __a , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) snake_case__ : List[Any] = processor.post_process_masks( __a , tf.convert_to_tensor(__a ) , tf.convert_to_tensor(__a ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np snake_case__ : Optional[Any] = [np.ones((1, 3, 5, 5) )] snake_case__ : Tuple = processor.post_process_masks( __a , np.array(__a ) , np.array(__a ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) snake_case__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): snake_case__ : Any = processor.post_process_masks( __a , np.array(__a ) , np.array(__a ) , return_tensors='tf' ) @require_vision @require_torchvision class lowercase_ ( unittest.TestCase ): def _lowerCAmelCase ( self : Optional[int] ): snake_case__ : List[str] = tempfile.mkdtemp() snake_case__ : str = SamImageProcessor() snake_case__ : Union[str, Any] = SamProcessor(__a ) processor.save_pretrained(self.tmpdirname ) def _lowerCAmelCase ( self : List[Any] , **__lowerCamelCase : Dict ): return AutoProcessor.from_pretrained(self.tmpdirname , **__a ).image_processor def _lowerCAmelCase ( self : List[Any] ): shutil.rmtree(self.tmpdirname ) def _lowerCAmelCase ( self : Tuple ): snake_case__ : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case__ : Tuple = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _lowerCAmelCase ( self : Optional[Any] ): snake_case__ : Optional[Any] = self.get_image_processor() snake_case__ : Any = SamProcessor(image_processor=__a ) snake_case__ : Dict = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) snake_case__ : List[str] = [tf.convert_to_tensor(__a )] snake_case__ : Dict = [torch.tensor(__a )] snake_case__ : Dict = [[1764, 2646]] snake_case__ : List[Any] = [[683, 1024]] snake_case__ : List[str] = processor.post_process_masks( __a , __a , __a , return_tensors='tf' ) snake_case__ : Any = processor.post_process_masks( __a , __a , __a , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _lowerCAmelCase ( self : Dict ): snake_case__ : List[Any] = self.get_image_processor() snake_case__ : Tuple = SamProcessor(image_processor=__a ) snake_case__ : str = self.prepare_image_inputs() snake_case__ : Tuple = image_processor(__a , return_tensors='pt' )['pixel_values'].numpy() snake_case__ : Optional[int] = processor(images=__a , return_tensors='pt' )['pixel_values'].numpy() snake_case__ : Dict = image_processor(__a , return_tensors='tf' )['pixel_values'].numpy() snake_case__ : List[Any] = processor(images=__a , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(__a , __a ) ) self.assertTrue(np.allclose(__a , __a ) ) self.assertTrue(np.allclose(__a , __a ) )
270
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[int] , __a : int , __a : int , __a : int , __a : str=0.0 , __a : Optional[int] = None , __a : str = "geglu" , __a : Optional[int] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : str = "layer_norm" , __a : bool = False , ): super().__init__() _a = only_cross_attention _a = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" _a = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f'`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to' f' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _a = AdaLayerNorm(__a , __a ) elif self.use_ada_layer_norm_zero: _a = AdaLayerNormZero(__a , __a ) else: _a = nn.LayerNorm(__a , elementwise_affine=__a ) _a = Attention( query_dim=__a , heads=__a , dim_head=__a , dropout=__a , bias=__a , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__a , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _a = ( AdaLayerNorm(__a , __a ) if self.use_ada_layer_norm else nn.LayerNorm(__a , elementwise_affine=__a ) ) _a = Attention( query_dim=__a , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__a , dim_head=__a , dropout=__a , bias=__a , upcast_attention=__a , ) # is self-attn if encoder_hidden_states is none else: _a = None _a = None # 3. Feed-forward _a = nn.LayerNorm(__a , elementwise_affine=__a ) _a = FeedForward(__a , dropout=__a , activation_fn=__a , final_dropout=__a ) # let chunk size default to None _a = None _a = 0 def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : int ): # Sets chunk feed-forward _a = chunk_size _a = dim def UpperCamelCase__ ( self : List[str] , __a : torch.FloatTensor , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.LongTensor] = None , __a : Dict[str, Any] = None , __a : Optional[torch.LongTensor] = None , ): # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: _a = self.norma(__a , __a ) elif self.use_ada_layer_norm_zero: _a , _a , _a , _a , _a = self.norma( __a , __a , __a , hidden_dtype=hidden_states.dtype ) else: _a = self.norma(__a ) _a = cross_attention_kwargs if cross_attention_kwargs is not None else {} _a = self.attna( __a , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__a , **__a , ) if self.use_ada_layer_norm_zero: _a = gate_msa.unsqueeze(1 ) * attn_output _a = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _a = ( self.norma(__a , __a ) if self.use_ada_layer_norm else self.norma(__a ) ) _a = self.attna( __a , encoder_hidden_states=__a , attention_mask=__a , **__a , ) _a = attn_output + hidden_states # 3. Feed-forward _a = self.norma(__a ) if self.use_ada_layer_norm_zero: _a = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f'`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.' ) _a = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _a = torch.cat( [self.ff(__a ) for hid_slice in norm_hidden_states.chunk(__a , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: _a = self.ff(__a ) if self.use_ada_layer_norm_zero: _a = gate_mlp.unsqueeze(1 ) * ff_output _a = ff_output + hidden_states return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[Any] , __a : int , __a : Optional[int] = None , __a : int = 4 , __a : float = 0.0 , __a : str = "geglu" , __a : bool = False , ): super().__init__() _a = int(dim * mult ) _a = dim_out if dim_out is not None else dim if activation_fn == "gelu": _a = GELU(__a , __a ) if activation_fn == "gelu-approximate": _a = GELU(__a , __a , approximate="tanh" ) elif activation_fn == "geglu": _a = GEGLU(__a , __a ) elif activation_fn == "geglu-approximate": _a = ApproximateGELU(__a , __a ) _a = nn.ModuleList([] ) # project in self.net.append(__a ) # project dropout self.net.append(nn.Dropout(__a ) ) # project out self.net.append(nn.Linear(__a , __a ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(__a ) ) def UpperCamelCase__ ( self : List[Any] , __a : Tuple ): for module in self.net: _a = module(__a ) return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : int , __a : int , __a : str = "none" ): super().__init__() _a = nn.Linear(__a , __a ) _a = approximate def UpperCamelCase__ ( self : Union[str, Any] , __a : List[Any] ): if gate.device.type != "mps": return F.gelu(__a , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def UpperCamelCase__ ( self : str , __a : Optional[int] ): _a = self.proj(__a ) _a = self.gelu(__a ) return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : str , __a : int , __a : int ): super().__init__() _a = nn.Linear(__a , dim_out * 2 ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[int] ): if gate.device.type != "mps": return F.gelu(__a ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def UpperCamelCase__ ( self : List[str] , __a : Any ): _a , _a = self.proj(__a ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(__a ) class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[Any] , __a : int , __a : int ): super().__init__() _a = nn.Linear(__a , __a ) def UpperCamelCase__ ( self : Union[str, Any] , __a : Dict ): _a = self.proj(__a ) return x * torch.sigmoid(1.702 * x ) class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : str , __a : str ): super().__init__() _a = nn.Embedding(__a , __a ) _a = nn.SiLU() _a = nn.Linear(__a , embedding_dim * 2 ) _a = nn.LayerNorm(__a , elementwise_affine=__a ) def UpperCamelCase__ ( self : Tuple , __a : Any , __a : Optional[Any] ): _a = self.linear(self.silu(self.emb(__a ) ) ) _a , _a = torch.chunk(__a , 2 ) _a = self.norm(__a ) * (1 + scale) + shift return x class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[Any] , __a : List[Any] , __a : Any ): super().__init__() _a = CombinedTimestepLabelEmbeddings(__a , __a ) _a = nn.SiLU() _a = nn.Linear(__a , 6 * embedding_dim , bias=__a ) _a = nn.LayerNorm(__a , elementwise_affine=__a , eps=1e-6 ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict , __a : List[Any] , __a : Union[str, Any] , __a : List[Any]=None ): _a = self.linear(self.silu(self.emb(__a , __a , hidden_dtype=__a ) ) ) _a , _a , _a , _a , _a , _a = emb.chunk(6 , dim=1 ) _a = self.norm(__a ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[int] , __a : int , __a : int , __a : int , __a : Optional[str] = None , __a : float = 1e-5 ): super().__init__() _a = num_groups _a = eps if act_fn is None: _a = None else: _a = get_activation(__a ) _a = nn.Linear(__a , out_dim * 2 ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[Any] , __a : List[Any] ): if self.act: _a = self.act(__a ) _a = self.linear(__a ) _a = emb[:, :, None, None] _a , _a = emb.chunk(2 , dim=1 ) _a = F.group_norm(__a , self.num_groups , eps=self.eps ) _a = x * (1 + scale) + shift return x
692
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase = { 'configuration_upernet': ['UperNetConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ 'UperNetForSemanticSegmentation', 'UperNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys __lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
96
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 __a =42 class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : int ): _a = [[] for _ in range(__a )] _a = size def __getitem__( self : int , __a : int ): return iter(self._graph[vertex] ) @property def UpperCamelCase__ ( self : Dict ): return self._size def UpperCamelCase__ ( self : Union[str, Any] , __a : int , __a : int , __a : int ): if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(__a , __a ) ) def UpperCamelCase__ ( self : Tuple , __a : int , __a : int ): _a = deque([start_vertex] ) _a = [None] * self.size _a = 0 while queue: _a = queue.popleft() _a = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _a = current_distance + edge.weight _a = distances[edge.destination_vertex] if ( isinstance(__a , __a ) and new_distance >= dest_vertex_distance ): continue _a = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
692
0
"""simple docstring""" import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowercase_ = logging.get_logger(__name__) class UpperCAmelCase_ : """simple docstring""" def __init__( self : Tuple , a_ : Dict , a_ : Union[str, Any] )-> List[str]: """simple docstring""" UpperCAmelCase_ : Dict = question_encoder UpperCAmelCase_ : Optional[int] = generator UpperCAmelCase_ : int = self.question_encoder def a ( self : Optional[Any] , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" if os.path.isfile(__a ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__a , exist_ok=__a ) UpperCAmelCase_ : Optional[int] = os.path.join(__a , """question_encoder_tokenizer""" ) UpperCAmelCase_ : Tuple = os.path.join(__a , """generator_tokenizer""" ) self.question_encoder.save_pretrained(__a ) self.generator.save_pretrained(__a ) @classmethod def a ( cls : Any , a_ : Optional[Any] , **a_ : List[Any] )-> List[Any]: """simple docstring""" from ..auto.tokenization_auto import AutoTokenizer UpperCAmelCase_ : Optional[int] = kwargs.pop("""config""" , __a ) if config is None: UpperCAmelCase_ : Union[str, Any] = RagConfig.from_pretrained(__a ) UpperCAmelCase_ : Union[str, Any] = AutoTokenizer.from_pretrained( __a , config=config.question_encoder , subfolder="""question_encoder_tokenizer""" ) UpperCAmelCase_ : Any = AutoTokenizer.from_pretrained( __a , config=config.generator , subfolder="""generator_tokenizer""" ) return cls(question_encoder=__a , generator=__a ) def __call__( self : Union[str, Any] , *a_ : Dict , **a_ : List[str] )-> int: """simple docstring""" return self.current_tokenizer(*__a , **__a ) def a ( self : Tuple , *a_ : Optional[int] , **a_ : List[Any] )-> Optional[int]: """simple docstring""" return self.generator.batch_decode(*__a , **__a ) def a ( self : Union[str, Any] , *a_ : Any , **a_ : Optional[int] )-> int: """simple docstring""" return self.generator.decode(*__a , **__a ) def a ( self : str )-> str: """simple docstring""" UpperCAmelCase_ : int = self.question_encoder def a ( self : Dict )-> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = self.generator def a ( self : List[Any] , a_ : List[str] , a_ : Optional[List[str]] = None , a_ : Optional[int] = None , a_ : Optional[int] = None , a_ : str = "longest" , a_ : str = None , a_ : bool = True , **a_ : int , )-> Union[str, Any]: """simple docstring""" warnings.warn( """`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the """ """regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` """ """context manager to prepare your targets. See the documentation of your specific tokenizer for more """ """details""" , __a , ) if max_length is None: UpperCAmelCase_ : Tuple = self.current_tokenizer.model_max_length UpperCAmelCase_ : Union[str, Any] = self( __a , add_special_tokens=__a , return_tensors=__a , max_length=__a , padding=__a , truncation=__a , **__a , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: UpperCAmelCase_ : List[Any] = self.current_tokenizer.model_max_length UpperCAmelCase_ : List[Any] = self( text_target=__a , add_special_tokens=__a , return_tensors=__a , padding=__a , max_length=__a , truncation=__a , **__a , ) UpperCAmelCase_ : Tuple = labels["""input_ids"""] return model_inputs
470
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =FlaxAutoencoderKL @property def UpperCamelCase__ ( self : str ): _a = 4 _a = 3 _a = (32, 32) _a = jax.random.PRNGKey(0 ) _a = jax.random.uniform(__a , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCamelCase__ ( self : List[Any] ): _a = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } _a = self.dummy_input return init_dict, inputs_dict
692
0
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def UpperCamelCase__ ( ) -> Optional[int]: _lowercase = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 20, """a """ * 30, """b """ * 7], } _lowercase = Dataset.from_dict(SCREAMING_SNAKE_CASE_ ) return dataset class a_ ( lowerCamelCase_ ): def UpperCamelCase_ ( self ): _lowercase = get_dataset() _lowercase = make_duplicate_clusters(__a , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def UpperCamelCase_ ( self ): _lowercase = get_dataset() _lowercase , _lowercase = deduplicate_dataset(__a ) self.assertEqual(len(__a ) , 2 ) print(__a ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] , 2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] , __a )
287
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration lowerCAmelCase_ : List[Any] = [ # tf -> hf ('/', '.'), ('layer_', 'layers.'), ('kernel', 'weight'), ('beta', 'bias'), ('gamma', 'weight'), ('pegasus', 'model'), ] lowerCAmelCase_ : Optional[int] = [ ('.output.dense', '.fc2'), ('intermediate.LayerNorm', 'final_layer_norm'), ('intermediate.dense', 'fc1'), ] lowerCAmelCase_ : Any = ( INIT_COMMON + [ ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.out_proj'), ('attention.self', 'self_attn'), ('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'), ('attention.encdec_output.dense', 'encoder_attn.out_proj'), ('attention.encdec', 'encoder_attn'), ('key', 'k_proj'), ('value', 'v_proj'), ('query', 'q_proj'), ('decoder.LayerNorm', 'decoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Tuple = ( INIT_COMMON + [ ('embeddings.word_embeddings', 'shared.weight'), ('embeddings.position_embeddings', 'embed_positions.weight'), ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.output'), ('attention.self', 'self_attn.self'), ('encoder.LayerNorm', 'encoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Optional[int] = [ 'encdec/key/bias', 'encdec/query/bias', 'encdec/value/bias', 'self/key/bias', 'self/query/bias', 'self/value/bias', 'encdec_output/dense/bias', 'attention/output/dense/bias', ] def _lowerCamelCase ( lowercase : Any , lowercase : Any ) -> Optional[Any]: for tf_name, hf_name in patterns: _a = k.replace(lowercase , lowercase ) return k def _lowerCamelCase ( lowercase : dict , lowercase : dict ) -> BigBirdPegasusForConditionalGeneration: _a = BigBirdPegasusConfig(**lowercase ) _a = BigBirdPegasusForConditionalGeneration(lowercase ) _a = torch_model.state_dict() _a = {} # separating decoder weights _a = {k: tf_weights[k] for k in tf_weights if k.startswith("pegasus/decoder" )} _a = {k: tf_weights[k] for k in tf_weights if not k.startswith("pegasus/decoder" )} for k, v in tqdm(decoder_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = DECODER_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict: raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' for k, v in tqdm(remaining_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = REMAINING_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' _a = mapping["model.embed_positions.weight"] _a = mapping.pop("model.embed_positions.weight" ) _a , _a = torch_model.load_state_dict(lowercase , strict=lowercase ) _a = [ k for k in missing if k not in [ "final_logits_bias", "model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight", ] ] assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}' assert extra == [], F'no matches found for the following tf keys {extra}' return torch_model def _lowerCamelCase ( lowercase : List[Any] ) -> Dict: _a = tf.train.list_variables(lowercase ) _a = {} _a = ["global_step"] for name, shape in tqdm(lowercase , desc="converting tf checkpoint to dict" ): _a = any(pat in name for pat in ignore_name ) if skip_key: continue _a = tf.train.load_variable(lowercase , lowercase ) _a = array return tf_weights def _lowerCamelCase ( lowercase : str , lowercase : str , lowercase : dict ) -> Union[str, Any]: _a = get_tf_weights_as_numpy(lowercase ) _a = convert_bigbird_pegasus(lowercase , lowercase ) torch_model.save_pretrained(lowercase ) if __name__ == "__main__": lowerCAmelCase_ : str = argparse.ArgumentParser() parser.add_argument('--tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('--save_dir', default=None, type=str, help='Path to the output PyTorch model.') lowerCAmelCase_ : Optional[Any] = parser.parse_args() lowerCAmelCase_ : Optional[Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase__ : Any = logging.get_logger(__name__) lowercase__ : List[Any] = '▁' lowercase__ : Optional[int] = {'vocab_file': 'sentencepiece.bpe.model'} lowercase__ : Optional[Any] = { 'vocab_file': { 'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model', } } lowercase__ : List[Any] = { 'facebook/xglm-564M': 20_48, } class _UpperCAmelCase ( lowerCamelCase_): _lowerCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES _lowerCAmelCase : str = PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase : List[str] = ["""input_ids""", """attention_mask"""] def __init__( self : str , lowercase_ : Optional[int] , lowercase_ : Optional[Any]="<s>" , lowercase_ : Union[str, Any]="</s>" , lowercase_ : Tuple="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Optional[int]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Union[str, Any] , ): snake_case_ : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer snake_case_ : Union[str, Any] = 7 snake_case_ : List[str] = [f"<madeupword{i}>" for i in range(self.num_madeup_words )] snake_case_ : Optional[int] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , cls_token=__a , pad_token=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) snake_case_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__a ) ) snake_case_ : Dict = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case_ : Optional[int] = 1 # Mimic fairseq token-to-id alignment for the first 4 token snake_case_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} snake_case_ : Tuple = len(self.sp_model ) snake_case_ : Tuple = {f"<madeupword{i}>": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(__a ) snake_case_ : Any = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Tuple ): snake_case_ : int = self.__dict__.copy() snake_case_ : Dict = None snake_case_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[Any] , lowercase_ : Union[str, Any] ): snake_case_ : Optional[int] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): snake_case_ : Optional[Any] = {} snake_case_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _snake_case ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None ): if token_ids_a is None: return [self.sep_token_id] + token_ids_a snake_case_ : List[str] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _snake_case ( self : Tuple , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) if token_ids_a is None: return [1] + ([0] * len(__a )) return [1] + ([0] * len(__a )) + [1, 1] + ([0] * len(__a )) def _snake_case ( self : List[str] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None ): snake_case_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def _snake_case ( self : List[str] ): return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def _snake_case ( self : List[Any] ): snake_case_ : Tuple = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self : Union[str, Any] , lowercase_ : str ): return self.sp_model.encode(__a , out_type=__a ) def _snake_case ( self : Optional[Any] , lowercase_ : Dict ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case_ : List[str] = self.sp_model.PieceToId(__a ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self : int , lowercase_ : str ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self : Any , lowercase_ : List[str] ): snake_case_ : Any = ''''''.join(__a ).replace(__a , ''' ''' ).strip() return out_string def _snake_case ( self : Dict , lowercase_ : str , lowercase_ : Optional[str] = None ): if not os.path.isdir(__a ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return snake_case_ : Optional[int] = os.path.join( __a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __a ) elif not os.path.isfile(self.vocab_file ): with open(__a , '''wb''' ) as fi: snake_case_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__a ) return (out_vocab_file,)
123
'''simple docstring''' def _lowerCamelCase ( lowercase : str , lowercase : list[str] ) -> str: _a = "" for word_or_phrase in separated: if not isinstance(lowercase , lowercase ): raise Exception("join() accepts only strings to be joined" ) joined += word_or_phrase + separator return joined.strip(lowercase ) if __name__ == "__main__": from doctest import testmod testmod()
692
0
from collections import deque from .hash_table import HashTable class lowerCAmelCase__ ( lowerCamelCase_ ): '''simple docstring''' def __init__( self : Any , *snake_case__ : Union[str, Any] , **snake_case__ : List[str] ) -> Optional[int]: super().__init__(*__a , **__a ) def _snake_case ( self : List[Any] , snake_case__ : List[Any] , snake_case__ : Tuple ) -> Union[str, Any]: _lowerCamelCase = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__a ) _lowerCamelCase = self.values[key] def _snake_case ( self : Tuple ) -> str: return ( sum(self.charge_factor - len(__a ) for slot in self.values ) / self.size_table * self.charge_factor ) def _snake_case ( self : Dict , snake_case__ : Union[str, Any] , snake_case__ : Any=None ) -> Any: if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__a ) == 0 ): return key return super()._collision_resolution(__a , __a )
544
'''simple docstring''' lowerCAmelCase_ : Optional[Any] = '\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' lowerCAmelCase_ : List[Any] = [{'type': 'code', 'content': INSTALL_CONTENT}] lowerCAmelCase_ : Dict = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
692
0
from __future__ import annotations def _lowerCAmelCase ( _lowerCAmelCase ) -> bool: '''simple docstring''' return len(set(_lowerCAmelCase ) ) == len(_lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
371
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') lowerCAmelCase_ : Optional[Any] = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) lowerCAmelCase_ : Dict = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) lowerCAmelCase_ : Dict = BeautifulSoup(res.text, 'html.parser') lowerCAmelCase_ : Optional[int] = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f"""https://google.com{link.get('href')}""")
692
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase_ : Any = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ : List[str] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys lowercase_ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
304
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets lowerCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) lowerCAmelCase_ : Tuple = '\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n author = "Moosavi, Nafise Sadat and\n Strube, Michael",\n booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/P16-1060",\n doi = "10.18653/v1/P16-1060",\n pages = "632--642",\n}\n\n' lowerCAmelCase_ : Union[str, Any] = '\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n' lowerCAmelCase_ : Union[str, Any] = '\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting \'keep_singletons=False\', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n \'mentions\': mentions\n \'muc\': MUC metric [Vilain et al, 1995]\n \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n \'ceafe\': CEAFe [Luo et al., 2005]\n \'lea\': LEA [Moosavi and Strube, 2016]\n \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric(\'coval\')\n >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\',\n ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\',\n ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\',\n ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\',\n ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\',\n ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n' def _lowerCamelCase ( lowercase : Tuple , lowercase : List[Any] , lowercase : Optional[int]=False , lowercase : Dict=False , lowercase : Optional[int]=True , lowercase : Union[str, Any]=False , lowercase : int="dummy_doc" ) -> Union[str, Any]: _a = {doc: key_lines} _a = {doc: sys_lines} _a = {} _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a , _a = reader.get_doc_mentions(lowercase , key_doc_lines[doc] , lowercase ) key_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) _a , _a = reader.get_doc_mentions(lowercase , sys_doc_lines[doc] , lowercase ) sys_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) if remove_nested: _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters _a = reader.get_mention_assignments(lowercase , lowercase ) _a = reader.get_mention_assignments(lowercase , lowercase ) _a = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( "Number of removed nested coreferring mentions in the key " F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( "Number of resulting singleton clusters in the key " F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' "files, respectively" ) return doc_coref_infos def _lowerCamelCase ( lowercase : List[Any] , lowercase : Any , lowercase : Optional[Any] , lowercase : Union[str, Any] , lowercase : Any , lowercase : List[str] , lowercase : Dict ) -> str: _a = get_coref_infos(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) _a = {} _a = 0 _a = 0 for name, metric in metrics: _a , _a , _a = evaluator.evaluate_documents(lowercase , lowercase , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} ) logger.info( name.ljust(10 ) , F'Recall: {recall * 100:.2f}' , F' Precision: {precision * 100:.2f}' , F' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: _a = (conll / 3) * 100 logger.info(F'CoNLL score: {conll:.2f}' ) output_scores.update({"conll_score": conll} ) return output_scores def _lowerCamelCase ( lowercase : Any ) -> str: _a = False for line in key_lines: if not line.startswith("#" ): if len(line.split() ) > 6: _a = line.split()[5] if not parse_col == "-": _a = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE (datasets.Metric ): """simple docstring""" def UpperCamelCase__ ( self : str ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Sequence(datasets.Value("string" ) ), } ) , codebase_urls=["https://github.com/ns-moosavi/coval"] , reference_urls=[ "https://github.com/ns-moosavi/coval", "https://www.aclweb.org/anthology/P16-1060", "http://www.conll.cemantix.org/2012/data.html", ] , ) def UpperCamelCase__ ( self : int , __a : Any , __a : int , __a : Optional[Any]=True , __a : Optional[Any]=False , __a : str=False , __a : List[str]=False ): _a = [ ("mentions", evaluator.mentions), ("muc", evaluator.muc), ("bcub", evaluator.b_cubed), ("ceafe", evaluator.ceafe), ("lea", evaluator.lea), ] if min_span: _a = util.check_gold_parse_annotation(__a ) if not has_gold_parse: raise NotImplementedError("References should have gold parse annotation to use 'min_span'." ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" _a = evaluate( key_lines=__a , sys_lines=__a , metrics=__a , NP_only=__a , remove_nested=__a , keep_singletons=__a , min_span=__a , ) return score
692
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase=False ) -> List[str]: '''simple docstring''' UpperCAmelCase__ : List[str] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"blocks.{i}.norm1.weight", F"deit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((F"blocks.{i}.norm1.bias", F"deit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((F"blocks.{i}.attn.proj.weight", F"deit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((F"blocks.{i}.attn.proj.bias", F"deit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((F"blocks.{i}.norm2.weight", F"deit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((F"blocks.{i}.norm2.bias", F"deit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((F"blocks.{i}.mlp.fc1.weight", F"deit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((F"blocks.{i}.mlp.fc1.bias", F"deit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((F"blocks.{i}.mlp.fc2.weight", F"deit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((F"blocks.{i}.mlp.fc2.bias", F"deit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" UpperCAmelCase__ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=False ) -> str: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: UpperCAmelCase__ : List[str] = """""" else: UpperCAmelCase__ : List[str] = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase__ : Dict = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) UpperCAmelCase__ : Optional[int] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] UpperCAmelCase__ : List[Any] = in_proj_bias[: config.hidden_size] UpperCAmelCase__ : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase__ : Tuple = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase__ : Union[str, Any] = in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase__ : int = in_proj_bias[-config.hidden_size :] def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ : Any = dct.pop(__lowerCamelCase ) UpperCAmelCase__ : str = val def _lowerCamelCase ( ) -> str: '''simple docstring''' UpperCAmelCase__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCAmelCase__ : Optional[int] = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw ) return im @torch.no_grad() def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ) -> Dict: '''simple docstring''' UpperCAmelCase__ : List[Any] = DeiTConfig() # all deit models have fine-tuned heads UpperCAmelCase__ : Any = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size UpperCAmelCase__ : List[Any] = 1000 UpperCAmelCase__ : Any = """huggingface/label-files""" UpperCAmelCase__ : Optional[Any] = """imagenet-1k-id2label.json""" UpperCAmelCase__ : List[Any] = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) UpperCAmelCase__ : int = {int(__lowerCamelCase ): v for k, v in idalabel.items()} UpperCAmelCase__ : Union[str, Any] = idalabel UpperCAmelCase__ : List[str] = {v: k for k, v in idalabel.items()} UpperCAmelCase__ : int = int(deit_name[-6:-4] ) UpperCAmelCase__ : Optional[int] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): UpperCAmelCase__ : List[Any] = 192 UpperCAmelCase__ : int = 768 UpperCAmelCase__ : Dict = 12 UpperCAmelCase__ : List[str] = 3 elif deit_name[9:].startswith("""small""" ): UpperCAmelCase__ : Union[str, Any] = 384 UpperCAmelCase__ : Tuple = 1536 UpperCAmelCase__ : Dict = 12 UpperCAmelCase__ : Optional[int] = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): UpperCAmelCase__ : List[Any] = 1024 UpperCAmelCase__ : Dict = 4096 UpperCAmelCase__ : str = 24 UpperCAmelCase__ : Optional[Any] = 16 # load original model from timm UpperCAmelCase__ : str = timm.create_model(__lowerCamelCase , pretrained=__lowerCamelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys UpperCAmelCase__ : Tuple = timm_model.state_dict() UpperCAmelCase__ : int = create_rename_keys(__lowerCamelCase , __lowerCamelCase ) for src, dest in rename_keys: rename_key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) read_in_q_k_v(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # load HuggingFace model UpperCAmelCase__ : int = DeiTForImageClassificationWithTeacher(__lowerCamelCase ).eval() model.load_state_dict(__lowerCamelCase ) # Check outputs on an image, prepared by DeiTImageProcessor UpperCAmelCase__ : Dict = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 UpperCAmelCase__ : int = DeiTImageProcessor(size=__lowerCamelCase , crop_size=config.image_size ) UpperCAmelCase__ : Tuple = image_processor(images=prepare_img() , return_tensors="""pt""" ) UpperCAmelCase__ : Optional[Any] = encoding["""pixel_values"""] UpperCAmelCase__ : List[Any] = model(__lowerCamelCase ) UpperCAmelCase__ : Optional[Any] = timm_model(__lowerCamelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__lowerCamelCase , outputs.logits , atol=1E-3 ) Path(__lowerCamelCase ).mkdir(exist_ok=__lowerCamelCase ) print(F"Saving model {deit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__lowerCamelCase ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--deit_name""", default="""vit_deit_base_distilled_patch16_224""", type=str, help="""Name of the DeiT timm model you\'d like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
79
'''simple docstring''' import math def _lowerCamelCase ( lowercase : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowercase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCamelCase ( lowercase : float = 0.1 ) -> int: _a = 3 _a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowercase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
0
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _lowerCAmelCase ( lowerCamelCase_ ): """simple docstring""" __magic_name__ :Tuple = ["""image_processor""", """tokenizer"""] __magic_name__ :List[str] = """LayoutLMv3ImageProcessor""" __magic_name__ :Dict = ("""LayoutLMv3Tokenizer""", """LayoutLMv3TokenizerFast""") def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , __a , ) lowerCAmelCase__ :Optional[Any] = kwargs.pop('feature_extractor' ) lowerCAmelCase__ :Optional[int] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(__a , __a ) def __call__( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = False , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = 0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( 'You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( 'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' ) # first, apply the image processor lowerCAmelCase__ :Dict = self.image_processor(images=__a , return_tensors=__a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__a , __a ): lowerCAmelCase__ :Optional[int] = [text] # add batch dimension (as the image processor always adds a batch dimension) lowerCAmelCase__ :Tuple = features['words'] lowerCAmelCase__ :Tuple = self.tokenizer( text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) # add pixel values lowerCAmelCase__ :List[Any] = features.pop('pixel_values' ) if return_overflowing_tokens is True: lowerCAmelCase__ :Optional[Any] = self.get_overflowing_images(__a , encoded_inputs['overflow_to_sample_mapping'] ) lowerCAmelCase__ :int = images return encoded_inputs def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(__a ) != len(__a ): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' F" {len(__a )} and {len(__a )}" ) return images_with_overflow def snake_case ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.tokenizer.decode(*__a , **__a ) @property def snake_case ( self ): '''simple docstring''' return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def snake_case ( self ): '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , __a , ) return self.image_processor_class @property def snake_case ( self ): '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , __a , ) return self.image_processor
93
'''simple docstring''' import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(CMStochasticIterativeScheduler,) __a =10 def UpperCamelCase__ ( self : Union[str, Any] , **__a : str ): _a = { "num_train_timesteps": 2_01, "sigma_min": 0.002, "sigma_max": 80.0, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[Any] ): _a = 10 _a = self.get_scheduler_config() _a = self.scheduler_classes[0](**__a ) scheduler.set_timesteps(__a ) _a = scheduler.timesteps[0] _a = scheduler.timesteps[1] _a = self.dummy_sample _a = 0.1 * sample _a = scheduler.step(__a , __a , __a ).prev_sample _a = scheduler.step(__a , __a , __a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase__ ( self : Any ): for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : int ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = 1 scheduler.set_timesteps(__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(__a ): # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [1_06, 0] scheduler.set_timesteps(timesteps=__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCamelCase__ ( self : List[Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 15, 0] with self.assertRaises(__a , msg="`timesteps` must be in descending order." ): scheduler.set_timesteps(timesteps=__a ) def UpperCamelCase__ ( self : Tuple ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 1, 0] _a = len(__a ) with self.assertRaises(__a , msg="Can only pass one of `num_inference_steps` or `timesteps`." ): scheduler.set_timesteps(num_inference_steps=__a , timesteps=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [scheduler.config.num_train_timesteps] with self.assertRaises( __a , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=__a )
692
0
"""simple docstring""" import os def snake_case_ ( A_ : str = "matrix.txt" ): '''simple docstring''' with open(os.path.join(os.path.dirname(A_ ), A_ ) ) as in_file: _lowerCamelCase : Dict = in_file.read() _lowerCamelCase : Union[str, Any] = [[int(A_ ) for cell in row.split(''',''' )] for row in data.strip().splitlines()] _lowerCamelCase : int = [[0 for cell in row] for row in grid] _lowerCamelCase : str = len(grid[0] ) _lowerCamelCase : Tuple = [[0 for i in range(A_ )] for j in range(A_ )] _lowerCamelCase : List[Any] = grid[0][0] for i in range(1, A_ ): _lowerCamelCase : Tuple = grid[0][i] + dp[0][i - 1] for i in range(1, A_ ): _lowerCamelCase : Optional[int] = grid[i][0] + dp[i - 1][0] for i in range(1, A_ ): for j in range(1, A_ ): _lowerCamelCase : Union[str, Any] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(F"""{solution() = }""")
83
'''simple docstring''' import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : int , **__a : Optional[Any] ): warnings.warn( "The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use YolosImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' from argparse import ArgumentParser from . import BaseTransformersCLICommand def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ) -> Tuple: return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class lowercase_ ( lowerCamelCase_ ): @staticmethod def _lowerCAmelCase ( __lowerCamelCase : ArgumentParser ): snake_case__ : Any = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' , type=__a , default=__a , help='Path to location to store the models' ) download_parser.add_argument( '--force' , action='store_true' , help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' , action='store_true' , help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' , ) download_parser.add_argument('model' , type=__a , help='Name of the model to download' ) download_parser.set_defaults(func=__a ) def __init__( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : bool , __lowerCamelCase : bool ): snake_case__ : Tuple = model snake_case__ : str = cache snake_case__ : str = force snake_case__ : Union[str, Any] = trust_remote_code def _lowerCAmelCase ( self : List[Any] ): from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
270
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) lowerCAmelCase_ : str = { 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='timesformer' def __init__( self : Optional[int] , __a : Optional[int]=2_24 , __a : Tuple=16 , __a : int=3 , __a : Union[str, Any]=8 , __a : Union[str, Any]=7_68 , __a : List[str]=12 , __a : Union[str, Any]=12 , __a : Optional[Any]=30_72 , __a : Tuple="gelu" , __a : str=0.0 , __a : List[Any]=0.0 , __a : Any=0.02 , __a : List[str]=1e-6 , __a : Any=True , __a : Union[str, Any]="divided_space_time" , __a : str=0 , **__a : Tuple , ): super().__init__(**__a ) _a = image_size _a = patch_size _a = num_channels _a = num_frames _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = initializer_range _a = layer_norm_eps _a = qkv_bias _a = attention_type _a = drop_path_rate
692
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase = { 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipConfig', 'InstructBlipQFormerConfig', 'InstructBlipVisionConfig', ], 'processing_instructblip': ['InstructBlipProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ 'INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'InstructBlipQFormerModel', 'InstructBlipPreTrainedModel', 'InstructBlipForConditionalGeneration', 'InstructBlipVisionModel', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
96
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase__ ( self : Dict ): _a = 1 _a = 3 _a = (32, 32) _a = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__a ) return image @property def UpperCamelCase__ ( self : Dict ): torch.manual_seed(0 ) _a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def UpperCamelCase__ ( self : Optional[int] ): torch.manual_seed(0 ) _a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def UpperCamelCase__ ( self : Optional[Any] ): torch.manual_seed(0 ) _a = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=50_06 , ) return RobertaSeriesModelWithTransformation(__a ) @property def UpperCamelCase__ ( self : str ): def extract(*__a : Tuple , **__a : str ): class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict ): _a = torch.ones([0] ) def UpperCamelCase__ ( self : List[str] , __a : Dict ): self.pixel_values.to(__a ) return self return Out() return extract def UpperCamelCase__ ( self : Optional[int] ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) _a = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , ) _a = output.images _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , return_dict=__a , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) # put models in fp16 _a = unet.half() _a = vae.half() _a = bert.half() # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , num_inference_steps=2 , output_type="np" , image=__a , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 _a = init_image.resize((7_60, 5_04) ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] _a = image[2_55:2_58, 3_83:3_86, -1] assert image.shape == (5_04, 7_60, 3) _a = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : Union[str, Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) _a = init_image.resize((7_68, 5_12) ) _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] assert image.shape == (5_12, 7_68, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
692
0
"""simple docstring""" import math def A_ ( lowercase = 100 ) -> int: """simple docstring""" UpperCAmelCase_ : List[Any] = sum(i * i for i in range(1 , n + 1 ) ) UpperCAmelCase_ : List[Any] = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
470
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , *__a : Tuple , **__a : Optional[Any] ): warnings.warn( "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DPTImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class a_ : a : Optional[Any] = 4_2 a : List[str] = 4_2 class a_ : def __init__( self , __UpperCamelCase ): _lowercase = [[] for _ in range(__a )] _lowercase = size def __getitem__( self , __UpperCamelCase ): return iter(self._graph[vertex] ) @property def UpperCamelCase_ ( self ): return self._size def UpperCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(__a , __a ) ) def UpperCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase ): _lowercase = deque([start_vertex] ) _lowercase = [None] * self.size _lowercase = 0 while queue: _lowercase = queue.popleft() _lowercase = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _lowercase = current_distance + edge.weight _lowercase = distances[edge.destination_vertex] if ( isinstance(__a , __a ) and new_distance >= dest_vertex_distance ): continue _lowercase = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
287
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Any ) -> Tuple: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : str = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Dict: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] ) -> Dict: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Optional[Any] , __a : Dict , __a : Optional[int] ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Optional[int]=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : List[str] , __a : Optional[Any] , __a : List[str] ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Dict , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : Optional[int] ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
692
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class _UpperCAmelCase ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase): _lowerCAmelCase : int = StableDiffusionPanoramaPipeline _lowerCAmelCase : Union[str, Any] = TEXT_TO_IMAGE_PARAMS _lowerCAmelCase : Optional[int] = TEXT_TO_IMAGE_BATCH_PARAMS _lowerCAmelCase : Any = TEXT_TO_IMAGE_IMAGE_PARAMS _lowerCAmelCase : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS def _snake_case ( self : int ): torch.manual_seed(0 ) snake_case_ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) snake_case_ : List[str] = DDIMScheduler() torch.manual_seed(0 ) snake_case_ : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case_ : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) snake_case_ : List[Any] = CLIPTextModel(__a ) snake_case_ : Optional[Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) snake_case_ : int = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def _snake_case ( self : Union[str, Any] , lowercase_ : Tuple , lowercase_ : List[Any]=0 ): snake_case_ : Optional[Any] = torch.manual_seed(__a ) snake_case_ : Any = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, # Setting height and width to None to prevent OOMs on CPU. '''height''': None, '''width''': None, '''num_inference_steps''': 1, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def _snake_case ( self : Optional[int] ): snake_case_ : Tuple = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case_ : List[str] = self.get_dummy_components() snake_case_ : List[str] = StableDiffusionPanoramaPipeline(**__a ) snake_case_ : Optional[Any] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) snake_case_ : List[str] = self.get_dummy_inputs(__a ) snake_case_ : Tuple = sd_pipe(**__a ).images snake_case_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ : Union[str, Any] = np.array([0.61_86, 0.53_74, 0.49_15, 0.41_35, 0.41_14, 0.45_63, 0.51_28, 0.49_77, 0.47_57] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self : Any ): super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def _snake_case ( self : Union[str, Any] ): super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def _snake_case ( self : Dict ): snake_case_ : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case_ : Tuple = self.get_dummy_components() snake_case_ : List[str] = StableDiffusionPanoramaPipeline(**__a ) snake_case_ : Optional[int] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) snake_case_ : Dict = self.get_dummy_inputs(__a ) snake_case_ : List[Any] = '''french fries''' snake_case_ : Optional[int] = sd_pipe(**__a , negative_prompt=__a ) snake_case_ : Union[str, Any] = output.images snake_case_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ : int = np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self : Optional[int] ): snake_case_ : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case_ : int = self.get_dummy_components() snake_case_ : Optional[int] = StableDiffusionPanoramaPipeline(**__a ) snake_case_ : Union[str, Any] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) snake_case_ : Optional[Any] = self.get_dummy_inputs(__a ) snake_case_ : Optional[Any] = sd_pipe(**__a , view_batch_size=2 ) snake_case_ : List[Any] = output.images snake_case_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ : Any = np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self : List[str] ): snake_case_ : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case_ : List[str] = self.get_dummy_components() snake_case_ : int = EulerAncestralDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' ) snake_case_ : Optional[Any] = StableDiffusionPanoramaPipeline(**__a ) snake_case_ : str = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) snake_case_ : str = self.get_dummy_inputs(__a ) snake_case_ : Dict = sd_pipe(**__a ).images snake_case_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ : Dict = np.array([0.40_24, 0.65_10, 0.49_01, 0.53_78, 0.58_13, 0.56_22, 0.47_95, 0.44_67, 0.49_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self : Union[str, Any] ): snake_case_ : Union[str, Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case_ : Optional[int] = self.get_dummy_components() snake_case_ : Any = PNDMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , skip_prk_steps=__a ) snake_case_ : Union[str, Any] = StableDiffusionPanoramaPipeline(**__a ) snake_case_ : Optional[int] = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) snake_case_ : Optional[Any] = self.get_dummy_inputs(__a ) snake_case_ : Union[str, Any] = sd_pipe(**__a ).images snake_case_ : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ : List[Any] = np.array([0.63_91, 0.62_91, 0.48_61, 0.51_34, 0.55_52, 0.45_78, 0.50_32, 0.50_23, 0.45_39] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase): def _snake_case ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self : List[Any] , lowercase_ : Union[str, Any]=0 ): snake_case_ : List[Any] = torch.manual_seed(__a ) snake_case_ : Optional[int] = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def _snake_case ( self : int ): snake_case_ : Tuple = '''stabilityai/stable-diffusion-2-base''' snake_case_ : Optional[Any] = DDIMScheduler.from_pretrained(__a , subfolder='''scheduler''' ) snake_case_ : Tuple = StableDiffusionPanoramaPipeline.from_pretrained(__a , scheduler=__a , safety_checker=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() snake_case_ : List[str] = self.get_inputs() snake_case_ : List[str] = pipe(**__a ).images snake_case_ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) snake_case_ : List[str] = np.array( [ 0.36_96_83_92, 0.27_02_53_72, 0.32_44_67_66, 0.28_37_93_87, 0.36_36_32_74, 0.30_73_33_47, 0.27_10_00_27, 0.27_05_41_25, 0.25_53_60_96, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def _snake_case ( self : Optional[Any] ): snake_case_ : List[Any] = StableDiffusionPanoramaPipeline.from_pretrained( '''stabilityai/stable-diffusion-2-base''' , safety_checker=__a ) snake_case_ : List[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() snake_case_ : Dict = self.get_inputs() snake_case_ : Union[str, Any] = pipe(**__a ).images snake_case_ : Any = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) snake_case_ : int = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def _snake_case ( self : List[Any] ): snake_case_ : List[str] = 0 def callback_fn(lowercase_ : int , lowercase_ : int , lowercase_ : torch.FloatTensor ) -> None: snake_case_ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: snake_case_ : str = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) snake_case_ : Optional[Any] = latents[0, -3:, -3:, -1] snake_case_ : Tuple = np.array( [ 0.18_68_18_69, 0.33_90_78_16, 0.5_36_12_76, 0.14_43_28_65, -0.02_85_66_11, -0.73_94_11_23, 0.23_39_79_87, 0.47_32_26_82, -0.37_82_31_64, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: snake_case_ : Any = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) snake_case_ : Optional[Any] = latents[0, -3:, -3:, -1] snake_case_ : List[str] = np.array( [ 0.18_53_96_45, 0.33_98_72_48, 0.5_37_85_59, 0.14_43_71_42, -0.02_45_52_61, -0.7_33_83_17, 0.23_99_07_55, 0.47_35_62_72, -0.3_78_65_05, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 snake_case_ : Any = False snake_case_ : int = '''stabilityai/stable-diffusion-2-base''' snake_case_ : str = DDIMScheduler.from_pretrained(__a , subfolder='''scheduler''' ) snake_case_ : Any = StableDiffusionPanoramaPipeline.from_pretrained(__a , scheduler=__a , safety_checker=__a ) snake_case_ : List[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() snake_case_ : Union[str, Any] = self.get_inputs() pipe(**__a , callback=__a , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def _snake_case ( self : int ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() snake_case_ : Tuple = '''stabilityai/stable-diffusion-2-base''' snake_case_ : Any = DDIMScheduler.from_pretrained(__a , subfolder='''scheduler''' ) snake_case_ : int = StableDiffusionPanoramaPipeline.from_pretrained(__a , scheduler=__a , safety_checker=__a ) snake_case_ : Union[str, Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() snake_case_ : Dict = self.get_inputs() snake_case_ : str = pipe(**__a ) snake_case_ : List[Any] = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
123
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase_ : Any = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys lowerCAmelCase_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
692
0
def lowerCamelCase ( UpperCamelCase : int = 1_00 ) -> int: _lowerCamelCase = n * (n + 1) * (2 * n + 1) / 6 _lowerCamelCase = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'''{solution() = }''')
544
'''simple docstring''' import gc import threading import time import psutil import torch class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] ): _a = psutil.Process() _a = False def UpperCamelCase__ ( self : Tuple ): _a = -1 while True: _a = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def UpperCamelCase__ ( self : List[Any] ): _a = True _a = threading.Thread(target=self.peak_monitor ) _a = True self.thread.start() def UpperCamelCase__ ( self : Optional[int] ): _a = False self.thread.join() return self.cpu_memory_peak lowerCAmelCase_ : List[Any] = PeakCPUMemory() def _lowerCamelCase ( ) -> Tuple: # Time _a = {"time": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem _a = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): _a = torch.cuda.memory_allocated(lowercase ) torch.cuda.reset_peak_memory_stats() return measures def _lowerCamelCase ( lowercase : Any ) -> int: # Time _a = {"time": time.time() - start_measures["time"]} gc.collect() torch.cuda.empty_cache() # CPU mem _a = (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20 _a = (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): _a = (torch.cuda.memory_allocated(lowercase ) - start_measures[str(lowercase )]) / 2**20 _a = (torch.cuda.max_memory_allocated(lowercase ) - start_measures[str(lowercase )]) / 2**20 return measures def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Dict ) -> str: print(F'{description}:' ) print(F'- Time: {measures["time"]:.2f}s' ) for i in range(torch.cuda.device_count() ): print(F'- GPU {i} allocated: {measures[str(lowercase )]:.2f}MiB' ) _a = measures[F'{i}-peak'] print(F'- GPU {i} peak: {peak:.2f}MiB' ) print(F'- CPU RAM allocated: {measures["cpu"]:.2f}MiB' ) print(F'- CPU RAM peak: {measures["cpu-peak"]:.2f}MiB' )
692
0
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer A : Union[str, Any] = 'bart' A : Optional[int] = True @st.cache(allow_output_mutation=_lowerCAmelCase ) def _lowerCAmelCase ( ) -> List[str]: '''simple docstring''' if LOAD_DENSE_INDEX: __snake_case = AutoTokenizer.from_pretrained("yjernite/retribert-base-uncased" ) __snake_case = AutoModel.from_pretrained("yjernite/retribert-base-uncased" ).to("cuda:0" ) __snake_case = qar_model.eval() else: __snake_case , __snake_case = (None, None) if MODEL_TYPE == "bart": __snake_case = AutoTokenizer.from_pretrained("yjernite/bart_eli5" ) __snake_case = AutoModelForSeqaSeqLM.from_pretrained("yjernite/bart_eli5" ).to("cuda:0" ) __snake_case = torch.load("seq2seq_models/eli5_bart_model_blm_2.pth" ) sas_model.load_state_dict(save_dict["model"] ) __snake_case = sas_model.eval() else: __snake_case , __snake_case = make_qa_sas_model( model_name="t5-small" , from_file="seq2seq_models/eli5_t5_model_1024_4.pth" , device="cuda:0" ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=_lowerCAmelCase ) def _lowerCAmelCase ( ) -> Optional[int]: '''simple docstring''' if LOAD_DENSE_INDEX: __snake_case = faiss.StandardGpuResources() __snake_case = datasets.load_dataset(path="wiki_snippets" , name="wiki40b_en_100_0" )["train"] __snake_case = np.memmap( "wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat" , dtype="float32" , mode="r" , shape=(wikiaab_passages.num_rows, 128) , ) __snake_case = faiss.IndexFlatIP(128 ) __snake_case = faiss.index_cpu_to_gpu(_lowerCAmelCase , 1 , _lowerCAmelCase ) wikiaab_gpu_index_flat.add(_lowerCAmelCase ) # TODO fix for larger GPU else: __snake_case , __snake_case = (None, None) __snake_case = Elasticsearch([{"host": "localhost", "port": "9200"}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=_lowerCAmelCase ) def _lowerCAmelCase ( ) -> Optional[Any]: '''simple docstring''' __snake_case = datasets.load_dataset("eli5" , name="LFQA_reddit" ) __snake_case = elia["train_eli5"] __snake_case = np.memmap( "eli5_questions_reps.dat" , dtype="float32" , mode="r" , shape=(elia_train.num_rows, 128) ) __snake_case = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(_lowerCAmelCase ) return (elia_train, eli5_train_q_index) A : Any = load_indexes() A : Optional[int] = load_models() A : str = load_train_data() def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase=10 ) -> Optional[Any]: '''simple docstring''' __snake_case = embed_questions_for_retrieval([question] , _lowerCAmelCase , _lowerCAmelCase ) __snake_case , __snake_case = eli5_train_q_index.search(_lowerCAmelCase , _lowerCAmelCase ) __snake_case = [elia_train[int(_lowerCAmelCase )] for i in I[0]] return nn_examples def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase="wiki40b" , _lowerCAmelCase="dense" , _lowerCAmelCase=10 ) -> Optional[int]: '''simple docstring''' if source == "none": __snake_case , __snake_case = (" <P> ".join(["" for _ in range(11 )] ).strip(), []) else: if method == "dense": __snake_case , __snake_case = query_qa_dense_index( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) else: __snake_case , __snake_case = query_es_index( _lowerCAmelCase , _lowerCAmelCase , index_name="english_wiki40b_snippets_100w" , n_results=_lowerCAmelCase , ) __snake_case = [ (res["article_title"], res["section_title"].strip(), res["score"], res["passage_text"]) for res in hit_lst ] __snake_case = "question: {} context: {}".format(_lowerCAmelCase , _lowerCAmelCase ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda _lowerCAmelCase : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _lowerCAmelCase : None), } ) def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=64 , _lowerCAmelCase=256 , _lowerCAmelCase=False , _lowerCAmelCase=2 , _lowerCAmelCase=0.95 , _lowerCAmelCase=0.8 ) -> Any: '''simple docstring''' with torch.no_grad(): __snake_case = qa_sas_generate( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , num_answers=1 , num_beams=_lowerCAmelCase , min_len=_lowerCAmelCase , max_len=_lowerCAmelCase , do_sample=_lowerCAmelCase , temp=_lowerCAmelCase , top_p=_lowerCAmelCase , top_k=_lowerCAmelCase , max_input_length=1024 , device="cuda:0" , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar A : List[str] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' A : Optional[Any] = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia A : List[str] = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) A : Tuple = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] A : int = st.sidebar.checkbox('Demo options') if demo_options: A : int = st.sidebar.selectbox( '', action_list, index=3, ) A : Tuple = action_list.index(action_st) A : List[Any] = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) A : List[str] = show_type == 'Show full text of passages' else: A : List[str] = 3 A : Optional[Any] = True A : Union[str, Any] = st.sidebar.checkbox('Retrieval options') if retrieval_options: A : Any = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) A : Optional[Any] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) A : List[Any] = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: A : Tuple = 'wiki40b' A : int = 'dense' A : List[Any] = 'beam' A : Dict = 2 A : Tuple = 64 A : int = 256 A : Optional[Any] = None A : Union[str, Any] = None A : List[str] = st.sidebar.checkbox('Generation options') if generate_options: A : str = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) A : Optional[int] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) A : Optional[int] = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) A : str = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": A : Optional[Any] = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: A : Any = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) A : str = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) A : Optional[int] = None # start main text A : Tuple = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] A : Tuple = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": A : Any = st.text_input('Enter your question here:', '') else: A : Union[str, Any] = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": A : str = make_support(question, source=wiki_source, method='dense', n_results=10) A : Tuple = make_support(question, source=wiki_source, method='sparse', n_results=10) A : Any = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] A : str = support_list[:10] A : List[Any] = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: A : List[str] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: A : Optional[int] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): A : Union[str, Any] = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) A : List[str] = res[1].strip() if sec_titles == "": A : List[Any] = '[{}]({})'.format(res[0], wiki_url) else: A : List[Any] = sec_titles.split(' & ') A : str = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: A : Union[str, Any] = find_nearest_training(question) A : int = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) A : Tuple = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) A : int = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
371
'''simple docstring''' import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(DDIMParallelScheduler,) __a =(('eta', 0.0), ('num_inference_steps', 50)) def UpperCamelCase__ ( self : Optional[int] , **__a : Any ): _a = { "num_train_timesteps": 10_00, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[str] , **__a : Optional[int] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config(**__a ) _a = scheduler_class(**__a ) _a , _a = 10, 0.0 _a = self.dummy_model() _a = self.dummy_sample_deter scheduler.set_timesteps(__a ) for t in scheduler.timesteps: _a = model(__a , __a ) _a = scheduler.step(__a , __a , __a , __a ).prev_sample return sample def UpperCamelCase__ ( self : str ): for timesteps in [1_00, 5_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : Dict ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__a ) _a = self.scheduler_classes[0] _a = self.get_scheduler_config(steps_offset=1 ) _a = scheduler_class(**__a ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_01, 6_01, 4_01, 2_01, 1] ) ) def UpperCamelCase__ ( self : Tuple ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def UpperCamelCase__ ( self : Dict ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__a ) def UpperCamelCase__ ( self : Tuple ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def UpperCamelCase__ ( self : Dict ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__a ) def UpperCamelCase__ ( self : Optional[int] ): for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__a ) def UpperCamelCase__ ( self : Optional[Any] ): for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__a ) def UpperCamelCase__ ( self : List[Any] ): self.check_over_configs(thresholding=__a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__a , prediction_type=__a , sample_max_value=__a , ) def UpperCamelCase__ ( self : List[Any] ): for t in [1, 10, 49]: self.check_over_forward(time_step=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 5_00] ): self.check_over_forward(time_step=__a , num_inference_steps=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__a , eta=__a ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_20 , 4_00 ) - 0.14771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_80 , 9_60 ) - 0.32460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 , 4_86 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 , 9_98 ) - 0.02 ) ) < 1e-5 def UpperCamelCase__ ( self : List[str] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a , _a = 10, 0.0 scheduler.set_timesteps(__a ) _a = self.dummy_model() _a = self.dummy_sample_deter _a = self.dummy_sample_deter + 0.1 _a = self.dummy_sample_deter - 0.1 _a = samplea.shape[0] _a = torch.stack([samplea, samplea, samplea] , dim=0 ) _a = torch.arange(__a )[0:3, None].repeat(1 , __a ) _a = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _a = scheduler.batch_step_no_noise(__a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __a ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1147.7904 ) < 1e-2 assert abs(result_mean.item() - 0.4982 ) < 1e-3 def UpperCamelCase__ ( self : List[str] ): _a = self.full_loop() _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 172.0067 ) < 1e-2 assert abs(result_mean.item() - 0.223967 ) < 1e-3 def UpperCamelCase__ ( self : str ): _a = self.full_loop(prediction_type="v_prediction" ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 52.5302 ) < 1e-2 assert abs(result_mean.item() - 0.0684 ) < 1e-3 def UpperCamelCase__ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _a = self.full_loop(set_alpha_to_one=__a , beta_start=0.01 ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 149.8295 ) < 1e-2 assert abs(result_mean.item() - 0.1951 ) < 1e-3 def UpperCamelCase__ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _a = self.full_loop(set_alpha_to_one=__a , beta_start=0.01 ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 149.0784 ) < 1e-2 assert abs(result_mean.item() - 0.1941 ) < 1e-3
692
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowercase_ : Dict = logging.get_logger(__name__) class lowercase ( lowerCamelCase_ ): """simple docstring""" _UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self : List[str] , lowerCamelCase_ : bool = True , lowerCamelCase_ : Dict[str, int] = None , lowerCamelCase_ : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase_ : bool = True , lowerCamelCase_ : Union[int, float] = 1 / 2_55 , lowerCamelCase_ : bool = True , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : bool = True , **lowerCamelCase_ : Optional[int] , ): '''simple docstring''' super().__init__(**__a ) _snake_case : str = size if size is not None else {'height': 3_84, 'width': 3_84} _snake_case : List[str] = get_size_dict(__a , default_to_square=__a ) _snake_case : List[str] = do_resize _snake_case : int = size _snake_case : int = resample _snake_case : int = do_rescale _snake_case : int = rescale_factor _snake_case : Optional[Any] = do_normalize _snake_case : Any = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _snake_case : str = image_std if image_std is not None else OPENAI_CLIP_STD _snake_case : Optional[int] = do_convert_rgb def __UpperCAmelCase ( self : Tuple , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Dict[str, int] , lowerCamelCase_ : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : List[Any] , ): '''simple docstring''' _snake_case : Dict = get_size_dict(__a , default_to_square=__a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}''' ) _snake_case : int = (size['height'], size['width']) return resize(__a , size=__a , resample=__a , data_format=__a , **__a ) def __UpperCAmelCase ( self : str , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Union[int, float] , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : Any , ): '''simple docstring''' return rescale(__a , scale=__a , data_format=__a , **__a ) def __UpperCAmelCase ( self : Any , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Union[float, List[float]] , lowerCamelCase_ : Union[float, List[float]] , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : List[str] , ): '''simple docstring''' return normalize(__a , mean=__a , std=__a , data_format=__a , **__a ) def __UpperCAmelCase ( self : List[Any] , lowerCamelCase_ : ImageInput , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[Dict[str, int]] = None , lowerCamelCase_ : PILImageResampling = None , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[float] = None , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[str, TensorType]] = None , lowerCamelCase_ : bool = None , lowerCamelCase_ : ChannelDimension = ChannelDimension.FIRST , **lowerCamelCase_ : List[str] , ): '''simple docstring''' _snake_case : str = do_resize if do_resize is not None else self.do_resize _snake_case : int = resample if resample is not None else self.resample _snake_case : List[str] = do_rescale if do_rescale is not None else self.do_rescale _snake_case : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor _snake_case : List[str] = do_normalize if do_normalize is not None else self.do_normalize _snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean _snake_case : int = image_std if image_std is not None else self.image_std _snake_case : Optional[int] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _snake_case : Any = size if size is not None else self.size _snake_case : str = get_size_dict(__a , default_to_square=__a ) _snake_case : Tuple = make_list_of_images(__a ) if not valid_images(__a ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: _snake_case : str = [convert_to_rgb(__a ) for image in images] # All transformations expect numpy arrays. _snake_case : Union[str, Any] = [to_numpy_array(__a ) for image in images] if do_resize: _snake_case : str = [self.resize(image=__a , size=__a , resample=__a ) for image in images] if do_rescale: _snake_case : Tuple = [self.rescale(image=__a , scale=__a ) for image in images] if do_normalize: _snake_case : Union[str, Any] = [self.normalize(image=__a , mean=__a , std=__a ) for image in images] _snake_case : List[Any] = [to_channel_dimension_format(__a , __a ) for image in images] _snake_case : Union[str, Any] = BatchFeature(data={'pixel_values': images} , tensor_type=__a ) return encoded_outputs
304
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _lowerCamelCase ( lowercase : Any ) -> List[str]: return getitem, k def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Any: return setitem, k, v def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: return delitem, k def _lowerCamelCase ( lowercase : Tuple , lowercase : Dict , *lowercase : Union[str, Any] ) -> int: try: return fun(lowercase , *lowercase ), None except Exception as e: return None, e lowerCAmelCase_ : Optional[Any] = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) lowerCAmelCase_ : Optional[int] = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] lowerCAmelCase_ : int = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] lowerCAmelCase_ : List[Any] = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('key_a', 'val_b'), ] @pytest.mark.parametrize( "operations" , ( pytest.param(_add_items , id="add items" ), pytest.param(_overwrite_items , id="overwrite items" ), pytest.param(_delete_items , id="delete items" ), pytest.param(_access_absent_items , id="access absent items" ), pytest.param(_add_with_resize_up , id="add with resize up" ), pytest.param(_add_with_resize_down , id="add with resize down" ), ) , ) def _lowerCamelCase ( lowercase : Optional[int] ) -> Optional[int]: _a = HashMap(initial_block_size=4 ) _a = {} for _, (fun, *args) in enumerate(lowercase ): _a , _a = _run_operation(lowercase , lowercase , *lowercase ) _a , _a = _run_operation(lowercase , lowercase , *lowercase ) assert my_res == py_res assert str(lowercase ) == str(lowercase ) assert set(lowercase ) == set(lowercase ) assert len(lowercase ) == len(lowercase ) assert set(my.items() ) == set(py.items() ) def _lowerCamelCase ( ) -> str: def is_public(lowercase : str ) -> bool: return not name.startswith("_" ) _a = {name for name in dir({} ) if is_public(lowercase )} _a = {name for name in dir(HashMap() ) if is_public(lowercase )} assert dict_public_names > hash_public_names
692
0
def _lowerCamelCase ( __lowerCamelCase = 3 , __lowerCamelCase = 7 , __lowerCamelCase = 100_0000 ) -> int: '''simple docstring''' UpperCAmelCase__ : List[Any] = 0 UpperCAmelCase__ : Any = 1 for current_denominator in range(1 , limit + 1 ): UpperCAmelCase__ : List[str] = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: UpperCAmelCase__ : Any = current_numerator UpperCAmelCase__ : Optional[Any] = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_00_00_00))
79
'''simple docstring''' import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =PhobertTokenizer __a =False def UpperCamelCase__ ( self : int ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _a = ["T@@", "i", "I", "R@@", "r", "e@@"] _a = dict(zip(__a , range(len(__a ) ) ) ) _a = ["#version: 0.2", "l à</w>"] _a = {"unk_token": "<unk>"} _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(f'{token} {vocab_tokens[token]}\n' ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__a ) ) def UpperCamelCase__ ( self : str , **__a : List[str] ): kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ): _a = "Tôi là VinAI Research" _a = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>" return input_text, output_text def UpperCamelCase__ ( self : Dict ): _a = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _a = "Tôi là VinAI Research" _a = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split() _a = tokenizer.tokenize(__a ) print(__a ) self.assertListEqual(__a , __a ) _a = tokens + [tokenizer.unk_token] _a = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a )
692
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class _lowerCAmelCase ( lowerCamelCase_ ): """simple docstring""" __magic_name__ :Union[str, Any] = """camembert""" def __init__( self , __UpperCAmelCase=3_0_5_2_2 , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=1_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=5_1_2 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=2 , __UpperCAmelCase="absolute" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) lowerCAmelCase__ :Optional[Any] = vocab_size lowerCAmelCase__ :Optional[Any] = hidden_size lowerCAmelCase__ :Optional[Any] = num_hidden_layers lowerCAmelCase__ :int = num_attention_heads lowerCAmelCase__ :Optional[Any] = hidden_act lowerCAmelCase__ :str = intermediate_size lowerCAmelCase__ :Optional[int] = hidden_dropout_prob lowerCAmelCase__ :str = attention_probs_dropout_prob lowerCAmelCase__ :Union[str, Any] = max_position_embeddings lowerCAmelCase__ :List[Any] = type_vocab_size lowerCAmelCase__ :str = initializer_range lowerCAmelCase__ :List[Any] = layer_norm_eps lowerCAmelCase__ :Dict = position_embedding_type lowerCAmelCase__ :int = use_cache lowerCAmelCase__ :Union[str, Any] = classifier_dropout class _lowerCAmelCase ( lowerCamelCase_ ): """simple docstring""" @property def snake_case ( self ): '''simple docstring''' if self.task == "multiple-choice": lowerCAmelCase__ :Union[str, Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowerCAmelCase__ :List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
93
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : str , *__a : Any , __a : str=None , __a : Union[str, Any]=None , **__a : Any ): super().__init__(*__a , **__a ) _a = eval_examples _a = post_process_function def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : Any=None , __a : str=None , __a : str = "eval" ): _a = self.eval_dataset if eval_dataset is None else eval_dataset _a = self.get_eval_dataloader(__a ) _a = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _a = self.compute_metrics _a = None _a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _a = time.time() try: _a = eval_loop( __a , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__a , metric_key_prefix=__a , ) finally: _a = compute_metrics _a = self.args.eval_batch_size * self.args.world_size if f'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( __a , __a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default _a = self.post_process_function(__a , __a , output.predictions ) _a = self.compute_metrics(__a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'{metric_key_prefix}_' ): _a = metrics.pop(__a ) metrics.update(output.metrics ) else: _a = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__a ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _a = self.callback_handler.on_evaluate(self.args , self.state , self.control , __a ) return metrics def UpperCamelCase__ ( self : Tuple , __a : Dict , __a : Optional[Any] , __a : Optional[Any]=None , __a : str = "test" ): _a = self.get_test_dataloader(__a ) # Temporarily disable metric computation, we will do it in the loop here. _a = self.compute_metrics _a = None _a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _a = time.time() try: _a = eval_loop( __a , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__a , metric_key_prefix=__a , ) finally: _a = compute_metrics _a = self.args.eval_batch_size * self.args.world_size if f'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( __a , __a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output _a = self.post_process_function(__a , __a , output.predictions , "predict" ) _a = self.compute_metrics(__a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'{metric_key_prefix}_' ): _a = metrics.pop(__a ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__a )
692
0
"""simple docstring""" def snake_case_ ( A_ : int ): '''simple docstring''' if n == 1 or not isinstance(A_, A_ ): return 0 elif n == 2: return 1 else: _lowerCamelCase : Any = [0, 1] for i in range(2, n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def snake_case_ ( A_ : int ): '''simple docstring''' _lowerCamelCase : List[str] = 0 _lowerCamelCase : str = 2 while digits < n: index += 1 _lowerCamelCase : int = len(str(fibonacci(A_ ) ) ) return index def snake_case_ ( A_ : int = 10_00 ): '''simple docstring''' return fibonacci_digits_index(A_ ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
83
'''simple docstring''' import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : Dict , **__a : List[Any] ): warnings.warn( "The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ChineseCLIPImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' import sys A_ = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ) -> int: snake_case__ : str = 1 for digit in s: product *= int(__SCREAMING_SNAKE_CASE ) return product def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE = N ) -> int: snake_case__ : Dict = -sys.maxsize - 1 snake_case__ : str = n[:13] snake_case__ : List[Any] = 13 while cur_index < len(__SCREAMING_SNAKE_CASE ) - 13: if int(n[cur_index] ) >= int(substr[0] ): snake_case__ : Optional[int] = substr[1:] + n[cur_index] cur_index += 1 else: snake_case__ : str = max(__SCREAMING_SNAKE_CASE , str_eval(__SCREAMING_SNAKE_CASE ) ) snake_case__ : str = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(F'{solution() = }')
270
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[int] , __a : int , __a : int , __a : int , __a : str=0.0 , __a : Optional[int] = None , __a : str = "geglu" , __a : Optional[int] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : str = "layer_norm" , __a : bool = False , ): super().__init__() _a = only_cross_attention _a = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" _a = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f'`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to' f' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _a = AdaLayerNorm(__a , __a ) elif self.use_ada_layer_norm_zero: _a = AdaLayerNormZero(__a , __a ) else: _a = nn.LayerNorm(__a , elementwise_affine=__a ) _a = Attention( query_dim=__a , heads=__a , dim_head=__a , dropout=__a , bias=__a , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__a , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _a = ( AdaLayerNorm(__a , __a ) if self.use_ada_layer_norm else nn.LayerNorm(__a , elementwise_affine=__a ) ) _a = Attention( query_dim=__a , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__a , dim_head=__a , dropout=__a , bias=__a , upcast_attention=__a , ) # is self-attn if encoder_hidden_states is none else: _a = None _a = None # 3. Feed-forward _a = nn.LayerNorm(__a , elementwise_affine=__a ) _a = FeedForward(__a , dropout=__a , activation_fn=__a , final_dropout=__a ) # let chunk size default to None _a = None _a = 0 def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : int ): # Sets chunk feed-forward _a = chunk_size _a = dim def UpperCamelCase__ ( self : List[str] , __a : torch.FloatTensor , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.LongTensor] = None , __a : Dict[str, Any] = None , __a : Optional[torch.LongTensor] = None , ): # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: _a = self.norma(__a , __a ) elif self.use_ada_layer_norm_zero: _a , _a , _a , _a , _a = self.norma( __a , __a , __a , hidden_dtype=hidden_states.dtype ) else: _a = self.norma(__a ) _a = cross_attention_kwargs if cross_attention_kwargs is not None else {} _a = self.attna( __a , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__a , **__a , ) if self.use_ada_layer_norm_zero: _a = gate_msa.unsqueeze(1 ) * attn_output _a = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _a = ( self.norma(__a , __a ) if self.use_ada_layer_norm else self.norma(__a ) ) _a = self.attna( __a , encoder_hidden_states=__a , attention_mask=__a , **__a , ) _a = attn_output + hidden_states # 3. Feed-forward _a = self.norma(__a ) if self.use_ada_layer_norm_zero: _a = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f'`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.' ) _a = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _a = torch.cat( [self.ff(__a ) for hid_slice in norm_hidden_states.chunk(__a , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: _a = self.ff(__a ) if self.use_ada_layer_norm_zero: _a = gate_mlp.unsqueeze(1 ) * ff_output _a = ff_output + hidden_states return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[Any] , __a : int , __a : Optional[int] = None , __a : int = 4 , __a : float = 0.0 , __a : str = "geglu" , __a : bool = False , ): super().__init__() _a = int(dim * mult ) _a = dim_out if dim_out is not None else dim if activation_fn == "gelu": _a = GELU(__a , __a ) if activation_fn == "gelu-approximate": _a = GELU(__a , __a , approximate="tanh" ) elif activation_fn == "geglu": _a = GEGLU(__a , __a ) elif activation_fn == "geglu-approximate": _a = ApproximateGELU(__a , __a ) _a = nn.ModuleList([] ) # project in self.net.append(__a ) # project dropout self.net.append(nn.Dropout(__a ) ) # project out self.net.append(nn.Linear(__a , __a ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(__a ) ) def UpperCamelCase__ ( self : List[Any] , __a : Tuple ): for module in self.net: _a = module(__a ) return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : int , __a : int , __a : str = "none" ): super().__init__() _a = nn.Linear(__a , __a ) _a = approximate def UpperCamelCase__ ( self : Union[str, Any] , __a : List[Any] ): if gate.device.type != "mps": return F.gelu(__a , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def UpperCamelCase__ ( self : str , __a : Optional[int] ): _a = self.proj(__a ) _a = self.gelu(__a ) return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : str , __a : int , __a : int ): super().__init__() _a = nn.Linear(__a , dim_out * 2 ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[int] ): if gate.device.type != "mps": return F.gelu(__a ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def UpperCamelCase__ ( self : List[str] , __a : Any ): _a , _a = self.proj(__a ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(__a ) class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[Any] , __a : int , __a : int ): super().__init__() _a = nn.Linear(__a , __a ) def UpperCamelCase__ ( self : Union[str, Any] , __a : Dict ): _a = self.proj(__a ) return x * torch.sigmoid(1.702 * x ) class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : str , __a : str ): super().__init__() _a = nn.Embedding(__a , __a ) _a = nn.SiLU() _a = nn.Linear(__a , embedding_dim * 2 ) _a = nn.LayerNorm(__a , elementwise_affine=__a ) def UpperCamelCase__ ( self : Tuple , __a : Any , __a : Optional[Any] ): _a = self.linear(self.silu(self.emb(__a ) ) ) _a , _a = torch.chunk(__a , 2 ) _a = self.norm(__a ) * (1 + scale) + shift return x class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[Any] , __a : List[Any] , __a : Any ): super().__init__() _a = CombinedTimestepLabelEmbeddings(__a , __a ) _a = nn.SiLU() _a = nn.Linear(__a , 6 * embedding_dim , bias=__a ) _a = nn.LayerNorm(__a , elementwise_affine=__a , eps=1e-6 ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict , __a : List[Any] , __a : Union[str, Any] , __a : List[Any]=None ): _a = self.linear(self.silu(self.emb(__a , __a , hidden_dtype=__a ) ) ) _a , _a , _a , _a , _a , _a = emb.chunk(6 , dim=1 ) _a = self.norm(__a ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[int] , __a : int , __a : int , __a : int , __a : Optional[str] = None , __a : float = 1e-5 ): super().__init__() _a = num_groups _a = eps if act_fn is None: _a = None else: _a = get_activation(__a ) _a = nn.Linear(__a , out_dim * 2 ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[Any] , __a : List[Any] ): if self.act: _a = self.act(__a ) _a = self.linear(__a ) _a = emb[:, :, None, None] _a , _a = emb.chunk(2 , dim=1 ) _a = F.group_norm(__a , self.num_groups , eps=self.eps ) _a = x * (1 + scale) + shift return x
692
0
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort __lowerCamelCase = '1' __lowerCamelCase = '0' __lowerCamelCase = '1' __lowerCamelCase = ort.SessionOptions() __lowerCamelCase = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('Create inference session...') __lowerCamelCase = ['TensorrtExecutionProvider', 'CUDAExecutionProvider'] __lowerCamelCase = ort.InferenceSession('model.onnx', sess_options=sess_opt, providers=execution_provider) __lowerCamelCase = ort.RunOptions() __lowerCamelCase = 1_28 __lowerCamelCase = 1 __lowerCamelCase = np.ones((batch, sequence), dtype=np.intaa) __lowerCamelCase = np.ones((batch, sequence), dtype=np.intaa) __lowerCamelCase = np.ones((batch, sequence), dtype=np.intaa) print('Warm up phase...') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('Start inference...') __lowerCamelCase = time.time() __lowerCamelCase = 20_00 __lowerCamelCase = {} for iter in range(max_iters): __lowerCamelCase = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('Average Inference Time = {:.3f} ms'.format((time.time() - start_time) * 10_00 / max_iters))
96
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 __a =42 class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : int ): _a = [[] for _ in range(__a )] _a = size def __getitem__( self : int , __a : int ): return iter(self._graph[vertex] ) @property def UpperCamelCase__ ( self : Dict ): return self._size def UpperCamelCase__ ( self : Union[str, Any] , __a : int , __a : int , __a : int ): if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(__a , __a ) ) def UpperCamelCase__ ( self : Tuple , __a : int , __a : int ): _a = deque([start_vertex] ) _a = [None] * self.size _a = 0 while queue: _a = queue.popleft() _a = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _a = current_distance + edge.weight _a = distances[edge.destination_vertex] if ( isinstance(__a , __a ) and new_distance >= dest_vertex_distance ): continue _a = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
692
0
"""simple docstring""" import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def A_ ( lowercase , lowercase ) -> str: """simple docstring""" UpperCAmelCase_ : List[str] = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'''encoder.deit.blocks.{i}.norm1.weight''', f'''encoder.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''encoder.deit.blocks.{i}.norm1.bias''', f'''encoder.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''encoder.deit.blocks.{i}.attn.proj.weight''', f'''encoder.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''encoder.deit.blocks.{i}.attn.proj.bias''', f'''encoder.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append( (f'''encoder.deit.blocks.{i}.norm2.weight''', f'''encoder.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''encoder.deit.blocks.{i}.norm2.bias''', f'''encoder.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''encoder.deit.blocks.{i}.mlp.fc1.weight''', f'''encoder.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append( (f'''encoder.deit.blocks.{i}.mlp.fc1.bias''', f'''encoder.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append( (f'''encoder.deit.blocks.{i}.mlp.fc2.weight''', f'''encoder.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''encoder.deit.blocks.{i}.mlp.fc2.bias''', f'''encoder.encoder.layer.{i}.output.dense.bias''') ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ("""encoder.deit.cls_token""", """encoder.embeddings.cls_token"""), ("""encoder.deit.pos_embed""", """encoder.embeddings.position_embeddings"""), ("""encoder.deit.patch_embed.proj.weight""", """encoder.embeddings.patch_embeddings.projection.weight"""), ("""encoder.deit.patch_embed.proj.bias""", """encoder.embeddings.patch_embeddings.projection.bias"""), ("""encoder.deit.norm.weight""", """encoder.layernorm.weight"""), ("""encoder.deit.norm.bias""", """encoder.layernorm.bias"""), ] ) return rename_keys def A_ ( lowercase , lowercase ) -> Any: """simple docstring""" for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) UpperCAmelCase_ : List[Any] = state_dict.pop(f'''encoder.deit.blocks.{i}.attn.qkv.weight''' ) UpperCAmelCase_ : List[str] = in_proj_weight[ : encoder_config.hidden_size, : ] UpperCAmelCase_ : Optional[int] = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] UpperCAmelCase_ : List[Any] = in_proj_weight[ -encoder_config.hidden_size :, : ] def A_ ( lowercase , lowercase , lowercase ) -> int: """simple docstring""" UpperCAmelCase_ : int = dct.pop(lowercase ) UpperCAmelCase_ : Dict = val def A_ ( lowercase ) -> Any: """simple docstring""" if "handwritten" in checkpoint_url: UpperCAmelCase_ : Any = """https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg""" # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: UpperCAmelCase_ : List[str] = """https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg""" UpperCAmelCase_ : Tuple = Image.open(requests.get(lowercase , stream=lowercase ).raw ).convert("""RGB""" ) return im @torch.no_grad() def A_ ( lowercase , lowercase ) -> Any: """simple docstring""" UpperCAmelCase_ : List[Any] = ViTConfig(image_size=384 , qkv_bias=lowercase ) UpperCAmelCase_ : Optional[int] = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: UpperCAmelCase_ : List[Any] = 768 elif "large" in checkpoint_url: # use ViT-large encoder UpperCAmelCase_ : str = 1024 UpperCAmelCase_ : int = 4096 UpperCAmelCase_ : Union[str, Any] = 24 UpperCAmelCase_ : Optional[int] = 16 UpperCAmelCase_ : int = 1024 else: raise ValueError("""Should either find 'base' or 'large' in checkpoint URL""" ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: UpperCAmelCase_ : Dict = False UpperCAmelCase_ : Dict = """relu""" UpperCAmelCase_ : str = 1024 UpperCAmelCase_ : Dict = True UpperCAmelCase_ : Any = False UpperCAmelCase_ : Optional[int] = False # load HuggingFace model UpperCAmelCase_ : List[Any] = ViTModel(lowercase , add_pooling_layer=lowercase ) UpperCAmelCase_ : Any = TrOCRForCausalLM(lowercase ) UpperCAmelCase_ : Union[str, Any] = VisionEncoderDecoderModel(encoder=lowercase , decoder=lowercase ) model.eval() # load state_dict of original model, rename some keys UpperCAmelCase_ : str = torch.hub.load_state_dict_from_url(lowercase , map_location="""cpu""" , check_hash=lowercase )["""model"""] UpperCAmelCase_ : Union[str, Any] = create_rename_keys(lowercase , lowercase ) for src, dest in rename_keys: rename_key(lowercase , lowercase , lowercase ) read_in_q_k_v(lowercase , lowercase ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): UpperCAmelCase_ : Optional[int] = state_dict.pop(lowercase ) if key.startswith("""decoder""" ) and "output_projection" not in key: UpperCAmelCase_ : Optional[Any] = val else: UpperCAmelCase_ : List[Any] = val # load state dict model.load_state_dict(lowercase ) # Check outputs on an image UpperCAmelCase_ : Optional[int] = ViTImageProcessor(size=encoder_config.image_size ) UpperCAmelCase_ : List[Any] = RobertaTokenizer.from_pretrained("""roberta-large""" ) UpperCAmelCase_ : Union[str, Any] = TrOCRProcessor(lowercase , lowercase ) UpperCAmelCase_ : List[Any] = processor(images=prepare_img(lowercase ) , return_tensors="""pt""" ).pixel_values # verify logits UpperCAmelCase_ : str = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) UpperCAmelCase_ : Tuple = model(pixel_values=lowercase , decoder_input_ids=lowercase ) UpperCAmelCase_ : Tuple = outputs.logits UpperCAmelCase_ : Optional[Any] = torch.Size([1, 1, 5_0265] ) if "trocr-base-handwritten" in checkpoint_url: UpperCAmelCase_ : Union[str, Any] = torch.tensor( [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311] ) elif "trocr-large-handwritten" in checkpoint_url: UpperCAmelCase_ : int = torch.tensor( [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170] ) elif "trocr-base-printed" in checkpoint_url: UpperCAmelCase_ : Any = torch.tensor( [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210] ) elif "trocr-large-printed" in checkpoint_url: UpperCAmelCase_ : Any = torch.tensor( [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10] , lowercase , atol=1E-3 ), "First elements of logits not as expected" Path(lowercase ).mkdir(exist_ok=lowercase ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(lowercase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt", type=str, help="URL to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) lowercase_ = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
470
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =FlaxAutoencoderKL @property def UpperCamelCase__ ( self : str ): _a = 4 _a = 3 _a = (32, 32) _a = jax.random.PRNGKey(0 ) _a = jax.random.uniform(__a , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCamelCase__ ( self : List[Any] ): _a = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } _a = self.dummy_input return init_dict, inputs_dict
692
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A : List[Any] = {'configuration_glpn': ['GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GLPNConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Union[str, Any] = ['GLPNFeatureExtractor'] A : Tuple = ['GLPNImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[Any] = [ 'GLPN_PRETRAINED_MODEL_ARCHIVE_LIST', 'GLPNForDepthEstimation', 'GLPNLayer', 'GLPNModel', 'GLPNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys A : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
287
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration lowerCAmelCase_ : List[Any] = [ # tf -> hf ('/', '.'), ('layer_', 'layers.'), ('kernel', 'weight'), ('beta', 'bias'), ('gamma', 'weight'), ('pegasus', 'model'), ] lowerCAmelCase_ : Optional[int] = [ ('.output.dense', '.fc2'), ('intermediate.LayerNorm', 'final_layer_norm'), ('intermediate.dense', 'fc1'), ] lowerCAmelCase_ : Any = ( INIT_COMMON + [ ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.out_proj'), ('attention.self', 'self_attn'), ('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'), ('attention.encdec_output.dense', 'encoder_attn.out_proj'), ('attention.encdec', 'encoder_attn'), ('key', 'k_proj'), ('value', 'v_proj'), ('query', 'q_proj'), ('decoder.LayerNorm', 'decoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Tuple = ( INIT_COMMON + [ ('embeddings.word_embeddings', 'shared.weight'), ('embeddings.position_embeddings', 'embed_positions.weight'), ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.output'), ('attention.self', 'self_attn.self'), ('encoder.LayerNorm', 'encoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Optional[int] = [ 'encdec/key/bias', 'encdec/query/bias', 'encdec/value/bias', 'self/key/bias', 'self/query/bias', 'self/value/bias', 'encdec_output/dense/bias', 'attention/output/dense/bias', ] def _lowerCamelCase ( lowercase : Any , lowercase : Any ) -> Optional[Any]: for tf_name, hf_name in patterns: _a = k.replace(lowercase , lowercase ) return k def _lowerCamelCase ( lowercase : dict , lowercase : dict ) -> BigBirdPegasusForConditionalGeneration: _a = BigBirdPegasusConfig(**lowercase ) _a = BigBirdPegasusForConditionalGeneration(lowercase ) _a = torch_model.state_dict() _a = {} # separating decoder weights _a = {k: tf_weights[k] for k in tf_weights if k.startswith("pegasus/decoder" )} _a = {k: tf_weights[k] for k in tf_weights if not k.startswith("pegasus/decoder" )} for k, v in tqdm(decoder_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = DECODER_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict: raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' for k, v in tqdm(remaining_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = REMAINING_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' _a = mapping["model.embed_positions.weight"] _a = mapping.pop("model.embed_positions.weight" ) _a , _a = torch_model.load_state_dict(lowercase , strict=lowercase ) _a = [ k for k in missing if k not in [ "final_logits_bias", "model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight", ] ] assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}' assert extra == [], F'no matches found for the following tf keys {extra}' return torch_model def _lowerCamelCase ( lowercase : List[Any] ) -> Dict: _a = tf.train.list_variables(lowercase ) _a = {} _a = ["global_step"] for name, shape in tqdm(lowercase , desc="converting tf checkpoint to dict" ): _a = any(pat in name for pat in ignore_name ) if skip_key: continue _a = tf.train.load_variable(lowercase , lowercase ) _a = array return tf_weights def _lowerCamelCase ( lowercase : str , lowercase : str , lowercase : dict ) -> Union[str, Any]: _a = get_tf_weights_as_numpy(lowercase ) _a = convert_bigbird_pegasus(lowercase , lowercase ) torch_model.save_pretrained(lowercase ) if __name__ == "__main__": lowerCAmelCase_ : str = argparse.ArgumentParser() parser.add_argument('--tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('--save_dir', default=None, type=str, help='Path to the output PyTorch model.') lowerCAmelCase_ : Optional[Any] = parser.parse_args() lowerCAmelCase_ : Optional[Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
0
"""simple docstring""" from math import factorial lowercase__ : str = {str(d): factorial(d) for d in range(10)} def __lowercase ( _a ): return sum(DIGIT_FACTORIAL[d] for d in str(_a ) ) def __lowercase ( ): snake_case_ : Dict = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , _a ) if sum_of_digit_factorial(_a ) == i ) if __name__ == "__main__": print(f'{solution() = }')
123
'''simple docstring''' def _lowerCamelCase ( lowercase : str , lowercase : list[str] ) -> str: _a = "" for word_or_phrase in separated: if not isinstance(lowercase , lowercase ): raise Exception("join() accepts only strings to be joined" ) joined += word_or_phrase + separator return joined.strip(lowercase ) if __name__ == "__main__": from doctest import testmod testmod()
692
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( lowerCamelCase_ ): '''simple docstring''' @staticmethod @abstractmethod def _snake_case ( snake_case__ : ArgumentParser ) -> List[str]: raise NotImplementedError() @abstractmethod def _snake_case ( self : Optional[int] ) -> Any: raise NotImplementedError()
544
'''simple docstring''' lowerCAmelCase_ : Optional[Any] = '\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' lowerCAmelCase_ : List[Any] = [{'type': 'code', 'content': INSTALL_CONTENT}] lowerCAmelCase_ : Dict = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
692
0
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() A : List[str] = logging.get_logger() @dataclass class UpperCamelCase: snake_case_ : List[str] = 42 snake_case_ : Tuple = field(default_factory=lowerCamelCase_ ) snake_case_ : Any = field(default_factory=lowerCamelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Tensor , SCREAMING_SNAKE_CASE : Tensor ) -> str: '''simple docstring''' __snake_case = len(list(m.modules() ) ) == 1 or isinstance(__a , nn.Convad ) or isinstance(__a , nn.BatchNormad ) if has_not_submodules: self.traced.append(__a ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE : Tensor ) -> Any: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(__a ) [x.remove() for x in self.handles] return self @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return list(filter(lambda SCREAMING_SNAKE_CASE : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCamelCase: snake_case_ : Optional[int] = 42 snake_case_ : Optional[Any] = 42 snake_case_ : Any = 1 snake_case_ : str = field(default_factory=lowerCamelCase_ ) snake_case_ : Any = field(default_factory=lowerCamelCase_ ) snake_case_ : Tuple = True def __call__( self : Any , SCREAMING_SNAKE_CASE : Tensor ) -> Optional[int]: '''simple docstring''' __snake_case = Tracker(self.dest )(__a ).parametrized __snake_case = Tracker(self.src )(__a ).parametrized __snake_case = list(filter(lambda SCREAMING_SNAKE_CASE : type(__a ) not in self.src_skip , __a ) ) __snake_case = list(filter(lambda SCREAMING_SNAKE_CASE : type(__a ) not in self.dest_skip , __a ) ) if len(__a ) != len(__a ) and self.raise_if_mismatch: raise Exception( f'''Numbers of operations are different. Source module has {len(__a )} operations while''' f''' destination module has {len(__a )}.''' ) for dest_m, src_m in zip(__a , __a ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'''Transfered from={src_m} to={dest_m}''' ) class UpperCamelCase( nn.Module ): def __init__( self : int , SCREAMING_SNAKE_CASE : nn.Module ) -> Dict: '''simple docstring''' super().__init__() __snake_case = [] # - get the stem feature_blocks.append(("conv1", model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith("block" ), f'''Unexpected layer name {k}''' __snake_case = len(__a ) + 1 feature_blocks.append((f'''res{block_index}''', v) ) __snake_case = nn.ModuleDict(__a ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE : Tensor ) -> Union[str, Any]: '''simple docstring''' return get_trunk_forward_outputs( __a , out_feat_keys=__a , feature_blocks=self._feature_blocks , ) class UpperCamelCase( lowerCamelCase_ ): def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE : str ) -> Any: '''simple docstring''' __snake_case = x.split("-" ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE : str ) -> Optional[int]: '''simple docstring''' if x not in self: __snake_case = self.convert_name_to_timm(__a ) __snake_case = partial(lambda: (timm.create_model(__a , pretrained=__a ).eval(), None) ) else: __snake_case = super().__getitem__(__a ) return val class UpperCamelCase( lowerCamelCase_ ): def __getitem__( self : Dict , SCREAMING_SNAKE_CASE : str ) -> str: '''simple docstring''' if "seer" in x and "in1k" not in x: __snake_case = RegNetModel else: __snake_case = RegNetForImageClassification return val def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: '''simple docstring''' for from_key, to_key in keys: __snake_case = from_state_dict[from_key].clone() print(F'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = True , ) -> int: '''simple docstring''' print(F'''Converting {name}...''' ) with torch.no_grad(): __snake_case , __snake_case = from_model_func() __snake_case = our_model_func(_lowerCAmelCase ).eval() __snake_case = ModuleTransfer(src=_lowerCAmelCase , dest=_lowerCAmelCase , raise_if_mismatch=_lowerCAmelCase ) __snake_case = torch.randn((1, 3, 224, 224) ) module_transfer(_lowerCAmelCase ) if from_state_dict is not None: __snake_case = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: __snake_case = [("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")] __snake_case = manually_copy_vissl_head(_lowerCAmelCase , our_model.state_dict() , _lowerCAmelCase ) our_model.load_state_dict(_lowerCAmelCase ) __snake_case = our_model(_lowerCAmelCase , output_hidden_states=_lowerCAmelCase ) __snake_case = ( our_outputs.logits if isinstance(_lowerCAmelCase , _lowerCAmelCase ) else our_outputs.last_hidden_state ) __snake_case = from_model(_lowerCAmelCase ) __snake_case = from_output[-1] if type(_lowerCAmelCase ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: __snake_case = our_outputs.hidden_states[-1] assert torch.allclose(_lowerCAmelCase , _lowerCAmelCase ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message="Add model" , use_temp_dir=_lowerCAmelCase , ) __snake_case = 224 if "seer" not in name else 384 # we can use the convnext one __snake_case = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" , size=_lowerCAmelCase ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message="Add image processor" , use_temp_dir=_lowerCAmelCase , ) print(F'''Pushed {name}''' ) def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = True ) -> Optional[Any]: '''simple docstring''' __snake_case = "imagenet-1k-id2label.json" __snake_case = 1000 __snake_case = (1, num_labels) __snake_case = "huggingface/label-files" __snake_case = num_labels __snake_case = json.load(open(cached_download(hf_hub_url(_lowerCAmelCase , _lowerCAmelCase , repo_type="dataset" ) ) , "r" ) ) __snake_case = {int(_lowerCAmelCase ): v for k, v in idalabel.items()} __snake_case = idalabel __snake_case = {v: k for k, v in idalabel.items()} __snake_case = partial(_lowerCAmelCase , num_labels=_lowerCAmelCase , idalabel=_lowerCAmelCase , labelaid=_lowerCAmelCase ) __snake_case = { "regnet-x-002": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type="x" ), "regnet-x-004": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type="x" ), "regnet-x-006": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type="x" ), "regnet-x-008": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type="x" ), "regnet-x-016": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type="x" ), "regnet-x-032": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type="x" ), "regnet-x-040": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type="x" ), "regnet-x-064": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type="x" ), "regnet-x-080": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type="x" ), "regnet-x-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type="x" ), "regnet-x-160": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type="x" ), "regnet-x-320": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type="x" ), # y variant "regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), "regnet-y-004": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), "regnet-y-006": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), "regnet-y-008": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), "regnet-y-016": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), "regnet-y-032": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24 ), "regnet-y-040": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64 ), "regnet-y-064": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72 ), "regnet-y-080": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56 ), "regnet-y-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 ), "regnet-y-160": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112 ), "regnet-y-320": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 "regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), "regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), "regnet-y-1280-seer": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), "regnet-y-2560-seer": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), "regnet-y-10b-seer": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), # finetuned on imagenet "regnet-y-320-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), "regnet-y-640-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), "regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), "regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), "regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), } __snake_case = NameToOurModelFuncMap() __snake_case = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(_lowerCAmelCase , _lowerCAmelCase ) -> Tuple[nn.Module, Dict]: __snake_case = torch.hub.load_state_dict_from_url(_lowerCAmelCase , model_dir=str(_lowerCAmelCase ) , map_location="cpu" ) __snake_case = model_func() # check if we have a head, if yes add it __snake_case = files["classy_state_dict"]["base_model"]["model"] __snake_case = model_state_dict["trunk"] model.load_state_dict(_lowerCAmelCase ) return model.eval(), model_state_dict["heads"] # pretrained __snake_case = partial( _lowerCAmelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) __snake_case = partial( _lowerCAmelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) __snake_case = partial( _lowerCAmelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) __snake_case = partial( _lowerCAmelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned __snake_case = partial( _lowerCAmelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) __snake_case = partial( _lowerCAmelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) __snake_case = partial( _lowerCAmelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) __snake_case = partial( _lowerCAmelCase , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( _lowerCAmelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , _lowerCAmelCase , _lowerCAmelCase , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( _lowerCAmelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , ) return config, expected_shape if __name__ == "__main__": A : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported regnet* architecture,' ' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) A : str = parser.parse_args() A : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
371
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') lowerCAmelCase_ : Optional[Any] = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) lowerCAmelCase_ : Dict = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) lowerCAmelCase_ : Dict = BeautifulSoup(res.text, 'html.parser') lowerCAmelCase_ : Optional[int] = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f"""https://google.com{link.get('href')}""")
692
0
def A__( __lowerCAmelCase = 10**9 ): _snake_case : Optional[int] = 1 _snake_case : Optional[int] = 2 _snake_case : int = 0 _snake_case : List[Any] = 0 _snake_case : int = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value _snake_case : Optional[Any] = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(F'''{solution() = }''')
304
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets lowerCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) lowerCAmelCase_ : Tuple = '\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n author = "Moosavi, Nafise Sadat and\n Strube, Michael",\n booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/P16-1060",\n doi = "10.18653/v1/P16-1060",\n pages = "632--642",\n}\n\n' lowerCAmelCase_ : Union[str, Any] = '\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n' lowerCAmelCase_ : Union[str, Any] = '\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting \'keep_singletons=False\', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n \'mentions\': mentions\n \'muc\': MUC metric [Vilain et al, 1995]\n \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n \'ceafe\': CEAFe [Luo et al., 2005]\n \'lea\': LEA [Moosavi and Strube, 2016]\n \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric(\'coval\')\n >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\',\n ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\',\n ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\',\n ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\',\n ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\',\n ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n' def _lowerCamelCase ( lowercase : Tuple , lowercase : List[Any] , lowercase : Optional[int]=False , lowercase : Dict=False , lowercase : Optional[int]=True , lowercase : Union[str, Any]=False , lowercase : int="dummy_doc" ) -> Union[str, Any]: _a = {doc: key_lines} _a = {doc: sys_lines} _a = {} _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a , _a = reader.get_doc_mentions(lowercase , key_doc_lines[doc] , lowercase ) key_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) _a , _a = reader.get_doc_mentions(lowercase , sys_doc_lines[doc] , lowercase ) sys_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) if remove_nested: _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters _a = reader.get_mention_assignments(lowercase , lowercase ) _a = reader.get_mention_assignments(lowercase , lowercase ) _a = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( "Number of removed nested coreferring mentions in the key " F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( "Number of resulting singleton clusters in the key " F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' "files, respectively" ) return doc_coref_infos def _lowerCamelCase ( lowercase : List[Any] , lowercase : Any , lowercase : Optional[Any] , lowercase : Union[str, Any] , lowercase : Any , lowercase : List[str] , lowercase : Dict ) -> str: _a = get_coref_infos(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) _a = {} _a = 0 _a = 0 for name, metric in metrics: _a , _a , _a = evaluator.evaluate_documents(lowercase , lowercase , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} ) logger.info( name.ljust(10 ) , F'Recall: {recall * 100:.2f}' , F' Precision: {precision * 100:.2f}' , F' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: _a = (conll / 3) * 100 logger.info(F'CoNLL score: {conll:.2f}' ) output_scores.update({"conll_score": conll} ) return output_scores def _lowerCamelCase ( lowercase : Any ) -> str: _a = False for line in key_lines: if not line.startswith("#" ): if len(line.split() ) > 6: _a = line.split()[5] if not parse_col == "-": _a = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE (datasets.Metric ): """simple docstring""" def UpperCamelCase__ ( self : str ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Sequence(datasets.Value("string" ) ), } ) , codebase_urls=["https://github.com/ns-moosavi/coval"] , reference_urls=[ "https://github.com/ns-moosavi/coval", "https://www.aclweb.org/anthology/P16-1060", "http://www.conll.cemantix.org/2012/data.html", ] , ) def UpperCamelCase__ ( self : int , __a : Any , __a : int , __a : Optional[Any]=True , __a : Optional[Any]=False , __a : str=False , __a : List[str]=False ): _a = [ ("mentions", evaluator.mentions), ("muc", evaluator.muc), ("bcub", evaluator.b_cubed), ("ceafe", evaluator.ceafe), ("lea", evaluator.lea), ] if min_span: _a = util.check_gold_parse_annotation(__a ) if not has_gold_parse: raise NotImplementedError("References should have gold parse annotation to use 'min_span'." ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" _a = evaluate( key_lines=__a , sys_lines=__a , metrics=__a , NP_only=__a , remove_nested=__a , keep_singletons=__a , min_span=__a , ) return score
692
0
import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=13 , _lowerCAmelCase=7 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=99 , _lowerCAmelCase=64 , _lowerCAmelCase=5 , _lowerCAmelCase=4 , _lowerCAmelCase=37 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=16 , _lowerCAmelCase=2 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=3 , _lowerCAmelCase=4 , _lowerCAmelCase=None , ): UpperCAmelCase__ : Any = parent UpperCAmelCase__ : List[Any] = batch_size UpperCAmelCase__ : str = seq_length UpperCAmelCase__ : int = is_training UpperCAmelCase__ : Optional[Any] = use_input_mask UpperCAmelCase__ : Union[str, Any] = use_token_type_ids UpperCAmelCase__ : Dict = use_labels UpperCAmelCase__ : Tuple = vocab_size UpperCAmelCase__ : Optional[int] = hidden_size UpperCAmelCase__ : Tuple = num_hidden_layers UpperCAmelCase__ : Tuple = num_attention_heads UpperCAmelCase__ : List[Any] = intermediate_size UpperCAmelCase__ : List[str] = hidden_act UpperCAmelCase__ : List[Any] = hidden_dropout_prob UpperCAmelCase__ : Optional[int] = attention_probs_dropout_prob UpperCAmelCase__ : Dict = max_position_embeddings UpperCAmelCase__ : Tuple = type_vocab_size UpperCAmelCase__ : List[Any] = type_sequence_label_size UpperCAmelCase__ : Optional[Any] = initializer_range UpperCAmelCase__ : Optional[Any] = num_labels UpperCAmelCase__ : List[str] = num_choices UpperCAmelCase__ : Optional[Any] = scope UpperCAmelCase__ : Optional[int] = vocab_size - 1 def __UpperCAmelCase ( self ): UpperCAmelCase__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase__ : Optional[int] = None if self.use_input_mask: UpperCAmelCase__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase__ : str = None if self.use_labels: UpperCAmelCase__ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase__ : int = self.get_config() return config, input_ids, input_mask, token_labels def __UpperCAmelCase ( self ): return GPTNeoXConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__a , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = self.prepare_config_and_inputs() UpperCAmelCase__ : List[str] = True return config, input_ids, input_mask, token_labels def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : str = GPTNeoXModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase__ : List[Any] = model(__a , attention_mask=__a ) UpperCAmelCase__ : List[Any] = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Optional[Any] = True UpperCAmelCase__ : Union[str, Any] = GPTNeoXModel(__a ) model.to(__a ) model.eval() UpperCAmelCase__ : List[str] = model(__a , attention_mask=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Optional[int] = GPTNeoXForCausalLM(config=__a ) model.to(__a ) model.eval() UpperCAmelCase__ : Union[str, Any] = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Optional[int] = self.num_labels UpperCAmelCase__ : int = GPTNeoXForQuestionAnswering(__a ) model.to(__a ) model.eval() UpperCAmelCase__ : int = model(__a , attention_mask=__a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Dict = self.num_labels UpperCAmelCase__ : str = GPTNeoXForSequenceClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ : str = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Dict = self.num_labels UpperCAmelCase__ : Union[str, Any] = GPTNeoXForTokenClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase__ : Dict = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : int = True UpperCAmelCase__ : Any = GPTNeoXForCausalLM(config=__a ) model.to(__a ) model.eval() # first forward pass UpperCAmelCase__ : Tuple = model(__a , attention_mask=__a , use_cache=__a ) UpperCAmelCase__ : List[str] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase__ : str = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase__ : Optional[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and UpperCAmelCase__ : List[str] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase__ : Tuple = torch.cat([input_mask, next_mask] , dim=-1 ) UpperCAmelCase__ : Optional[int] = model(__a , attention_mask=__a , output_hidden_states=__a ) UpperCAmelCase__ : Tuple = output_from_no_past["""hidden_states"""][0] UpperCAmelCase__ : Dict = model( __a , attention_mask=__a , past_key_values=__a , output_hidden_states=__a , )["""hidden_states"""][0] # select random slice UpperCAmelCase__ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase__ : int = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase__ : Optional[int] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__a , __a , atol=1e-3 ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Tuple = config_and_inputs UpperCAmelCase__ : str = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): __lowerCamelCase = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) __lowerCamelCase = (GPTNeoXForCausalLM,) if is_torch_available() else () __lowerCamelCase = ( { 'feature-extraction': GPTNeoXModel, 'question-answering': GPTNeoXForQuestionAnswering, 'text-classification': GPTNeoXForSequenceClassification, 'text-generation': GPTNeoXForCausalLM, 'token-classification': GPTNeoXForTokenClassification, 'zero-shot': GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = GPTNeoXModelTester(self ) UpperCAmelCase__ : Tuple = ConfigTester(self , config_class=__a , hidden_size=64 , num_attention_heads=8 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__a , __a , __a ) def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(__a , __a , __a ) def __UpperCAmelCase ( self ): # This regression test was failing with PyTorch < 1.3 UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_decoder() UpperCAmelCase__ : List[str] = None self.model_tester.create_and_check_model_as_decoder(__a , __a , __a ) def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(__a , __a , __a ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*__a ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__a ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__a ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__a ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def __UpperCAmelCase ( self ): pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : str = ids_tensor([1, 10] , config.vocab_size ) UpperCAmelCase__ : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights UpperCAmelCase__ : List[Any] = GPTNeoXModel(__a ) original_model.to(__a ) original_model.eval() UpperCAmelCase__ : Tuple = original_model(__a ).last_hidden_state UpperCAmelCase__ : List[Any] = original_model(__a ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights UpperCAmelCase__ : Union[str, Any] = {"""type""": scaling_type, """factor""": 1_0.0} UpperCAmelCase__ : Union[str, Any] = GPTNeoXModel(__a ) scaled_model.to(__a ) scaled_model.eval() UpperCAmelCase__ : Tuple = scaled_model(__a ).last_hidden_state UpperCAmelCase__ : str = scaled_model(__a ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__a , __a , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(__a , __a , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__a , __a , atol=1e-5 ) ) @require_torch class UpperCAmelCase_ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: UpperCAmelCase__ : str = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(__a ) UpperCAmelCase__ : str = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(__a ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 UpperCAmelCase__ : Optional[Any] = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" UpperCAmelCase__ : Dict = model.generate(**__a , do_sample=__a , max_new_tokens=20 ) UpperCAmelCase__ : Optional[int] = tokenizer.batch_decode(__a )[0] self.assertEqual(__a , __a )
79
'''simple docstring''' import math def _lowerCamelCase ( lowercase : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowercase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCamelCase ( lowercase : float = 0.1 ) -> int: _a = 3 _a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowercase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
0
"""simple docstring""" import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration __A = 50_0000 __A = os.path.split(__file__) __A = os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json""")) @get_duration def __A (_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :Dict = dataset.map(**_SCREAMING_SNAKE_CASE ) @get_duration def __A (_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) ->List[str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = dataset.filter(**_SCREAMING_SNAKE_CASE ) def __A () ->int: """simple docstring""" lowerCAmelCase__ :Optional[int] = {'num examples': SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ :Optional[Any] = datasets.Features({'text': datasets.Value('string' ), 'numbers': datasets.Value('float32' )} ) lowerCAmelCase__ :str = generate_example_dataset( os.path.join(_SCREAMING_SNAKE_CASE , 'dataset.arrow' ) , _SCREAMING_SNAKE_CASE , num_examples=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :int = transformers.AutoTokenizer.from_pretrained('bert-base-cased' , use_fast=_SCREAMING_SNAKE_CASE ) def tokenize(_SCREAMING_SNAKE_CASE ): return tokenizer(examples['text'] ) lowerCAmelCase__ :List[Any] = map(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Optional[Any] = map(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :int = map(_SCREAMING_SNAKE_CASE , function=lambda _SCREAMING_SNAKE_CASE : None , batched=_SCREAMING_SNAKE_CASE ) with dataset.formatted_as(type='numpy' ): lowerCAmelCase__ :List[Any] = map(_SCREAMING_SNAKE_CASE , function=lambda _SCREAMING_SNAKE_CASE : None , batched=_SCREAMING_SNAKE_CASE ) with dataset.formatted_as(type='pandas' ): lowerCAmelCase__ :List[Any] = map(_SCREAMING_SNAKE_CASE , function=lambda _SCREAMING_SNAKE_CASE : None , batched=_SCREAMING_SNAKE_CASE ) with dataset.formatted_as(type='torch' , columns='numbers' ): lowerCAmelCase__ :List[Any] = map(_SCREAMING_SNAKE_CASE , function=lambda _SCREAMING_SNAKE_CASE : None , batched=_SCREAMING_SNAKE_CASE ) with dataset.formatted_as(type='tensorflow' , columns='numbers' ): lowerCAmelCase__ :Tuple = map(_SCREAMING_SNAKE_CASE , function=lambda _SCREAMING_SNAKE_CASE : None , batched=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = map(_SCREAMING_SNAKE_CASE , function=_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :str = filter(_SCREAMING_SNAKE_CASE ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(json.dumps(_SCREAMING_SNAKE_CASE ).encode('utf-8' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
93
'''simple docstring''' import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(CMStochasticIterativeScheduler,) __a =10 def UpperCamelCase__ ( self : Union[str, Any] , **__a : str ): _a = { "num_train_timesteps": 2_01, "sigma_min": 0.002, "sigma_max": 80.0, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[Any] ): _a = 10 _a = self.get_scheduler_config() _a = self.scheduler_classes[0](**__a ) scheduler.set_timesteps(__a ) _a = scheduler.timesteps[0] _a = scheduler.timesteps[1] _a = self.dummy_sample _a = 0.1 * sample _a = scheduler.step(__a , __a , __a ).prev_sample _a = scheduler.step(__a , __a , __a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase__ ( self : Any ): for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : int ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = 1 scheduler.set_timesteps(__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(__a ): # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [1_06, 0] scheduler.set_timesteps(timesteps=__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCamelCase__ ( self : List[Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 15, 0] with self.assertRaises(__a , msg="`timesteps` must be in descending order." ): scheduler.set_timesteps(timesteps=__a ) def UpperCamelCase__ ( self : Tuple ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 1, 0] _a = len(__a ) with self.assertRaises(__a , msg="Can only pass one of `num_inference_steps` or `timesteps`." ): scheduler.set_timesteps(num_inference_steps=__a , timesteps=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [scheduler.config.num_train_timesteps] with self.assertRaises( __a , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=__a )
692
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowerCAmelCase__ = logging.get_logger(__name__) class __snake_case ( lowerCamelCase_): def __init__( self : Optional[Any] , *__lowerCAmelCase : Dict , **__lowerCAmelCase : List[Any] ): """simple docstring""" warnings.warn( '''The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use ChineseCLIPImageProcessor instead.''' , __a , ) super().__init__(*__a , **__a )
83
'''simple docstring''' import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : int , **__a : Optional[Any] ): warnings.warn( "The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use YolosImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' import numpy # List of input, output pairs A_ = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) A_ = (((515, 22, 13), 555), ((61, 35, 49), 150)) A_ = [2, 4, 1, 5] A_ = len(train_data) A_ = 0.0_09 def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="train" ) -> Optional[Any]: return calculate_hypothesis_value(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) - output( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ) -> str: snake_case__ : Optional[int] = 0 for i in range(len(__SCREAMING_SNAKE_CASE ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Tuple: if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[int]: if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=m ) -> int: snake_case__ : Union[str, Any] = 0 for i in range(__SCREAMING_SNAKE_CASE ): if index == -1: summation_value += _error(__SCREAMING_SNAKE_CASE ) else: summation_value += _error(__SCREAMING_SNAKE_CASE ) * train_data[i][0][index] return summation_value def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case__ : Union[str, Any] = summation_of_cost_derivative(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) / m return cost_derivative_value def UpperCamelCase__ ( ) -> List[Any]: global parameter_vector # Tune these values to set a tolerance value for predicted output snake_case__ : Any = 0.000002 snake_case__ : int = 0 snake_case__ : Union[str, Any] = 0 while True: j += 1 snake_case__ : Optional[int] = [0, 0, 0, 0] for i in range(0 , len(__SCREAMING_SNAKE_CASE ) ): snake_case__ : Any = get_cost_derivative(i - 1 ) snake_case__ : int = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=__SCREAMING_SNAKE_CASE , rtol=__SCREAMING_SNAKE_CASE , ): break snake_case__ : int = temp_parameter_vector print(('Number of iterations:', j) ) def UpperCamelCase__ ( ) -> Union[str, Any]: for i in range(len(__SCREAMING_SNAKE_CASE ) ): print(('Actual output value:', output(__SCREAMING_SNAKE_CASE , 'test' )) ) print(('Hypothesis output:', calculate_hypothesis_value(__SCREAMING_SNAKE_CASE , 'test' )) ) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
270
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) lowerCAmelCase_ : str = { 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='timesformer' def __init__( self : Optional[int] , __a : Optional[int]=2_24 , __a : Tuple=16 , __a : int=3 , __a : Union[str, Any]=8 , __a : Union[str, Any]=7_68 , __a : List[str]=12 , __a : Union[str, Any]=12 , __a : Optional[Any]=30_72 , __a : Tuple="gelu" , __a : str=0.0 , __a : List[Any]=0.0 , __a : Any=0.02 , __a : List[str]=1e-6 , __a : Any=True , __a : Union[str, Any]="divided_space_time" , __a : str=0 , **__a : Tuple , ): super().__init__(**__a ) _a = image_size _a = patch_size _a = num_channels _a = num_frames _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = initializer_range _a = layer_norm_eps _a = qkv_bias _a = attention_type _a = drop_path_rate
692
0
"""simple docstring""" class __A : def __init__( self : Tuple ) -> Optional[Any]: __magic_name__: Tuple = {} # Mapping from char to TrieNode __magic_name__: Optional[Any] = False def lowerCamelCase__ ( self : Tuple , __snake_case : list[str] ) -> List[Any]: for word in words: self.insert(__a ) def lowerCamelCase__ ( self : Optional[Any] , __snake_case : str ) -> Union[str, Any]: __magic_name__: List[Any] = self for char in word: if char not in curr.nodes: __magic_name__: str = TrieNode() __magic_name__: int = curr.nodes[char] __magic_name__: int = True def lowerCamelCase__ ( self : str , __snake_case : str ) -> List[str]: __magic_name__: List[str] = self for char in word: if char not in curr.nodes: return False __magic_name__: str = curr.nodes[char] return curr.is_leaf def lowerCamelCase__ ( self : Optional[Any] , __snake_case : str ) -> Any: def _delete(__snake_case : TrieNode , __snake_case : str , __snake_case : int ) -> bool: if index == len(__a ): # If word does not exist if not curr.is_leaf: return False __magic_name__: str = False return len(curr.nodes ) == 0 __magic_name__: List[Any] = word[index] __magic_name__: Tuple = curr.nodes.get(__a ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted __magic_name__: Optional[int] = _delete(__a , __a , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , __a , 0 ) def a ( __UpperCAmelCase : TrieNode , __UpperCAmelCase : str ) -> None: if node.is_leaf: print(__UpperCAmelCase , end=""" """ ) for key, value in node.nodes.items(): print_words(__UpperCAmelCase , word + key ) def a ( ) -> bool: __magic_name__: Tuple = """banana bananas bandana band apple all beast""".split() __magic_name__: List[str] = TrieNode() root.insert_many(__UpperCAmelCase ) # print_words(root, "") assert all(root.find(__UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def a ( __UpperCAmelCase : str , __UpperCAmelCase : bool ) -> None: print(str(__UpperCAmelCase ) , """works!""" if passes else """doesn't work :(""" ) def a ( ) -> None: assert test_trie() def a ( ) -> None: print_results("""Testing trie functionality""" , test_trie() ) if __name__ == "__main__": main()
96
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase__ ( self : Dict ): _a = 1 _a = 3 _a = (32, 32) _a = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__a ) return image @property def UpperCamelCase__ ( self : Dict ): torch.manual_seed(0 ) _a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def UpperCamelCase__ ( self : Optional[int] ): torch.manual_seed(0 ) _a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def UpperCamelCase__ ( self : Optional[Any] ): torch.manual_seed(0 ) _a = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=50_06 , ) return RobertaSeriesModelWithTransformation(__a ) @property def UpperCamelCase__ ( self : str ): def extract(*__a : Tuple , **__a : str ): class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict ): _a = torch.ones([0] ) def UpperCamelCase__ ( self : List[str] , __a : Dict ): self.pixel_values.to(__a ) return self return Out() return extract def UpperCamelCase__ ( self : Optional[int] ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) _a = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , ) _a = output.images _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , return_dict=__a , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) # put models in fp16 _a = unet.half() _a = vae.half() _a = bert.half() # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , num_inference_steps=2 , output_type="np" , image=__a , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 _a = init_image.resize((7_60, 5_04) ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] _a = image[2_55:2_58, 3_83:3_86, -1] assert image.shape == (5_04, 7_60, 3) _a = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : Union[str, Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) _a = init_image.resize((7_68, 5_12) ) _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] assert image.shape == (5_12, 7_68, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
692
0
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase_ : """simple docstring""" def __init__( self : List[Any] , a_ : List[Any] , a_ : List[Any]=13 , a_ : Optional[Any]=7 , a_ : str=True , a_ : Optional[Any]=True , a_ : List[str]=False , a_ : Optional[int]=True , a_ : str=99 , a_ : int=32 , a_ : int=5 , a_ : Optional[int]=4 , a_ : List[Any]=37 , a_ : Dict="gelu" , a_ : List[Any]=0.1 , a_ : Optional[int]=0.1 , a_ : Optional[Any]=5_12 , a_ : int=16 , a_ : str=2 , a_ : Union[str, Any]=0.02 , a_ : List[str]=3 , a_ : Tuple=4 , a_ : Tuple=None , )-> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[str] = parent UpperCAmelCase_ : str = batch_size UpperCAmelCase_ : Optional[Any] = seq_length UpperCAmelCase_ : Union[str, Any] = is_training UpperCAmelCase_ : int = use_input_mask UpperCAmelCase_ : Union[str, Any] = use_token_type_ids UpperCAmelCase_ : Optional[Any] = use_labels UpperCAmelCase_ : List[str] = vocab_size UpperCAmelCase_ : Tuple = hidden_size UpperCAmelCase_ : int = num_hidden_layers UpperCAmelCase_ : List[str] = num_attention_heads UpperCAmelCase_ : List[Any] = intermediate_size UpperCAmelCase_ : Dict = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : Optional[int] = attention_probs_dropout_prob UpperCAmelCase_ : Optional[Any] = max_position_embeddings UpperCAmelCase_ : str = type_vocab_size UpperCAmelCase_ : Tuple = type_sequence_label_size UpperCAmelCase_ : List[Any] = initializer_range UpperCAmelCase_ : Any = num_labels UpperCAmelCase_ : Optional[int] = num_choices UpperCAmelCase_ : Union[str, Any] = scope def a ( self : Union[str, Any] )-> Any: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Union[str, Any] = None if self.use_input_mask: UpperCAmelCase_ : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : int = None if self.use_token_type_ids: UpperCAmelCase_ : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Dict = None UpperCAmelCase_ : int = None UpperCAmelCase_ : int = None if self.use_labels: UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : Any = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a ( self : Tuple )-> Optional[int]: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__a , initializer_range=self.initializer_range , ) def a ( self : Union[str, Any] , a_ : Dict , a_ : Any , a_ : Any , a_ : int , a_ : Tuple , a_ : List[Any] , a_ : Tuple )-> Dict: """simple docstring""" UpperCAmelCase_ : Tuple = BioGptModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ : Optional[int] = model(__a , attention_mask=__a ) UpperCAmelCase_ : Union[str, Any] = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Dict , a_ : Dict , a_ : Union[str, Any] , a_ : str , a_ : List[Any] , a_ : Union[str, Any] , a_ : List[str] , a_ : List[Any] , a_ : Union[str, Any] , a_ : str , )-> Dict: """simple docstring""" UpperCAmelCase_ : List[str] = BioGptForCausalLM(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ : str = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a ( self : Union[str, Any] , a_ : Dict , a_ : List[str] , a_ : Any , a_ : Dict , a_ : Optional[int] , *a_ : Union[str, Any] )-> Dict: """simple docstring""" UpperCAmelCase_ : str = BioGptModel(config=__a ) model.to(__a ) model.eval() # create attention mask UpperCAmelCase_ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=__a ) UpperCAmelCase_ : List[Any] = self.seq_length // 2 UpperCAmelCase_ : Any = 0 # first forward pass UpperCAmelCase_ ,UpperCAmelCase_ : Union[str, Any] = model(__a , attention_mask=__a ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase_ : int = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCAmelCase_ : List[Any] = ids_tensor((1,) , __a ).item() + 1 UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCAmelCase_ : List[Any] = random_other_next_tokens # append to next input_ids and attn_mask UpperCAmelCase_ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=__a )] , dim=1 , ) # get two different outputs UpperCAmelCase_ : Optional[int] = model(__a , attention_mask=__a )["""last_hidden_state"""] UpperCAmelCase_ : Optional[int] = model(__a , past_key_values=__a , attention_mask=__a )["""last_hidden_state"""] # select random slice UpperCAmelCase_ : Dict = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : int = output_from_no_past[:, -1, random_slice_idx].detach() UpperCAmelCase_ : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__a , __a , atol=1E-3 ) ) def a ( self : Optional[int] , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : List[str] , a_ : Union[str, Any] , *a_ : Dict )-> int: """simple docstring""" UpperCAmelCase_ : List[Any] = BioGptModel(config=__a ).to(__a ).eval() UpperCAmelCase_ : str = torch.ones(input_ids.shape , dtype=torch.long , device=__a ) # first forward pass UpperCAmelCase_ : List[Any] = model(__a , attention_mask=__a , use_cache=__a ) UpperCAmelCase_ ,UpperCAmelCase_ : Dict = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase_ : Union[str, Any] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCAmelCase_ : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : Optional[int] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCAmelCase_ : Any = model(__a , attention_mask=__a )["""last_hidden_state"""] UpperCAmelCase_ : Dict = model(__a , attention_mask=__a , past_key_values=__a )[ """last_hidden_state""" ] # select random slice UpperCAmelCase_ : Dict = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : Optional[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase_ : Union[str, Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__a , __a , atol=1E-3 ) ) def a ( self : List[Any] , a_ : Optional[int] , a_ : Optional[int] , a_ : List[Any] , a_ : int , a_ : Optional[Any] , *a_ : Tuple , a_ : List[str]=False )-> int: """simple docstring""" UpperCAmelCase_ : Any = BioGptForCausalLM(__a ) model.to(__a ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCAmelCase_ : str = model(__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def a ( self : Any , a_ : List[str] , *a_ : Dict )-> Optional[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = BioGptModel(__a ) UpperCAmelCase_ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def a ( self : Any , a_ : int , a_ : str , a_ : str , a_ : Union[str, Any] , a_ : Tuple , *a_ : Any )-> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.num_labels UpperCAmelCase_ : Union[str, Any] = BioGptForTokenClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase_ : str = model(__a , attention_mask=__a , token_type_ids=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a ( self : Optional[int] )-> Optional[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) ,( UpperCAmelCase_ ) ,( UpperCAmelCase_ ) ,( UpperCAmelCase_ ) ,( UpperCAmelCase_ ) ,( UpperCAmelCase_ ) ,( UpperCAmelCase_ ) , ) : List[str] = config_and_inputs UpperCAmelCase_ : List[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ (lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) UpperCamelCase_ : List[Any] = (BioGptForCausalLM,) if is_torch_available() else () UpperCamelCase_ : Dict = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase_ : Optional[Any] = False def a ( self : Tuple )-> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = BioGptModelTester(self ) UpperCAmelCase_ : Union[str, Any] = ConfigTester(self , config_class=__a , hidden_size=37 ) def a ( self : List[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def a ( self : List[Any] )-> Any: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def a ( self : List[Any] )-> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : Dict = type self.model_tester.create_and_check_model(*__a ) def a ( self : Union[str, Any] )-> str: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__a ) def a ( self : Tuple )-> Optional[int]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*__a , gradient_checkpointing=__a ) def a ( self : Dict )-> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__a ) def a ( self : int )-> Optional[Any]: """simple docstring""" UpperCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*__a ) def a ( self : Optional[Any] )-> Any: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*__a ) @slow def a ( self : List[Any] )-> Any: """simple docstring""" UpperCAmelCase_ : List[str] = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(__a ) UpperCAmelCase_ : Optional[Any] = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCAmelCase_ : Union[str, Any] = """left""" # Define PAD Token = EOS Token = 50256 UpperCAmelCase_ : str = tokenizer.eos_token UpperCAmelCase_ : Optional[int] = model.config.eos_token_id # use different length sentences to test batching UpperCAmelCase_ : Any = [ """Hello, my dog is a little""", """Today, I""", ] UpperCAmelCase_ : Dict = tokenizer(__a , return_tensors="""pt""" , padding=__a ) UpperCAmelCase_ : int = inputs["""input_ids"""].to(__a ) UpperCAmelCase_ : List[Any] = model.generate( input_ids=__a , attention_mask=inputs["""attention_mask"""].to(__a ) , ) UpperCAmelCase_ : Any = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(__a ) UpperCAmelCase_ : Optional[Any] = model.generate(input_ids=__a ) UpperCAmelCase_ : Any = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCAmelCase_ : Tuple = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(__a ) UpperCAmelCase_ : Optional[int] = model.generate(input_ids=__a , max_length=model.config.max_length - num_paddings ) UpperCAmelCase_ : Optional[Any] = tokenizer.batch_decode(__a , skip_special_tokens=__a ) UpperCAmelCase_ : Any = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__a ) UpperCAmelCase_ : Optional[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=__a ) UpperCAmelCase_ : List[Any] = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , [non_padded_sentence, padded_sentence] ) @slow def a ( self : Union[str, Any] )-> Tuple: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Dict = BioGptModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def a ( self : Optional[Any] )-> Dict: """simple docstring""" UpperCAmelCase_ ,UpperCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : Tuple = 3 UpperCAmelCase_ : Optional[int] = input_dict["""input_ids"""] UpperCAmelCase_ : Optional[Any] = input_ids.ne(1 ).to(__a ) UpperCAmelCase_ : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCAmelCase_ : Optional[Any] = BioGptForSequenceClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase_ : str = model(__a , attention_mask=__a , labels=__a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def a ( self : Optional[Any] )-> Optional[Any]: """simple docstring""" UpperCAmelCase_ ,UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[Any] = 3 UpperCAmelCase_ : Dict = """multi_label_classification""" UpperCAmelCase_ : Any = input_dict["""input_ids"""] UpperCAmelCase_ : Optional[Any] = input_ids.ne(1 ).to(__a ) UpperCAmelCase_ : List[str] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCAmelCase_ : str = BioGptForSequenceClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase_ : List[str] = model(__a , attention_mask=__a , labels=__a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCAmelCase_ (unittest.TestCase ): """simple docstring""" @slow def a ( self : Tuple )-> Dict: """simple docstring""" UpperCAmelCase_ : Dict = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCAmelCase_ : Tuple = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCAmelCase_ : int = model(__a )[0] UpperCAmelCase_ : Optional[Any] = 4_23_84 UpperCAmelCase_ : Optional[Any] = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , __a ) UpperCAmelCase_ : str = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1E-4 ) ) @slow def a ( self : Tuple )-> Dict: """simple docstring""" UpperCAmelCase_ : str = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCAmelCase_ : Dict = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(__a ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(__a ) UpperCAmelCase_ : Dict = model.generate( **__a , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=__a , ) UpperCAmelCase_ : Any = tokenizer.decode(output_ids[0] , skip_special_tokens=__a ) UpperCAmelCase_ : str = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(__a , __a )
470
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , *__a : Tuple , **__a : Optional[Any] ): warnings.warn( "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DPTImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow A : Union[str, Any] = False class a_ ( unittest.TestCase ): def UpperCamelCase_ ( self , __UpperCamelCase=32 ): set_seed(0 ) _lowercase = UNetaDModel(sample_size=__a , in_channels=3 , out_channels=3 ) _lowercase = torch.optim.SGD(model.parameters() , lr=0.00_01 ) return model, optimizer @slow def UpperCamelCase_ ( self ): _lowercase = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable _lowercase = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.00_01 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=__a , ) _lowercase = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.00_01 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=__a , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) _lowercase = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(__a ) for _ in range(4 )] _lowercase = [torch.randn((4, 3, 32, 32) ).to(__a ) for _ in range(4 )] _lowercase = [torch.randint(0 , 1_000 , (4,) ).long().to(__a ) for _ in range(4 )] # train with a DDPM scheduler _lowercase , _lowercase = self.get_model_optimizer(resolution=32 ) model.train().to(__a ) for i in range(4 ): optimizer.zero_grad() _lowercase = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) _lowercase = model(__a , timesteps[i] ).sample _lowercase = torch.nn.functional.mse_loss(__a , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM _lowercase , _lowercase = self.get_model_optimizer(resolution=32 ) model.train().to(__a ) for i in range(4 ): optimizer.zero_grad() _lowercase = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) _lowercase = model(__a , timesteps[i] ).sample _lowercase = torch.nn.functional.mse_loss(__a , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(__a , __a , atol=1E-5 ) ) self.assertTrue(torch.allclose(__a , __a , atol=1E-5 ) )
287
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Any ) -> Tuple: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : str = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Dict: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] ) -> Dict: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Optional[Any] , __a : Dict , __a : Optional[int] ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Optional[int]=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : List[str] , __a : Optional[Any] , __a : List[str] ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Dict , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : Optional[int] ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
692
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowercase__ : Union[str, Any] = { 'configuration_speech_to_text': ['SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Speech2TextConfig'], 'processing_speech_to_text': ['Speech2TextProcessor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Any = ['Speech2TextTokenizer'] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Union[str, Any] = ['Speech2TextFeatureExtractor'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : str = [ 'TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFSpeech2TextForConditionalGeneration', 'TFSpeech2TextModel', 'TFSpeech2TextPreTrainedModel', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[Any] = [ 'SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Speech2TextForConditionalGeneration', 'Speech2TextModel', 'Speech2TextPreTrainedModel', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowercase__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
123
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase_ : Any = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys lowerCAmelCase_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
692
0
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( lowerCamelCase_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = FlaxAutoencoderKL @property def _snake_case ( self : str ) -> Optional[int]: _lowerCamelCase = 4 _lowerCamelCase = 3 _lowerCamelCase = (3_2, 3_2) _lowerCamelCase = jax.random.PRNGKey(0 ) _lowerCamelCase = jax.random.uniform(__a , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def _snake_case ( self : List[Any] ) -> Tuple: _lowerCamelCase = { 'block_out_channels': [3_2, 6_4], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } _lowerCamelCase = self.dummy_input return init_dict, inputs_dict
544
'''simple docstring''' import gc import threading import time import psutil import torch class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] ): _a = psutil.Process() _a = False def UpperCamelCase__ ( self : Tuple ): _a = -1 while True: _a = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def UpperCamelCase__ ( self : List[Any] ): _a = True _a = threading.Thread(target=self.peak_monitor ) _a = True self.thread.start() def UpperCamelCase__ ( self : Optional[int] ): _a = False self.thread.join() return self.cpu_memory_peak lowerCAmelCase_ : List[Any] = PeakCPUMemory() def _lowerCamelCase ( ) -> Tuple: # Time _a = {"time": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem _a = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): _a = torch.cuda.memory_allocated(lowercase ) torch.cuda.reset_peak_memory_stats() return measures def _lowerCamelCase ( lowercase : Any ) -> int: # Time _a = {"time": time.time() - start_measures["time"]} gc.collect() torch.cuda.empty_cache() # CPU mem _a = (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20 _a = (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): _a = (torch.cuda.memory_allocated(lowercase ) - start_measures[str(lowercase )]) / 2**20 _a = (torch.cuda.max_memory_allocated(lowercase ) - start_measures[str(lowercase )]) / 2**20 return measures def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Dict ) -> str: print(F'{description}:' ) print(F'- Time: {measures["time"]:.2f}s' ) for i in range(torch.cuda.device_count() ): print(F'- GPU {i} allocated: {measures[str(lowercase )]:.2f}MiB' ) _a = measures[F'{i}-peak'] print(F'- GPU {i} peak: {peak:.2f}MiB' ) print(F'- CPU RAM allocated: {measures["cpu"]:.2f}MiB' ) print(F'- CPU RAM peak: {measures["cpu-peak"]:.2f}MiB' )
692
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available A : Optional[Any] = { 'configuration_gpt_neo': ['GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoConfig', 'GPTNeoOnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[Any] = [ 'GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoForCausalLM', 'GPTNeoForQuestionAnswering', 'GPTNeoForSequenceClassification', 'GPTNeoForTokenClassification', 'GPTNeoModel', 'GPTNeoPreTrainedModel', 'load_tf_weights_in_gpt_neo', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = [ 'FlaxGPTNeoForCausalLM', 'FlaxGPTNeoModel', 'FlaxGPTNeoPreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys A : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
371
'''simple docstring''' import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(DDIMParallelScheduler,) __a =(('eta', 0.0), ('num_inference_steps', 50)) def UpperCamelCase__ ( self : Optional[int] , **__a : Any ): _a = { "num_train_timesteps": 10_00, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[str] , **__a : Optional[int] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config(**__a ) _a = scheduler_class(**__a ) _a , _a = 10, 0.0 _a = self.dummy_model() _a = self.dummy_sample_deter scheduler.set_timesteps(__a ) for t in scheduler.timesteps: _a = model(__a , __a ) _a = scheduler.step(__a , __a , __a , __a ).prev_sample return sample def UpperCamelCase__ ( self : str ): for timesteps in [1_00, 5_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : Dict ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__a ) _a = self.scheduler_classes[0] _a = self.get_scheduler_config(steps_offset=1 ) _a = scheduler_class(**__a ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_01, 6_01, 4_01, 2_01, 1] ) ) def UpperCamelCase__ ( self : Tuple ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def UpperCamelCase__ ( self : Dict ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__a ) def UpperCamelCase__ ( self : Tuple ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def UpperCamelCase__ ( self : Dict ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__a ) def UpperCamelCase__ ( self : Optional[int] ): for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__a ) def UpperCamelCase__ ( self : Optional[Any] ): for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__a ) def UpperCamelCase__ ( self : List[Any] ): self.check_over_configs(thresholding=__a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__a , prediction_type=__a , sample_max_value=__a , ) def UpperCamelCase__ ( self : List[Any] ): for t in [1, 10, 49]: self.check_over_forward(time_step=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 5_00] ): self.check_over_forward(time_step=__a , num_inference_steps=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__a , eta=__a ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_20 , 4_00 ) - 0.14771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_80 , 9_60 ) - 0.32460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 , 4_86 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 , 9_98 ) - 0.02 ) ) < 1e-5 def UpperCamelCase__ ( self : List[str] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a , _a = 10, 0.0 scheduler.set_timesteps(__a ) _a = self.dummy_model() _a = self.dummy_sample_deter _a = self.dummy_sample_deter + 0.1 _a = self.dummy_sample_deter - 0.1 _a = samplea.shape[0] _a = torch.stack([samplea, samplea, samplea] , dim=0 ) _a = torch.arange(__a )[0:3, None].repeat(1 , __a ) _a = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _a = scheduler.batch_step_no_noise(__a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __a ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1147.7904 ) < 1e-2 assert abs(result_mean.item() - 0.4982 ) < 1e-3 def UpperCamelCase__ ( self : List[str] ): _a = self.full_loop() _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 172.0067 ) < 1e-2 assert abs(result_mean.item() - 0.223967 ) < 1e-3 def UpperCamelCase__ ( self : str ): _a = self.full_loop(prediction_type="v_prediction" ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 52.5302 ) < 1e-2 assert abs(result_mean.item() - 0.0684 ) < 1e-3 def UpperCamelCase__ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _a = self.full_loop(set_alpha_to_one=__a , beta_start=0.01 ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 149.8295 ) < 1e-2 assert abs(result_mean.item() - 0.1951 ) < 1e-3 def UpperCamelCase__ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _a = self.full_loop(set_alpha_to_one=__a , beta_start=0.01 ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 149.0784 ) < 1e-2 assert abs(result_mean.item() - 0.1941 ) < 1e-3
692
0
from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def A__( ): import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join _snake_case : Dict = '__test_patch_submodule_mock__' with patch_submodule(_test_patching , 'os.path.join' , __lowerCAmelCase ): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os , _PatchedModuleObj ) assert isinstance(_test_patching.os.path , _PatchedModuleObj ) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path , _PatchedModuleObj ) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os , _PatchedModuleObj ) assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj ) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path , _PatchedModuleObj ) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def A__( ): assert _test_patching.open is open _snake_case : Optional[Any] = '__test_patch_submodule_builtin_mock__' # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching , 'open' , __lowerCAmelCase ): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def A__( ): # pandas.read_csv is not present in _test_patching _snake_case : int = '__test_patch_submodule_missing_mock__' with patch_submodule(_test_patching , 'pandas.read_csv' , __lowerCAmelCase ): pass def A__( ): # builtin should always be mocked even if they're not in the globals # in case they're loaded at one point _snake_case : Optional[int] = '__test_patch_submodule_missing_builtin_mock__' # _test_patching doesn't have "len" in its globals assert getattr(_test_patching , 'len' , __lowerCAmelCase ) is None with patch_submodule(_test_patching , 'len' , __lowerCAmelCase ): assert _test_patching.len is mock assert _test_patching.len is len def A__( ): _snake_case : Tuple = '__test_patch_submodule_start_and_stop_mock__' _snake_case : Optional[int] = patch_submodule(_test_patching , 'open' , __lowerCAmelCase ) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def A__( ): from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join _snake_case : Tuple = '__test_patch_submodule_successive_join__' _snake_case : Tuple = '__test_patch_submodule_successive_dirname__' _snake_case : List[Any] = '__test_patch_submodule_successive_rename__' assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching , 'os.path.join' , __lowerCAmelCase ): with patch_submodule(_test_patching , 'os.rename' , __lowerCAmelCase ): with patch_submodule(_test_patching , 'os.path.dirname' , __lowerCAmelCase ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching , 'os.rename' , __lowerCAmelCase ): with patch_submodule(_test_patching , 'os.path.join' , __lowerCAmelCase ): with patch_submodule(_test_patching , 'os.path.dirname' , __lowerCAmelCase ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def A__( ): _snake_case : Optional[int] = '__test_patch_submodule_doesnt_exist_mock__' with patch_submodule(_test_patching , '__module_that_doesn_exist__.__attribute_that_doesn_exist__' , __lowerCAmelCase ): pass with patch_submodule(_test_patching , 'os.__attribute_that_doesn_exist__' , __lowerCAmelCase ): pass
304
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _lowerCamelCase ( lowercase : Any ) -> List[str]: return getitem, k def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Any: return setitem, k, v def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: return delitem, k def _lowerCamelCase ( lowercase : Tuple , lowercase : Dict , *lowercase : Union[str, Any] ) -> int: try: return fun(lowercase , *lowercase ), None except Exception as e: return None, e lowerCAmelCase_ : Optional[Any] = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) lowerCAmelCase_ : Optional[int] = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] lowerCAmelCase_ : int = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] lowerCAmelCase_ : List[Any] = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('key_a', 'val_b'), ] @pytest.mark.parametrize( "operations" , ( pytest.param(_add_items , id="add items" ), pytest.param(_overwrite_items , id="overwrite items" ), pytest.param(_delete_items , id="delete items" ), pytest.param(_access_absent_items , id="access absent items" ), pytest.param(_add_with_resize_up , id="add with resize up" ), pytest.param(_add_with_resize_down , id="add with resize down" ), ) , ) def _lowerCamelCase ( lowercase : Optional[int] ) -> Optional[int]: _a = HashMap(initial_block_size=4 ) _a = {} for _, (fun, *args) in enumerate(lowercase ): _a , _a = _run_operation(lowercase , lowercase , *lowercase ) _a , _a = _run_operation(lowercase , lowercase , *lowercase ) assert my_res == py_res assert str(lowercase ) == str(lowercase ) assert set(lowercase ) == set(lowercase ) assert len(lowercase ) == len(lowercase ) assert set(my.items() ) == set(py.items() ) def _lowerCamelCase ( ) -> str: def is_public(lowercase : str ) -> bool: return not name.startswith("_" ) _a = {name for name in dir({} ) if is_public(lowercase )} _a = {name for name in dir(HashMap() ) if is_public(lowercase )} assert dict_public_names > hash_public_names
692
0
def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> float: '''simple docstring''' UpperCAmelCase__ : List[str] = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def _lowerCamelCase ( ) -> Tuple: '''simple docstring''' print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
79
'''simple docstring''' import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =PhobertTokenizer __a =False def UpperCamelCase__ ( self : int ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _a = ["T@@", "i", "I", "R@@", "r", "e@@"] _a = dict(zip(__a , range(len(__a ) ) ) ) _a = ["#version: 0.2", "l à</w>"] _a = {"unk_token": "<unk>"} _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(f'{token} {vocab_tokens[token]}\n' ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__a ) ) def UpperCamelCase__ ( self : str , **__a : List[str] ): kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ): _a = "Tôi là VinAI Research" _a = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>" return input_text, output_text def UpperCamelCase__ ( self : Dict ): _a = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _a = "Tôi là VinAI Research" _a = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split() _a = tokenizer.tokenize(__a ) print(__a ) self.assertListEqual(__a , __a ) _a = tokens + [tokenizer.unk_token] _a = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a )
692
0
"""simple docstring""" import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _lowerCAmelCase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase=1_3 , __UpperCAmelCase=3 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=2_2_4 , __UpperCAmelCase=1_0_0_0 , __UpperCAmelCase=[3, 3, 6, 4] , __UpperCAmelCase=[4_8, 5_6, 1_1_2, 2_2_0] , ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = parent lowerCAmelCase__ :Dict = batch_size lowerCAmelCase__ :Optional[Any] = num_channels lowerCAmelCase__ :Tuple = is_training lowerCAmelCase__ :Tuple = use_labels lowerCAmelCase__ :int = hidden_dropout_prob lowerCAmelCase__ :Dict = attention_probs_dropout_prob lowerCAmelCase__ :List[str] = num_labels lowerCAmelCase__ :List[Any] = image_size lowerCAmelCase__ :Any = layer_depths lowerCAmelCase__ :List[str] = embed_dims def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ :Dict = None if self.use_labels: lowerCAmelCase__ :Any = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ :Dict = self.get_config() return config, pixel_values, labels def snake_case ( self ): '''simple docstring''' return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='gelu' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=__a , layer_scale_init_value=1E-5 , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = SwiftFormerModel(config=__a ) model.to(__a ) model.eval() lowerCAmelCase__ :Optional[int] = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :int = self.num_labels lowerCAmelCase__ :Tuple = SwiftFormerForImageClassification(__a ) model.to(__a ) model.eval() lowerCAmelCase__ :str = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) lowerCAmelCase__ :Optional[int] = SwiftFormerForImageClassification(__a ) model.to(__a ) model.eval() lowerCAmelCase__ :str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ :List[Any] = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case ( self ): '''simple docstring''' ((lowerCAmelCase__) , (lowerCAmelCase__) , (lowerCAmelCase__)) :Union[str, Any] = self.prepare_config_and_inputs() lowerCAmelCase__ :List[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __magic_name__ :Dict = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () __magic_name__ :int = ( {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification} if is_torch_available() else {} ) __magic_name__ :Dict = False __magic_name__ :List[str] = False __magic_name__ :Optional[int] = False __magic_name__ :Dict = False __magic_name__ :List[Any] = False def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = SwiftFormerModelTester(self ) lowerCAmelCase__ :Any = ConfigTester( self , config_class=__a , has_text_modality=__a , hidden_size=3_7 , num_attention_heads=1_2 , num_hidden_layers=1_2 , ) def snake_case ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='SwiftFormer does not use inputs_embeds' ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :List[str] = model_class(__a ) lowerCAmelCase__ :Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :int = model_class(__a ) lowerCAmelCase__ :int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ :Optional[Any] = [*signature.parameters.keys()] lowerCAmelCase__ :str = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def snake_case ( self ): '''simple docstring''' for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ :Any = SwiftFormerModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @unittest.skip(reason='SwiftFormer does not output attentions' ) def snake_case ( self ): '''simple docstring''' pass def snake_case ( self ): '''simple docstring''' def check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :List[Any] = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): lowerCAmelCase__ :List[Any] = model(**self._prepare_for_class(__a , __a ) ) lowerCAmelCase__ :Optional[int] = outputs.hidden_states lowerCAmelCase__ :Any = 8 self.assertEqual(len(__a ) , __a ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(__a ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ :Any = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ :str = True check_hidden_states_output(__a , __a , __a ) def snake_case ( self ): '''simple docstring''' def _config_zero_init(__UpperCAmelCase ): lowerCAmelCase__ :Any = copy.deepcopy(__a ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(__a , __a , 1E-10 ) if isinstance(getattr(__a , __a , __a ) , __a ): lowerCAmelCase__ :Optional[Any] = _config_zero_init(getattr(__a , __a ) ) setattr(__a , __a , __a ) return configs_no_init lowerCAmelCase__ , lowerCAmelCase__ :int = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ :Optional[int] = _config_zero_init(__a ) for model_class in self.all_model_classes: lowerCAmelCase__ :List[str] = model_class(config=__a ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def snake_case ( self ): '''simple docstring''' pass def __A () ->List[str]: """simple docstring""" lowerCAmelCase__ :str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case ( self ): '''simple docstring''' return ViTImageProcessor.from_pretrained('MBZUAI/swiftformer-xs' ) if is_vision_available() else None @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = SwiftFormerForImageClassification.from_pretrained('MBZUAI/swiftformer-xs' ).to(__a ) lowerCAmelCase__ :Optional[Any] = self.default_image_processor lowerCAmelCase__ :Tuple = prepare_img() lowerCAmelCase__ :Tuple = image_processor(images=__a , return_tensors='pt' ).to(__a ) # forward pass with torch.no_grad(): lowerCAmelCase__ :Tuple = model(**__a ) # verify the logits lowerCAmelCase__ :List[Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __a ) lowerCAmelCase__ :List[Any] = torch.tensor([[-2.1703E00, 2.1107E00, -2.0811E00]] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1E-4 ) )
93
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : str , *__a : Any , __a : str=None , __a : Union[str, Any]=None , **__a : Any ): super().__init__(*__a , **__a ) _a = eval_examples _a = post_process_function def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : Any=None , __a : str=None , __a : str = "eval" ): _a = self.eval_dataset if eval_dataset is None else eval_dataset _a = self.get_eval_dataloader(__a ) _a = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _a = self.compute_metrics _a = None _a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _a = time.time() try: _a = eval_loop( __a , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__a , metric_key_prefix=__a , ) finally: _a = compute_metrics _a = self.args.eval_batch_size * self.args.world_size if f'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( __a , __a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default _a = self.post_process_function(__a , __a , output.predictions ) _a = self.compute_metrics(__a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'{metric_key_prefix}_' ): _a = metrics.pop(__a ) metrics.update(output.metrics ) else: _a = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__a ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _a = self.callback_handler.on_evaluate(self.args , self.state , self.control , __a ) return metrics def UpperCamelCase__ ( self : Tuple , __a : Dict , __a : Optional[Any] , __a : Optional[Any]=None , __a : str = "test" ): _a = self.get_test_dataloader(__a ) # Temporarily disable metric computation, we will do it in the loop here. _a = self.compute_metrics _a = None _a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _a = time.time() try: _a = eval_loop( __a , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__a , metric_key_prefix=__a , ) finally: _a = compute_metrics _a = self.args.eval_batch_size * self.args.world_size if f'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( __a , __a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output _a = self.post_process_function(__a , __a , output.predictions , "predict" ) _a = self.compute_metrics(__a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'{metric_key_prefix}_' ): _a = metrics.pop(__a ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__a )
692
0
"""simple docstring""" import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def snake_case_ ( A_ : Optional[int], A_ : Tuple, A_ : int ): '''simple docstring''' _lowerCamelCase : List[str] = AlbertConfig.from_json_file(A_ ) print(F'''Building PyTorch model from configuration: {config}''' ) _lowerCamelCase : str = AlbertForPreTraining(A_ ) # Load weights from tf checkpoint load_tf_weights_in_albert(A_, A_, A_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict(), A_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--albert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained ALBERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
83
'''simple docstring''' import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : Dict , **__a : List[Any] ): warnings.warn( "The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ChineseCLIPImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' import math def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ) -> int: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[int] = f"Input value of [number={number}] must be an integer" raise TypeError(__SCREAMING_SNAKE_CASE ) if number < 1: snake_case__ : Any = f"Input value of [number={number}] must be > 0" raise ValueError(__SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: snake_case__ : Tuple = int(math.log(number // 3 , 2 ) ) + 2 snake_case__ : int = [3, 5] snake_case__ : Any = 2 snake_case__ : Optional[int] = 3 for block in range(1 , __SCREAMING_SNAKE_CASE ): for _ in range(__SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): A_ = 0 try: A_ = proth(number) except ValueError: print(F'ValueError: there is no {number}th Proth number') continue print(F'The {number}th Proth number: {value}')
270
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[int] , __a : int , __a : int , __a : int , __a : str=0.0 , __a : Optional[int] = None , __a : str = "geglu" , __a : Optional[int] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : str = "layer_norm" , __a : bool = False , ): super().__init__() _a = only_cross_attention _a = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" _a = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f'`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to' f' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _a = AdaLayerNorm(__a , __a ) elif self.use_ada_layer_norm_zero: _a = AdaLayerNormZero(__a , __a ) else: _a = nn.LayerNorm(__a , elementwise_affine=__a ) _a = Attention( query_dim=__a , heads=__a , dim_head=__a , dropout=__a , bias=__a , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__a , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _a = ( AdaLayerNorm(__a , __a ) if self.use_ada_layer_norm else nn.LayerNorm(__a , elementwise_affine=__a ) ) _a = Attention( query_dim=__a , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__a , dim_head=__a , dropout=__a , bias=__a , upcast_attention=__a , ) # is self-attn if encoder_hidden_states is none else: _a = None _a = None # 3. Feed-forward _a = nn.LayerNorm(__a , elementwise_affine=__a ) _a = FeedForward(__a , dropout=__a , activation_fn=__a , final_dropout=__a ) # let chunk size default to None _a = None _a = 0 def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : int ): # Sets chunk feed-forward _a = chunk_size _a = dim def UpperCamelCase__ ( self : List[str] , __a : torch.FloatTensor , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.LongTensor] = None , __a : Dict[str, Any] = None , __a : Optional[torch.LongTensor] = None , ): # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: _a = self.norma(__a , __a ) elif self.use_ada_layer_norm_zero: _a , _a , _a , _a , _a = self.norma( __a , __a , __a , hidden_dtype=hidden_states.dtype ) else: _a = self.norma(__a ) _a = cross_attention_kwargs if cross_attention_kwargs is not None else {} _a = self.attna( __a , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__a , **__a , ) if self.use_ada_layer_norm_zero: _a = gate_msa.unsqueeze(1 ) * attn_output _a = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _a = ( self.norma(__a , __a ) if self.use_ada_layer_norm else self.norma(__a ) ) _a = self.attna( __a , encoder_hidden_states=__a , attention_mask=__a , **__a , ) _a = attn_output + hidden_states # 3. Feed-forward _a = self.norma(__a ) if self.use_ada_layer_norm_zero: _a = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f'`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.' ) _a = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _a = torch.cat( [self.ff(__a ) for hid_slice in norm_hidden_states.chunk(__a , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: _a = self.ff(__a ) if self.use_ada_layer_norm_zero: _a = gate_mlp.unsqueeze(1 ) * ff_output _a = ff_output + hidden_states return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[Any] , __a : int , __a : Optional[int] = None , __a : int = 4 , __a : float = 0.0 , __a : str = "geglu" , __a : bool = False , ): super().__init__() _a = int(dim * mult ) _a = dim_out if dim_out is not None else dim if activation_fn == "gelu": _a = GELU(__a , __a ) if activation_fn == "gelu-approximate": _a = GELU(__a , __a , approximate="tanh" ) elif activation_fn == "geglu": _a = GEGLU(__a , __a ) elif activation_fn == "geglu-approximate": _a = ApproximateGELU(__a , __a ) _a = nn.ModuleList([] ) # project in self.net.append(__a ) # project dropout self.net.append(nn.Dropout(__a ) ) # project out self.net.append(nn.Linear(__a , __a ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(__a ) ) def UpperCamelCase__ ( self : List[Any] , __a : Tuple ): for module in self.net: _a = module(__a ) return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : int , __a : int , __a : str = "none" ): super().__init__() _a = nn.Linear(__a , __a ) _a = approximate def UpperCamelCase__ ( self : Union[str, Any] , __a : List[Any] ): if gate.device.type != "mps": return F.gelu(__a , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def UpperCamelCase__ ( self : str , __a : Optional[int] ): _a = self.proj(__a ) _a = self.gelu(__a ) return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : str , __a : int , __a : int ): super().__init__() _a = nn.Linear(__a , dim_out * 2 ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[int] ): if gate.device.type != "mps": return F.gelu(__a ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def UpperCamelCase__ ( self : List[str] , __a : Any ): _a , _a = self.proj(__a ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(__a ) class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[Any] , __a : int , __a : int ): super().__init__() _a = nn.Linear(__a , __a ) def UpperCamelCase__ ( self : Union[str, Any] , __a : Dict ): _a = self.proj(__a ) return x * torch.sigmoid(1.702 * x ) class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : str , __a : str ): super().__init__() _a = nn.Embedding(__a , __a ) _a = nn.SiLU() _a = nn.Linear(__a , embedding_dim * 2 ) _a = nn.LayerNorm(__a , elementwise_affine=__a ) def UpperCamelCase__ ( self : Tuple , __a : Any , __a : Optional[Any] ): _a = self.linear(self.silu(self.emb(__a ) ) ) _a , _a = torch.chunk(__a , 2 ) _a = self.norm(__a ) * (1 + scale) + shift return x class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[Any] , __a : List[Any] , __a : Any ): super().__init__() _a = CombinedTimestepLabelEmbeddings(__a , __a ) _a = nn.SiLU() _a = nn.Linear(__a , 6 * embedding_dim , bias=__a ) _a = nn.LayerNorm(__a , elementwise_affine=__a , eps=1e-6 ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict , __a : List[Any] , __a : Union[str, Any] , __a : List[Any]=None ): _a = self.linear(self.silu(self.emb(__a , __a , hidden_dtype=__a ) ) ) _a , _a , _a , _a , _a , _a = emb.chunk(6 , dim=1 ) _a = self.norm(__a ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[int] , __a : int , __a : int , __a : int , __a : Optional[str] = None , __a : float = 1e-5 ): super().__init__() _a = num_groups _a = eps if act_fn is None: _a = None else: _a = get_activation(__a ) _a = nn.Linear(__a , out_dim * 2 ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[Any] , __a : List[Any] ): if self.act: _a = self.act(__a ) _a = self.linear(__a ) _a = emb[:, :, None, None] _a , _a = emb.chunk(2 , dim=1 ) _a = F.group_norm(__a , self.num_groups , eps=self.eps ) _a = x * (1 + scale) + shift return x
692
0
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.17.0.dev0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/text-classification/requirements.txt') __lowerCamelCase = logging.getLogger(__name__) @dataclass class __A : UpperCAmelCase__ = field( default="tab_fact" ,metadata={"help": "The name of the dataset to use (via the datasets library)."} ) UpperCAmelCase__ = field( default="tab_fact" ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ,) UpperCAmelCase__ = field( default=1_0_2_4 ,metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } ,) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } ,) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } ,) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } ,) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } ,) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={"help": "A csv or a json file containing the training data."} ) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={"help": "A csv or a json file containing the validation data."} ) UpperCAmelCase__ = field(default=lowerCamelCase_ ,metadata={"help": "A csv or a json file containing the test data."} ) def lowerCamelCase__ ( self : Any ) -> Dict: if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError("""Need either a GLUE task, a training/validation file or a dataset name.""" ) else: __magic_name__: Optional[Any] = self.train_file.split(""".""" )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." __magic_name__: Optional[int] = self.validation_file.split(""".""" )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class __A : UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} ,) UpperCAmelCase__ = field( default="main" ,metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} ,) UpperCAmelCase__ = field( default=lowerCamelCase_ ,metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } ,) def a ( ) -> Any: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __magic_name__: Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __magic_name__, __magic_name__, __magic_name__: Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __magic_name__, __magic_name__, __magic_name__: Union[str, Any] = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) __magic_name__: Optional[Any] = training_args.get_process_log_level() logger.setLevel(__UpperCAmelCase ) datasets.utils.logging.set_verbosity(__UpperCAmelCase ) transformers.utils.logging.set_verbosity(__UpperCAmelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(f'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. __magic_name__: Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __magic_name__: Union[str, Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. __magic_name__: Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. __magic_name__: Tuple = {"""train""": data_args.train_file, """validation""": data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: __magic_name__: List[str] = data_args.train_file.split(""".""" )[-1] __magic_name__: Tuple = data_args.test_file.split(""".""" )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." __magic_name__: Optional[int] = data_args.test_file else: raise ValueError("""Need either a GLUE task or a test file for `do_predict`.""" ) for key in data_files.keys(): logger.info(f'load a local file for {key}: {data_files[key]}' ) if data_args.train_file.endswith(""".csv""" ): # Loading a dataset from local csv files __magic_name__: List[str] = load_dataset("""csv""" , data_files=__UpperCAmelCase , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files __magic_name__: Optional[int] = load_dataset("""json""" , data_files=__UpperCAmelCase , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels __magic_name__: Dict = raw_datasets["""train"""].features["""label"""].names __magic_name__: str = len(__UpperCAmelCase ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __magic_name__: Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__UpperCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer __magic_name__: Union[str, Any] = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=__UpperCAmelCase , ) __magic_name__: Dict = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__UpperCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: __magic_name__: Dict = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch __magic_name__: Union[str, Any] = False # Some models have set the order of the labels to use, so let's make sure we do use it. __magic_name__: List[str] = {"""Refused""": 0, """Entailed""": 1} __magic_name__: List[Any] = {0: """Refused""", 1: """Entailed"""} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) __magic_name__: Dict = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(__UpperCAmelCase : List[str] ): # Tokenize the texts def _convert_table_text_to_pandas(__UpperCAmelCase : int ): __magic_name__: int = [_table_row.split("""#""" ) for _table_row in _table_text.strip("""\n""" ).split("""\n""" )] __magic_name__: List[str] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd __magic_name__: int = examples["""statement"""] __magic_name__: str = list(map(_convert_table_text_to_pandas , examples["""table_text"""] ) ) __magic_name__: Dict = tokenizer(__UpperCAmelCase , __UpperCAmelCase , padding=__UpperCAmelCase , max_length=__UpperCAmelCase , truncation=__UpperCAmelCase ) __magic_name__: Optional[int] = examples["""label"""] return result with training_args.main_process_first(desc="""dataset map pre-processing""" ): __magic_name__: Optional[int] = raw_datasets.map( __UpperCAmelCase , batched=__UpperCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on dataset""" , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError("""--do_train requires a train dataset""" ) __magic_name__: List[str] = raw_datasets["""train"""] if data_args.max_train_samples is not None: __magic_name__: Any = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError("""--do_eval requires a validation dataset""" ) __magic_name__: int = raw_datasets["""validation"""] if data_args.max_eval_samples is not None: __magic_name__: Optional[int] = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError("""--do_predict requires a test dataset""" ) __magic_name__: Any = raw_datasets["""test"""] if data_args.max_predict_samples is not None: __magic_name__: Dict = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(__UpperCAmelCase ) ) , 3 ): logger.info(f'Sample {index} of the training set: {train_dataset[index]}.' ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__UpperCAmelCase : EvalPrediction ): __magic_name__: List[Any] = p.predictions[0] if isinstance(p.predictions , __UpperCAmelCase ) else p.predictions __magic_name__: Optional[Any] = np.argmax(__UpperCAmelCase , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: __magic_name__: Optional[int] = default_data_collator elif training_args.fpaa: __magic_name__: Optional[int] = DataCollatorWithPadding(__UpperCAmelCase , pad_to_multiple_of=8 ) else: __magic_name__: Any = None # Initialize our Trainer __magic_name__: Optional[Any] = Trainer( model=__UpperCAmelCase , args=__UpperCAmelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__UpperCAmelCase , tokenizer=__UpperCAmelCase , data_collator=__UpperCAmelCase , ) # Training if training_args.do_train: __magic_name__: Optional[Any] = None if training_args.resume_from_checkpoint is not None: __magic_name__: int = training_args.resume_from_checkpoint elif last_checkpoint is not None: __magic_name__: List[str] = last_checkpoint __magic_name__: int = trainer.train(resume_from_checkpoint=__UpperCAmelCase ) __magic_name__: List[Any] = train_result.metrics __magic_name__: str = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__UpperCAmelCase ) ) __magic_name__: List[Any] = min(__UpperCAmelCase , len(__UpperCAmelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , __UpperCAmelCase ) trainer.save_metrics("""train""" , __UpperCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) __magic_name__: str = trainer.evaluate(eval_dataset=__UpperCAmelCase ) __magic_name__: List[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__UpperCAmelCase ) __magic_name__: Union[str, Any] = min(__UpperCAmelCase , len(__UpperCAmelCase ) ) trainer.log_metrics("""eval""" , __UpperCAmelCase ) trainer.save_metrics("""eval""" , __UpperCAmelCase ) if training_args.do_predict: logger.info("""*** Predict ***""" ) # Removing the `label` columns because it contains -1 and Trainer won't like that. __magic_name__: Optional[Any] = predict_dataset.remove_columns("""label""" ) __magic_name__: Union[str, Any] = trainer.predict(__UpperCAmelCase , metric_key_prefix="""predict""" ).predictions __magic_name__: int = np.argmax(__UpperCAmelCase , axis=1 ) __magic_name__: Dict = os.path.join(training_args.output_dir , """predict_results_tabfact.txt""" ) if trainer.is_world_process_zero(): with open(__UpperCAmelCase , """w""" ) as writer: logger.info("""***** Predict Results *****""" ) writer.write("""index\tprediction\n""" ) for index, item in enumerate(__UpperCAmelCase ): __magic_name__: int = label_list[item] writer.write(f'{index}\t{item}\n' ) __magic_name__: Dict = {"""finetuned_from""": model_args.model_name_or_path, """tasks""": """text-classification"""} if training_args.push_to_hub: trainer.push_to_hub(**__UpperCAmelCase ) else: trainer.create_model_card(**__UpperCAmelCase ) def a ( __UpperCAmelCase : Dict ) -> int: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
96
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 __a =42 class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : int ): _a = [[] for _ in range(__a )] _a = size def __getitem__( self : int , __a : int ): return iter(self._graph[vertex] ) @property def UpperCamelCase__ ( self : Dict ): return self._size def UpperCamelCase__ ( self : Union[str, Any] , __a : int , __a : int , __a : int ): if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(__a , __a ) ) def UpperCamelCase__ ( self : Tuple , __a : int , __a : int ): _a = deque([start_vertex] ) _a = [None] * self.size _a = 0 while queue: _a = queue.popleft() _a = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _a = current_distance + edge.weight _a = distances[edge.destination_vertex] if ( isinstance(__a , __a ) and new_distance >= dest_vertex_distance ): continue _a = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
692
0
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCAmelCase_ (lowerCamelCase_ ): """simple docstring""" UpperCamelCase_ : str = 42 UpperCamelCase_ : List[str] = 42 UpperCamelCase_ : Tuple = None class UpperCAmelCase_ (lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" UpperCamelCase_ : List[str] = 2 @register_to_config def __init__( self : Union[str, Any] , a_ : float = 0.02 , a_ : float = 1_00 , a_ : float = 1.007 , a_ : float = 80 , a_ : float = 0.05 , a_ : float = 50 , )-> int: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = sigma_max # setable values UpperCAmelCase_ : str = None UpperCAmelCase_ : Optional[int] = None UpperCAmelCase_ : Optional[Any] = None # sigma(t_i) def a ( self : Any , a_ : torch.FloatTensor , a_ : Optional[int] = None )-> Any: """simple docstring""" return sample def a ( self : List[Any] , a_ : int , a_ : Union[str, torch.device] = None )-> Tuple: """simple docstring""" UpperCAmelCase_ : Any = num_inference_steps UpperCAmelCase_ : Any = np.arange(0 , self.num_inference_steps )[::-1].copy() UpperCAmelCase_ : List[str] = torch.from_numpy(__a ).to(__a ) UpperCAmelCase_ : List[str] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] UpperCAmelCase_ : str = torch.tensor(__a , dtype=torch.floataa , device=__a ) def a ( self : Dict , a_ : torch.FloatTensor , a_ : float , a_ : Optional[torch.Generator] = None )-> int: """simple docstring""" if self.config.s_min <= sigma <= self.config.s_max: UpperCAmelCase_ : Optional[int] = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: UpperCAmelCase_ : List[str] = 0 # sample eps ~ N(0, S_noise^2 * I) UpperCAmelCase_ : str = self.config.s_noise * randn_tensor(sample.shape , generator=__a ).to(sample.device ) UpperCAmelCase_ : Dict = sigma + gamma * sigma UpperCAmelCase_ : List[Any] = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def a ( self : int , a_ : torch.FloatTensor , a_ : float , a_ : float , a_ : torch.FloatTensor , a_ : bool = True , )-> Optional[Any]: """simple docstring""" UpperCAmelCase_ : str = sample_hat + sigma_hat * model_output UpperCAmelCase_ : str = (sample_hat - pred_original_sample) / sigma_hat UpperCAmelCase_ : str = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=__a , derivative=__a , pred_original_sample=__a ) def a ( self : Dict , a_ : torch.FloatTensor , a_ : float , a_ : float , a_ : torch.FloatTensor , a_ : torch.FloatTensor , a_ : torch.FloatTensor , a_ : bool = True , )-> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = sample_prev + sigma_prev * model_output UpperCAmelCase_ : Union[str, Any] = (sample_prev - pred_original_sample) / sigma_prev UpperCAmelCase_ : Optional[int] = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=__a , derivative=__a , pred_original_sample=__a ) def a ( self : Optional[Any] , a_ : Dict , a_ : Optional[Any] , a_ : Tuple )-> Union[str, Any]: """simple docstring""" raise NotImplementedError()
470
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =FlaxAutoencoderKL @property def UpperCamelCase__ ( self : str ): _a = 4 _a = 3 _a = (32, 32) _a = jax.random.PRNGKey(0 ) _a = jax.random.uniform(__a , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCamelCase__ ( self : List[Any] ): _a = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } _a = self.dummy_input return init_dict, inputs_dict
692
0
import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('''Googling.....''') A : Optional[Any] = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) A : Dict = requests.get(url, headers={'''UserAgent''': UserAgent().random}) # res.raise_for_status() with open('''project1a.html''', '''wb''') as out_file: # only for knowing the class for data in res.iter_content(10_000): out_file.write(data) A : Dict = BeautifulSoup(res.text, '''html.parser''') A : Optional[int] = list(soup.select('''.eZt8xd'''))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('''href''')) else: webbrowser.open(F'https://google.com{link.get("href")}')
287
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration lowerCAmelCase_ : List[Any] = [ # tf -> hf ('/', '.'), ('layer_', 'layers.'), ('kernel', 'weight'), ('beta', 'bias'), ('gamma', 'weight'), ('pegasus', 'model'), ] lowerCAmelCase_ : Optional[int] = [ ('.output.dense', '.fc2'), ('intermediate.LayerNorm', 'final_layer_norm'), ('intermediate.dense', 'fc1'), ] lowerCAmelCase_ : Any = ( INIT_COMMON + [ ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.out_proj'), ('attention.self', 'self_attn'), ('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'), ('attention.encdec_output.dense', 'encoder_attn.out_proj'), ('attention.encdec', 'encoder_attn'), ('key', 'k_proj'), ('value', 'v_proj'), ('query', 'q_proj'), ('decoder.LayerNorm', 'decoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Tuple = ( INIT_COMMON + [ ('embeddings.word_embeddings', 'shared.weight'), ('embeddings.position_embeddings', 'embed_positions.weight'), ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.output'), ('attention.self', 'self_attn.self'), ('encoder.LayerNorm', 'encoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Optional[int] = [ 'encdec/key/bias', 'encdec/query/bias', 'encdec/value/bias', 'self/key/bias', 'self/query/bias', 'self/value/bias', 'encdec_output/dense/bias', 'attention/output/dense/bias', ] def _lowerCamelCase ( lowercase : Any , lowercase : Any ) -> Optional[Any]: for tf_name, hf_name in patterns: _a = k.replace(lowercase , lowercase ) return k def _lowerCamelCase ( lowercase : dict , lowercase : dict ) -> BigBirdPegasusForConditionalGeneration: _a = BigBirdPegasusConfig(**lowercase ) _a = BigBirdPegasusForConditionalGeneration(lowercase ) _a = torch_model.state_dict() _a = {} # separating decoder weights _a = {k: tf_weights[k] for k in tf_weights if k.startswith("pegasus/decoder" )} _a = {k: tf_weights[k] for k in tf_weights if not k.startswith("pegasus/decoder" )} for k, v in tqdm(decoder_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = DECODER_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict: raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' for k, v in tqdm(remaining_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = REMAINING_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' _a = mapping["model.embed_positions.weight"] _a = mapping.pop("model.embed_positions.weight" ) _a , _a = torch_model.load_state_dict(lowercase , strict=lowercase ) _a = [ k for k in missing if k not in [ "final_logits_bias", "model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight", ] ] assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}' assert extra == [], F'no matches found for the following tf keys {extra}' return torch_model def _lowerCamelCase ( lowercase : List[Any] ) -> Dict: _a = tf.train.list_variables(lowercase ) _a = {} _a = ["global_step"] for name, shape in tqdm(lowercase , desc="converting tf checkpoint to dict" ): _a = any(pat in name for pat in ignore_name ) if skip_key: continue _a = tf.train.load_variable(lowercase , lowercase ) _a = array return tf_weights def _lowerCamelCase ( lowercase : str , lowercase : str , lowercase : dict ) -> Union[str, Any]: _a = get_tf_weights_as_numpy(lowercase ) _a = convert_bigbird_pegasus(lowercase , lowercase ) torch_model.save_pretrained(lowercase ) if __name__ == "__main__": lowerCAmelCase_ : str = argparse.ArgumentParser() parser.add_argument('--tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('--save_dir', default=None, type=str, help='Path to the output PyTorch model.') lowerCAmelCase_ : Optional[Any] = parser.parse_args() lowerCAmelCase_ : Optional[Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowercase__ : List[str] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''') lowercase__ : int = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) lowercase__ : Any = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _UpperCAmelCase : _lowerCAmelCase : Union[str, Any] = field( default="""cifar10""" , metadata={"""help""": """Name of a dataset from the datasets package"""}) _lowerCAmelCase : int = field( default=lowerCamelCase_ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}) _lowerCAmelCase : Dict = field( default=lowerCamelCase_ , metadata={"""help""": """The column name of the images in the files. If not set, will try to use \'image\' or \'img\'."""} , ) _lowerCAmelCase : Dict = field(default=lowerCamelCase_ , metadata={"""help""": """A folder containing the training data."""}) _lowerCAmelCase : int = field(default=lowerCamelCase_ , metadata={"""help""": """A folder containing the validation data."""}) _lowerCAmelCase : Any = field( default=0.15 , metadata={"""help""": """Percent to split off of train for validation."""}) _lowerCAmelCase : Optional[int] = field(default=3_2 , metadata={"""help""": """The size of the square patches to use for masking."""}) _lowerCAmelCase : Optional[Any] = field( default=0.6 , metadata={"""help""": """Percentage of patches to mask."""} , ) _lowerCAmelCase : List[str] = field( default=lowerCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _lowerCAmelCase : Optional[int] = field( default=lowerCamelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def _snake_case ( self : Union[str, Any] ): snake_case_ : Any = {} if self.train_dir is not None: snake_case_ : List[str] = self.train_dir if self.validation_dir is not None: snake_case_ : str = self.validation_dir snake_case_ : Optional[int] = data_files if data_files else None @dataclass class _UpperCAmelCase : _lowerCAmelCase : int = field( default=lowerCamelCase_ , metadata={ """help""": ( """The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a """ """checkpoint identifier on the hub. """ """Don\'t set if you want to train a model from scratch.""" ) } , ) _lowerCAmelCase : List[str] = field( default=lowerCamelCase_ , metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(lowerCamelCase_)} , ) _lowerCAmelCase : Dict = field( default=lowerCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) _lowerCAmelCase : Dict = field( default=lowerCamelCase_ , metadata={ """help""": ( """Override some existing default config settings when a model is trained from scratch. Example: """ """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index""" ) } , ) _lowerCAmelCase : Union[str, Any] = field( default=lowerCamelCase_ , metadata={"""help""": """Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"""} , ) _lowerCAmelCase : str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _lowerCAmelCase : List[Any] = field(default=lowerCamelCase_ , metadata={"""help""": """Name or path of preprocessor config."""}) _lowerCAmelCase : str = field( default=lowerCamelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _lowerCAmelCase : Optional[int] = field( default=lowerCamelCase_ , metadata={ """help""": ( """The size (resolution) of each image. If not specified, will use `image_size` of the configuration.""" ) } , ) _lowerCAmelCase : Dict = field( default=lowerCamelCase_ , metadata={ """help""": ( """The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.""" ) } , ) _lowerCAmelCase : Optional[int] = field( default=lowerCamelCase_ , metadata={"""help""": """Stride to use for the encoder."""} , ) class _UpperCAmelCase : def __init__( self : List[str] , lowercase_ : Dict=192 , lowercase_ : int=32 , lowercase_ : Any=4 , lowercase_ : Any=0.6 ): snake_case_ : int = input_size snake_case_ : Tuple = mask_patch_size snake_case_ : Optional[int] = model_patch_size snake_case_ : Optional[Any] = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError('''Input size must be divisible by mask patch size''' ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError('''Mask patch size must be divisible by model patch size''' ) snake_case_ : List[Any] = self.input_size // self.mask_patch_size snake_case_ : List[Any] = self.mask_patch_size // self.model_patch_size snake_case_ : Dict = self.rand_size**2 snake_case_ : str = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self : List[Any] ): snake_case_ : int = np.random.permutation(self.token_count )[: self.mask_count] snake_case_ : Optional[int] = np.zeros(self.token_count , dtype=__a ) snake_case_ : str = 1 snake_case_ : List[Any] = mask.reshape((self.rand_size, self.rand_size) ) snake_case_ : Optional[int] = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def __lowercase ( _a ): snake_case_ : Union[str, Any] = torch.stack([example['''pixel_values'''] for example in examples] ) snake_case_ : Optional[int] = torch.stack([example['''mask'''] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def __lowercase ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. snake_case_ : Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case_, snake_case_, snake_case_ : int = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case_, snake_case_, snake_case_ : Any = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_mim''' , _a , _a ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() snake_case_ : Dict = training_args.get_process_log_level() logger.setLevel(_a ) transformers.utils.logging.set_verbosity(_a ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. snake_case_ : List[str] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case_ : Optional[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset. snake_case_ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. snake_case_ : Optional[int] = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , _a ) and data_args.train_val_split > 0.0: snake_case_ : Optional[Any] = ds['''train'''].train_test_split(data_args.train_val_split ) snake_case_ : Any = split['''train'''] snake_case_ : Any = split['''test'''] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case_ : List[Any] = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name_or_path: snake_case_ : int = AutoConfig.from_pretrained(model_args.config_name_or_path , **_a ) elif model_args.model_name_or_path: snake_case_ : Optional[int] = AutoConfig.from_pretrained(model_args.model_name_or_path , **_a ) else: snake_case_ : Any = CONFIG_MAPPING[model_args.model_type]() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(_a , '''decoder_type''' ): snake_case_ : Tuple = '''simmim''' # adapt config snake_case_ : Tuple = model_args.image_size if model_args.image_size is not None else config.image_size snake_case_ : Tuple = model_args.patch_size if model_args.patch_size is not None else config.patch_size snake_case_ : Tuple = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { '''image_size''': model_args.image_size, '''patch_size''': model_args.patch_size, '''encoder_stride''': model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: snake_case_ : Union[str, Any] = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **_a ) elif model_args.model_name_or_path: snake_case_ : Optional[int] = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **_a ) else: snake_case_ : Dict = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } snake_case_ : int = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: snake_case_ : Union[str, Any] = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=_a , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) snake_case_ : Optional[Any] = AutoModelForMaskedImageModeling.from_config(_a ) if training_args.do_train: snake_case_ : Optional[int] = ds['''train'''].column_names else: snake_case_ : Any = ds['''validation'''].column_names if data_args.image_column_name is not None: snake_case_ : Optional[Any] = data_args.image_column_name elif "image" in column_names: snake_case_ : str = '''image''' elif "img" in column_names: snake_case_ : Optional[Any] = '''img''' else: snake_case_ : str = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py snake_case_ : Optional[int] = Compose( [ Lambda(lambda _a : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator snake_case_ : Tuple = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(_a ): snake_case_ : int = [transforms(_a ) for image in examples[image_column_name]] snake_case_ : List[Any] = [mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: snake_case_ : Tuple = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(_a ) if training_args.do_eval: if "validation" not in ds: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: snake_case_ : Union[str, Any] = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(_a ) # Initialize our trainer snake_case_ : List[str] = Trainer( model=_a , args=_a , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=_a , data_collator=_a , ) # Training if training_args.do_train: snake_case_ : int = None if training_args.resume_from_checkpoint is not None: snake_case_ : Optional[int] = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case_ : List[str] = last_checkpoint snake_case_ : Optional[int] = trainer.train(resume_from_checkpoint=_a ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: snake_case_ : Union[str, Any] = trainer.evaluate() trainer.log_metrics('''eval''' , _a ) trainer.save_metrics('''eval''' , _a ) # Write model card and (optionally) push to hub snake_case_ : int = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''masked-image-modeling''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-image-modeling'''], } if training_args.push_to_hub: trainer.push_to_hub(**_a ) else: trainer.create_model_card(**_a ) if __name__ == "__main__": main()
123
'''simple docstring''' def _lowerCamelCase ( lowercase : str , lowercase : list[str] ) -> str: _a = "" for word_or_phrase in separated: if not isinstance(lowercase , lowercase ): raise Exception("join() accepts only strings to be joined" ) joined += word_or_phrase + separator return joined.strip(lowercase ) if __name__ == "__main__": from doctest import testmod testmod()
692
0
A = 'Alexander Joslin' import operator as op from .stack import Stack def lowerCamelCase ( UpperCamelCase : str ) -> int: _lowerCamelCase = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} _lowerCamelCase = Stack() _lowerCamelCase = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(UpperCamelCase ) ) elif i in operators: # RULE 2 operator_stack.push(UpperCamelCase ) elif i == ")": # RULE 4 _lowerCamelCase = operator_stack.peek() operator_stack.pop() _lowerCamelCase = operand_stack.peek() operand_stack.pop() _lowerCamelCase = operand_stack.peek() operand_stack.pop() _lowerCamelCase = operators[opr](UpperCamelCase , UpperCamelCase ) operand_stack.push(UpperCamelCase ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": A = '(5 + ((4 * 2) * (2 + 3)))' # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
544
'''simple docstring''' lowerCAmelCase_ : Optional[Any] = '\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' lowerCAmelCase_ : List[Any] = [{'type': 'code', 'content': INSTALL_CONTENT}] lowerCAmelCase_ : Dict = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
692
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A : str = logging.get_logger(__name__) A : List[str] = { 'microsoft/focalnet-tiny': 'https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json', } class UpperCamelCase( lowerCamelCase_ , lowerCamelCase_ ): snake_case_ : Tuple = """focalnet""" def __init__( self : str , SCREAMING_SNAKE_CASE : str=2_2_4 , SCREAMING_SNAKE_CASE : Optional[Any]=4 , SCREAMING_SNAKE_CASE : str=3 , SCREAMING_SNAKE_CASE : Dict=9_6 , SCREAMING_SNAKE_CASE : Tuple=False , SCREAMING_SNAKE_CASE : Dict=[1_9_2, 3_8_4, 7_6_8, 7_6_8] , SCREAMING_SNAKE_CASE : List[str]=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE : Optional[int]=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE : str="gelu" , SCREAMING_SNAKE_CASE : Tuple=4.0 , SCREAMING_SNAKE_CASE : Tuple=0.0 , SCREAMING_SNAKE_CASE : List[str]=0.1 , SCREAMING_SNAKE_CASE : Union[str, Any]=False , SCREAMING_SNAKE_CASE : Dict=1e-4 , SCREAMING_SNAKE_CASE : Optional[Any]=False , SCREAMING_SNAKE_CASE : Dict=False , SCREAMING_SNAKE_CASE : Any=False , SCREAMING_SNAKE_CASE : List[str]=0.02 , SCREAMING_SNAKE_CASE : int=1e-5 , SCREAMING_SNAKE_CASE : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE : List[str]=None , SCREAMING_SNAKE_CASE : Tuple=None , **SCREAMING_SNAKE_CASE : str , ) -> Optional[Any]: '''simple docstring''' super().__init__(**__a ) __snake_case = image_size __snake_case = patch_size __snake_case = num_channels __snake_case = embed_dim __snake_case = use_conv_embed __snake_case = hidden_sizes __snake_case = depths __snake_case = focal_levels __snake_case = focal_windows __snake_case = hidden_act __snake_case = mlp_ratio __snake_case = hidden_dropout_prob __snake_case = drop_path_rate __snake_case = use_layerscale __snake_case = layerscale_value __snake_case = use_post_layernorm __snake_case = use_post_layernorm_in_modulation __snake_case = normalize_modulator __snake_case = initializer_range __snake_case = layer_norm_eps __snake_case = encoder_stride __snake_case = ["stem"] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] __snake_case , __snake_case = get_aligned_output_features_output_indices( out_features=__a , out_indices=__a , stage_names=self.stage_names )
371
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') lowerCAmelCase_ : Optional[Any] = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) lowerCAmelCase_ : Dict = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) lowerCAmelCase_ : Dict = BeautifulSoup(res.text, 'html.parser') lowerCAmelCase_ : Optional[int] = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f"""https://google.com{link.get('href')}""")
692
0
import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase : """simple docstring""" def __init__( self : int , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : str=2 , lowerCamelCase_ : str=8 , lowerCamelCase_ : Union[str, Any]=True , lowerCamelCase_ : List[str]=True , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Optional[int]=True , lowerCamelCase_ : List[str]=99 , lowerCamelCase_ : List[str]=16 , lowerCamelCase_ : Tuple=5 , lowerCamelCase_ : Optional[int]=2 , lowerCamelCase_ : List[str]=36 , lowerCamelCase_ : int="gelu" , lowerCamelCase_ : Optional[int]=0.0 , lowerCamelCase_ : Dict=0.0 , lowerCamelCase_ : int=5_12 , lowerCamelCase_ : Union[str, Any]=16 , lowerCamelCase_ : str=2 , lowerCamelCase_ : List[str]=0.02 , lowerCamelCase_ : int=3 , lowerCamelCase_ : Any=4 , lowerCamelCase_ : Optional[int]=None , ): '''simple docstring''' _snake_case : List[Any] = parent _snake_case : List[Any] = batch_size _snake_case : Dict = seq_length _snake_case : List[Any] = is_training _snake_case : Tuple = use_input_mask _snake_case : Any = use_token_type_ids _snake_case : int = use_labels _snake_case : Any = vocab_size _snake_case : Union[str, Any] = hidden_size _snake_case : Dict = num_hidden_layers _snake_case : Any = num_attention_heads _snake_case : List[str] = intermediate_size _snake_case : Optional[Any] = hidden_act _snake_case : List[Any] = hidden_dropout_prob _snake_case : Optional[int] = attention_probs_dropout_prob _snake_case : Tuple = max_position_embeddings _snake_case : List[str] = type_vocab_size _snake_case : Dict = type_sequence_label_size _snake_case : Tuple = initializer_range _snake_case : Tuple = num_labels _snake_case : Optional[int] = num_choices _snake_case : Optional[int] = scope def __UpperCAmelCase ( self : str ): '''simple docstring''' _snake_case : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case : int = None if self.use_input_mask: _snake_case : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case : List[Any] = None if self.use_token_type_ids: _snake_case : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _snake_case : Union[str, Any] = None _snake_case : Union[str, Any] = None _snake_case : List[str] = None if self.use_labels: _snake_case : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _snake_case : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _snake_case : Any = ids_tensor([self.batch_size] , self.num_choices ) _snake_case : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self : str ): '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__a , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self : Any ): '''simple docstring''' _snake_case : Tuple = self.get_config() _snake_case : Optional[int] = 3_00 return config def __UpperCAmelCase ( self : List[str] ): '''simple docstring''' ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) : Any = self.prepare_config_and_inputs() _snake_case : List[str] = True _snake_case : Dict = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _snake_case : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self : Tuple , lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : List[str] , lowerCamelCase_ : Tuple , lowerCamelCase_ : str , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' _snake_case : int = MraModel(config=__a ) model.to(__a ) model.eval() _snake_case : Optional[Any] = model(__a , attention_mask=__a , token_type_ids=__a ) _snake_case : List[Any] = model(__a , token_type_ids=__a ) _snake_case : str = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self : Tuple , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : str , ): '''simple docstring''' _snake_case : Any = True _snake_case : Any = MraModel(__a ) model.to(__a ) model.eval() _snake_case : Optional[Any] = model( __a , attention_mask=__a , token_type_ids=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , ) _snake_case : str = model( __a , attention_mask=__a , token_type_ids=__a , encoder_hidden_states=__a , ) _snake_case : List[str] = model(__a , attention_mask=__a , token_type_ids=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self : str , lowerCamelCase_ : Any , lowerCamelCase_ : Tuple , lowerCamelCase_ : Tuple , lowerCamelCase_ : Dict , lowerCamelCase_ : int , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' _snake_case : Any = MraForMaskedLM(config=__a ) model.to(__a ) model.eval() _snake_case : Any = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self : Union[str, Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : str , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' _snake_case : Optional[int] = MraForQuestionAnswering(config=__a ) model.to(__a ) model.eval() _snake_case : int = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self : Dict , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : str , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Tuple ): '''simple docstring''' _snake_case : List[str] = self.num_labels _snake_case : Dict = MraForSequenceClassification(__a ) model.to(__a ) model.eval() _snake_case : Optional[int] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self : Optional[Any] , lowerCamelCase_ : int , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : str , lowerCamelCase_ : List[Any] ): '''simple docstring''' _snake_case : int = self.num_labels _snake_case : int = MraForTokenClassification(config=__a ) model.to(__a ) model.eval() _snake_case : str = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self : int , lowerCamelCase_ : List[str] , lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Any ): '''simple docstring''' _snake_case : Optional[Any] = self.num_choices _snake_case : Dict = MraForMultipleChoice(config=__a ) model.to(__a ) model.eval() _snake_case : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case : Optional[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case : str = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self : List[str] ): '''simple docstring''' _snake_case : Union[str, Any] = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) : Optional[int] = config_and_inputs _snake_case : str = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowercase ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" _UpperCamelCase : int = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) _UpperCamelCase : Union[str, Any] = False _UpperCamelCase : Tuple = False _UpperCamelCase : List[Any] = False _UpperCamelCase : int = False _UpperCamelCase : Any = () def __UpperCAmelCase ( self : Union[str, Any] ): '''simple docstring''' _snake_case : Optional[Any] = MraModelTester(self ) _snake_case : Optional[int] = ConfigTester(self , config_class=__a , hidden_size=37 ) def __UpperCAmelCase ( self : Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self : Tuple ): '''simple docstring''' _snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self : Any ): '''simple docstring''' _snake_case : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _snake_case : Tuple = type self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self : List[str] ): '''simple docstring''' _snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__a ) def __UpperCAmelCase ( self : Tuple ): '''simple docstring''' _snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__a ) def __UpperCAmelCase ( self : Optional[int] ): '''simple docstring''' _snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__a ) def __UpperCAmelCase ( self : Dict ): '''simple docstring''' _snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__a ) def __UpperCAmelCase ( self : Optional[Any] ): '''simple docstring''' _snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__a ) @slow def __UpperCAmelCase ( self : Optional[Any] ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : Optional[int] = MraModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @unittest.skip(reason='MRA does not output attentions' ) def __UpperCAmelCase ( self : Any ): '''simple docstring''' return @require_torch class lowercase ( unittest.TestCase ): """simple docstring""" @slow def __UpperCAmelCase ( self : Union[str, Any] ): '''simple docstring''' _snake_case : Any = MraModel.from_pretrained('uw-madison/mra-base-512-4' ) _snake_case : int = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): _snake_case : Optional[int] = model(__a )[0] _snake_case : int = torch.Size((1, 2_56, 7_68) ) self.assertEqual(output.shape , __a ) _snake_case : Union[str, Any] = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self : List[Any] ): '''simple docstring''' _snake_case : Dict = MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4' ) _snake_case : str = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): _snake_case : int = model(__a )[0] _snake_case : int = 5_02_65 _snake_case : Union[str, Any] = torch.Size((1, 2_56, vocab_size) ) self.assertEqual(output.shape , __a ) _snake_case : Optional[int] = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self : Any ): '''simple docstring''' _snake_case : str = MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3' ) _snake_case : Union[str, Any] = torch.arange(40_96 ).unsqueeze(0 ) with torch.no_grad(): _snake_case : Dict = model(__a )[0] _snake_case : str = 5_02_65 _snake_case : Optional[int] = torch.Size((1, 40_96, vocab_size) ) self.assertEqual(output.shape , __a ) _snake_case : List[str] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1e-4 ) )
304
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets lowerCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) lowerCAmelCase_ : Tuple = '\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n author = "Moosavi, Nafise Sadat and\n Strube, Michael",\n booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/P16-1060",\n doi = "10.18653/v1/P16-1060",\n pages = "632--642",\n}\n\n' lowerCAmelCase_ : Union[str, Any] = '\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n' lowerCAmelCase_ : Union[str, Any] = '\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting \'keep_singletons=False\', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n \'mentions\': mentions\n \'muc\': MUC metric [Vilain et al, 1995]\n \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n \'ceafe\': CEAFe [Luo et al., 2005]\n \'lea\': LEA [Moosavi and Strube, 2016]\n \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric(\'coval\')\n >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\',\n ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\',\n ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\',\n ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\',\n ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\',\n ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n' def _lowerCamelCase ( lowercase : Tuple , lowercase : List[Any] , lowercase : Optional[int]=False , lowercase : Dict=False , lowercase : Optional[int]=True , lowercase : Union[str, Any]=False , lowercase : int="dummy_doc" ) -> Union[str, Any]: _a = {doc: key_lines} _a = {doc: sys_lines} _a = {} _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a , _a = reader.get_doc_mentions(lowercase , key_doc_lines[doc] , lowercase ) key_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) _a , _a = reader.get_doc_mentions(lowercase , sys_doc_lines[doc] , lowercase ) sys_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) if remove_nested: _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters _a = reader.get_mention_assignments(lowercase , lowercase ) _a = reader.get_mention_assignments(lowercase , lowercase ) _a = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( "Number of removed nested coreferring mentions in the key " F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( "Number of resulting singleton clusters in the key " F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' "files, respectively" ) return doc_coref_infos def _lowerCamelCase ( lowercase : List[Any] , lowercase : Any , lowercase : Optional[Any] , lowercase : Union[str, Any] , lowercase : Any , lowercase : List[str] , lowercase : Dict ) -> str: _a = get_coref_infos(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) _a = {} _a = 0 _a = 0 for name, metric in metrics: _a , _a , _a = evaluator.evaluate_documents(lowercase , lowercase , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} ) logger.info( name.ljust(10 ) , F'Recall: {recall * 100:.2f}' , F' Precision: {precision * 100:.2f}' , F' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: _a = (conll / 3) * 100 logger.info(F'CoNLL score: {conll:.2f}' ) output_scores.update({"conll_score": conll} ) return output_scores def _lowerCamelCase ( lowercase : Any ) -> str: _a = False for line in key_lines: if not line.startswith("#" ): if len(line.split() ) > 6: _a = line.split()[5] if not parse_col == "-": _a = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE (datasets.Metric ): """simple docstring""" def UpperCamelCase__ ( self : str ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Sequence(datasets.Value("string" ) ), } ) , codebase_urls=["https://github.com/ns-moosavi/coval"] , reference_urls=[ "https://github.com/ns-moosavi/coval", "https://www.aclweb.org/anthology/P16-1060", "http://www.conll.cemantix.org/2012/data.html", ] , ) def UpperCamelCase__ ( self : int , __a : Any , __a : int , __a : Optional[Any]=True , __a : Optional[Any]=False , __a : str=False , __a : List[str]=False ): _a = [ ("mentions", evaluator.mentions), ("muc", evaluator.muc), ("bcub", evaluator.b_cubed), ("ceafe", evaluator.ceafe), ("lea", evaluator.lea), ] if min_span: _a = util.check_gold_parse_annotation(__a ) if not has_gold_parse: raise NotImplementedError("References should have gold parse annotation to use 'min_span'." ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" _a = evaluate( key_lines=__a , sys_lines=__a , metrics=__a , NP_only=__a , remove_nested=__a , keep_singletons=__a , min_span=__a , ) return score
692
0
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( lowerCamelCase_ ): __lowerCamelCase = (DDIMParallelScheduler,) __lowerCamelCase = (('eta', 0.0), ('num_inference_steps', 50)) def __UpperCAmelCase ( self , **_lowerCAmelCase ): UpperCAmelCase__ : Optional[Any] = { """num_train_timesteps""": 1000, """beta_start""": 0.0_0_0_1, """beta_end""": 0.0_2, """beta_schedule""": """linear""", """clip_sample""": True, } config.update(**__a ) return config def __UpperCAmelCase ( self , **_lowerCAmelCase ): UpperCAmelCase__ : int = self.scheduler_classes[0] UpperCAmelCase__ : int = self.get_scheduler_config(**__a ) UpperCAmelCase__ : int = scheduler_class(**__a ) UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = 10, 0.0 UpperCAmelCase__ : Union[str, Any] = self.dummy_model() UpperCAmelCase__ : str = self.dummy_sample_deter scheduler.set_timesteps(__a ) for t in scheduler.timesteps: UpperCAmelCase__ : str = model(__a , __a ) UpperCAmelCase__ : str = scheduler.step(__a , __a , __a , __a ).prev_sample return sample def __UpperCAmelCase ( self ): for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=__a ) def __UpperCAmelCase ( self ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__a ) UpperCAmelCase__ : Optional[Any] = self.scheduler_classes[0] UpperCAmelCase__ : List[str] = self.get_scheduler_config(steps_offset=1 ) UpperCAmelCase__ : Any = scheduler_class(**__a ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def __UpperCAmelCase ( self ): for beta_start, beta_end in zip([0.0_0_0_1, 0.0_0_1, 0.0_1, 0.1] , [0.0_0_2, 0.0_2, 0.2, 2] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def __UpperCAmelCase ( self ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__a ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def __UpperCAmelCase ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__a ) def __UpperCAmelCase ( self ): for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__a ) def __UpperCAmelCase ( self ): for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__a ) def __UpperCAmelCase ( self ): self.check_over_configs(thresholding=__a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__a , prediction_type=__a , sample_max_value=__a , ) def __UpperCAmelCase ( self ): for t in [1, 10, 49]: self.check_over_forward(time_step=__a ) def __UpperCAmelCase ( self ): for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__a , num_inference_steps=__a ) def __UpperCAmelCase ( self ): for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__a , eta=__a ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.scheduler_classes[0] UpperCAmelCase__ : str = self.get_scheduler_config() UpperCAmelCase__ : int = scheduler_class(**__a ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.1_4_7_7_1 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.3_2_4_6_0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.0_0_9_7_9 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.0_2 ) ) < 1e-5 def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = self.scheduler_classes[0] UpperCAmelCase__ : Union[str, Any] = self.get_scheduler_config() UpperCAmelCase__ : int = scheduler_class(**__a ) UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = 10, 0.0 scheduler.set_timesteps(__a ) UpperCAmelCase__ : int = self.dummy_model() UpperCAmelCase__ : List[str] = self.dummy_sample_deter UpperCAmelCase__ : Union[str, Any] = self.dummy_sample_deter + 0.1 UpperCAmelCase__ : Dict = self.dummy_sample_deter - 0.1 UpperCAmelCase__ : Optional[int] = samplea.shape[0] UpperCAmelCase__ : Any = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCAmelCase__ : str = torch.arange(__a )[0:3, None].repeat(1 , __a ) UpperCAmelCase__ : Dict = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCAmelCase__ : Optional[int] = scheduler.batch_step_no_noise(__a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __a ) UpperCAmelCase__ : List[str] = torch.sum(torch.abs(__a ) ) UpperCAmelCase__ : Union[str, Any] = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1_1_4_7.7_9_0_4 ) < 1e-2 assert abs(result_mean.item() - 0.4_9_8_2 ) < 1e-3 def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.full_loop() UpperCAmelCase__ : List[Any] = torch.sum(torch.abs(__a ) ) UpperCAmelCase__ : Optional[Any] = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1_7_2.0_0_6_7 ) < 1e-2 assert abs(result_mean.item() - 0.2_2_3_9_6_7 ) < 1e-3 def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = self.full_loop(prediction_type="""v_prediction""" ) UpperCAmelCase__ : Union[str, Any] = torch.sum(torch.abs(__a ) ) UpperCAmelCase__ : Tuple = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 5_2.5_3_0_2 ) < 1e-2 assert abs(result_mean.item() - 0.0_6_8_4 ) < 1e-3 def __UpperCAmelCase ( self ): # We specify different beta, so that the first alpha is 0.99 UpperCAmelCase__ : List[Any] = self.full_loop(set_alpha_to_one=__a , beta_start=0.0_1 ) UpperCAmelCase__ : List[str] = torch.sum(torch.abs(__a ) ) UpperCAmelCase__ : Tuple = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1_4_9.8_2_9_5 ) < 1e-2 assert abs(result_mean.item() - 0.1_9_5_1 ) < 1e-3 def __UpperCAmelCase ( self ): # We specify different beta, so that the first alpha is 0.99 UpperCAmelCase__ : List[Any] = self.full_loop(set_alpha_to_one=__a , beta_start=0.0_1 ) UpperCAmelCase__ : Tuple = torch.sum(torch.abs(__a ) ) UpperCAmelCase__ : Dict = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1_4_9.0_7_8_4 ) < 1e-2 assert abs(result_mean.item() - 0.1_9_4_1 ) < 1e-3
79
'''simple docstring''' import math def _lowerCamelCase ( lowercase : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowercase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCamelCase ( lowercase : float = 0.1 ) -> int: _a = 3 _a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowercase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A = logging.get_logger(__name__) class _lowerCAmelCase ( lowerCamelCase_ ): """simple docstring""" __magic_name__ :Optional[int] = ["""pixel_values"""] def __init__( self , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = PIL.Image.BICUBIC , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 1 / 2_5_5 , __UpperCAmelCase = True , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__a ) lowerCAmelCase__ :str = size if size is not None else {'height': 2_5_6, 'width': 2_5_6} lowerCAmelCase__ :str = get_size_dict(__a ) lowerCAmelCase__ :List[Any] = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} lowerCAmelCase__ :Any = get_size_dict(__a , param_name='crop_size' ) lowerCAmelCase__ :int = do_resize lowerCAmelCase__ :Dict = size lowerCAmelCase__ :Dict = resample lowerCAmelCase__ :Tuple = do_center_crop lowerCAmelCase__ :Optional[int] = crop_size lowerCAmelCase__ :str = do_rescale lowerCAmelCase__ :Dict = rescale_factor lowerCAmelCase__ :List[str] = do_normalize lowerCAmelCase__ :Dict = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ :List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = PIL.Image.BICUBIC , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :str = get_size_dict(__a ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}" ) return resize( __a , size=(size['height'], size['width']) , resample=__a , data_format=__a , **__a ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :str = get_size_dict(__a ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}" ) return center_crop(__a , size=(size['height'], size['width']) , data_format=__a , **__a ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' return rescale(__a , scale=__a , data_format=__a , **__a ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' return normalize(__a , mean=__a , std=__a , data_format=__a , **__a ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase=None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ :Any = resample if resample is not None else self.resample lowerCAmelCase__ :Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCAmelCase__ :List[str] = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ :Dict = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ :str = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ :Dict = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ :Tuple = image_std if image_std is not None else self.image_std lowerCAmelCase__ :Any = size if size is not None else self.size lowerCAmelCase__ :Optional[int] = get_size_dict(__a ) lowerCAmelCase__ :Optional[Any] = crop_size if crop_size is not None else self.crop_size lowerCAmelCase__ :Union[str, Any] = get_size_dict(__a , param_name='crop_size' ) lowerCAmelCase__ :Dict = make_list_of_images(__a ) if not valid_images(__a ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. lowerCAmelCase__ :Dict = [to_numpy_array(__a ) for image in images] if do_resize: lowerCAmelCase__ :Dict = [self.resize(image=__a , size=__a , resample=__a ) for image in images] if do_center_crop: lowerCAmelCase__ :Tuple = [self.center_crop(image=__a , size=__a ) for image in images] if do_rescale: lowerCAmelCase__ :Optional[int] = [self.rescale(image=__a , scale=__a ) for image in images] if do_normalize: lowerCAmelCase__ :int = [self.normalize(image=__a , mean=__a , std=__a ) for image in images] lowerCAmelCase__ :Dict = [to_channel_dimension_format(__a , __a ) for image in images] lowerCAmelCase__ :List[str] = {'pixel_values': images} return BatchFeature(data=__a , tensor_type=__a )
93
'''simple docstring''' import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(CMStochasticIterativeScheduler,) __a =10 def UpperCamelCase__ ( self : Union[str, Any] , **__a : str ): _a = { "num_train_timesteps": 2_01, "sigma_min": 0.002, "sigma_max": 80.0, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[Any] ): _a = 10 _a = self.get_scheduler_config() _a = self.scheduler_classes[0](**__a ) scheduler.set_timesteps(__a ) _a = scheduler.timesteps[0] _a = scheduler.timesteps[1] _a = self.dummy_sample _a = 0.1 * sample _a = scheduler.step(__a , __a , __a ).prev_sample _a = scheduler.step(__a , __a , __a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase__ ( self : Any ): for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : int ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = 1 scheduler.set_timesteps(__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(__a ): # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [1_06, 0] scheduler.set_timesteps(timesteps=__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCamelCase__ ( self : List[Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 15, 0] with self.assertRaises(__a , msg="`timesteps` must be in descending order." ): scheduler.set_timesteps(timesteps=__a ) def UpperCamelCase__ ( self : Tuple ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 1, 0] _a = len(__a ) with self.assertRaises(__a , msg="Can only pass one of `num_inference_steps` or `timesteps`." ): scheduler.set_timesteps(num_inference_steps=__a , timesteps=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [scheduler.config.num_train_timesteps] with self.assertRaises( __a , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=__a )
692
0
"""simple docstring""" class __snake_case : def __init__( self : Tuple , __lowerCAmelCase : list[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = len(__a ) _lowerCamelCase : str = [0] * len_array if len_array > 0: _lowerCamelCase : Dict = array[0] for i in range(1 , __a ): _lowerCamelCase : Any = self.prefix_sum[i - 1] + array[i] def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : int ): """simple docstring""" if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[Any] = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(__a ) return False if __name__ == "__main__": import doctest doctest.testmod()
83
'''simple docstring''' import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : int , **__a : Optional[Any] ): warnings.warn( "The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use YolosImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' from __future__ import annotations from math import pi def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> dict[str, float]: if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if inductance < 0: raise ValueError('Inductance cannot be negative' ) if frequency < 0: raise ValueError('Frequency cannot be negative' ) if reactance < 0: raise ValueError('Inductive reactance cannot be negative' ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
270
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) lowerCAmelCase_ : str = { 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='timesformer' def __init__( self : Optional[int] , __a : Optional[int]=2_24 , __a : Tuple=16 , __a : int=3 , __a : Union[str, Any]=8 , __a : Union[str, Any]=7_68 , __a : List[str]=12 , __a : Union[str, Any]=12 , __a : Optional[Any]=30_72 , __a : Tuple="gelu" , __a : str=0.0 , __a : List[Any]=0.0 , __a : Any=0.02 , __a : List[str]=1e-6 , __a : Any=True , __a : Union[str, Any]="divided_space_time" , __a : str=0 , **__a : Tuple , ): super().__init__(**__a ) _a = image_size _a = patch_size _a = num_channels _a = num_frames _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = initializer_range _a = layer_norm_eps _a = qkv_bias _a = attention_type _a = drop_path_rate
692
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCamelCase = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
96
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase__ ( self : Dict ): _a = 1 _a = 3 _a = (32, 32) _a = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__a ) return image @property def UpperCamelCase__ ( self : Dict ): torch.manual_seed(0 ) _a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def UpperCamelCase__ ( self : Optional[int] ): torch.manual_seed(0 ) _a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def UpperCamelCase__ ( self : Optional[Any] ): torch.manual_seed(0 ) _a = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=50_06 , ) return RobertaSeriesModelWithTransformation(__a ) @property def UpperCamelCase__ ( self : str ): def extract(*__a : Tuple , **__a : str ): class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict ): _a = torch.ones([0] ) def UpperCamelCase__ ( self : List[str] , __a : Dict ): self.pixel_values.to(__a ) return self return Out() return extract def UpperCamelCase__ ( self : Optional[int] ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) _a = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , ) _a = output.images _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , return_dict=__a , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) # put models in fp16 _a = unet.half() _a = vae.half() _a = bert.half() # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , num_inference_steps=2 , output_type="np" , image=__a , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 _a = init_image.resize((7_60, 5_04) ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] _a = image[2_55:2_58, 3_83:3_86, -1] assert image.shape == (5_04, 7_60, 3) _a = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : Union[str, Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) _a = init_image.resize((7_68, 5_12) ) _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] assert image.shape == (5_12, 7_68, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
692
0
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets lowercase_ = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' lowercase_ = '\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n' lowercase_ = '\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n "raw_values" : Returns a full set of errors in case of multioutput input.\n\n "uniform_average" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric("mse")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {\'mse\': 0.6123724356957945}\n\n If you\'re using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric("mse", "multilist")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mse\': array([0.41666667, 1. ])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ (datasets.Metric ): """simple docstring""" def a ( self : Dict )-> int: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] , ) def a ( self : Any )-> int: """simple docstring""" if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def a ( self : List[str] , a_ : Optional[int] , a_ : Optional[int] , a_ : List[str]=None , a_ : Optional[int]="uniform_average" , a_ : List[Any]=True )-> Optional[int]: """simple docstring""" UpperCAmelCase_ : int = mean_squared_error( __a , __a , sample_weight=__a , multioutput=__a , squared=__a ) return {"mse": mse}
470
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : int , *__a : Tuple , **__a : Optional[Any] ): warnings.warn( "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DPTImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node A : Dict = 4 A : List[Any] = 3 class a_ ( lowerCamelCase_ ): pass def UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Union[str, Any]: for shard in shards: for i in range(SCREAMING_SNAKE_CASE_ ): yield {"i": i, "shard": shard} def UpperCamelCase__ ( ) -> List[str]: _lowercase = int(os.environ["""RANK"""] ) _lowercase = int(os.environ["""WORLD_SIZE"""] ) _lowercase = ArgumentParser() parser.add_argument("""--streaming""" , type=SCREAMING_SNAKE_CASE_ ) parser.add_argument("""--local_rank""" , type=SCREAMING_SNAKE_CASE_ ) parser.add_argument("""--num_workers""" , type=SCREAMING_SNAKE_CASE_ , default=0 ) _lowercase = parser.parse_args() _lowercase = args.streaming _lowercase = args.num_workers _lowercase = {"""shards""": [f"""shard_{shard_idx}""" for shard_idx in range(SCREAMING_SNAKE_CASE_ )]} _lowercase = IterableDataset.from_generator(SCREAMING_SNAKE_CASE_ , gen_kwargs=SCREAMING_SNAKE_CASE_ ) if not streaming: _lowercase = Dataset.from_list(list(SCREAMING_SNAKE_CASE_ ) ) _lowercase = split_dataset_by_node(SCREAMING_SNAKE_CASE_ , rank=SCREAMING_SNAKE_CASE_ , world_size=SCREAMING_SNAKE_CASE_ ) _lowercase = torch.utils.data.DataLoader(SCREAMING_SNAKE_CASE_ , num_workers=SCREAMING_SNAKE_CASE_ ) _lowercase = NUM_SHARDS * NUM_ITEMS_PER_SHARD _lowercase = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) _lowercase = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(f"""local_size {local_size} != expected_local_size {expected_local_size}""" ) if __name__ == "__main__": main()
287
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerCamelCase ( lowercase : Any ) -> Tuple: _a = filter(lambda lowercase : p.requires_grad , model.parameters() ) _a = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase_ : str = logging.getLogger(__name__) def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Dict: if metric == "rouge2": _a = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": _a = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": _a = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' " function." ) _a = ModelCheckpoint( dirpath=lowercase , filename=lowercase , monitor=F'val_{metric}' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def _lowerCamelCase ( lowercase : Optional[int] , lowercase : List[str] ) -> Dict: return EarlyStopping( monitor=F'val_{metric}' , mode="min" if "loss" in metric else "max" , patience=lowercase , verbose=lowercase , ) class __SCREAMING_SNAKE_CASE (pl.Callback ): """simple docstring""" def UpperCamelCase__ ( self : Optional[Any] , __a : Dict , __a : Optional[int] ): _a = {f'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Optional[int]=True ): logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) _a = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results _a = Path(pl_module.hparams.output_dir ) if type_path == "test": _a = od / "test_results.txt" _a = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _a = od / f'{type_path}_results/{trainer.global_step:05d}.txt' _a = od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue _a = metrics[key] if isinstance(__a , torch.Tensor ): _a = val.item() _a = f'{key}: {val:.6f}\n' writer.write(__a ) if not save_generations: return if "preds" in metrics: _a = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def UpperCamelCase__ ( self : List[str] , __a : Optional[Any] , __a : List[str] ): try: _a = pl_module.model.model.num_parameters() except AttributeError: _a = pl_module.model.num_parameters() _a = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} ) @rank_zero_only def UpperCamelCase__ ( self : Dict , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def UpperCamelCase__ ( self : Any , __a : pl.Trainer , __a : Optional[int] ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
692
0
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() lowercase__ : Dict = logging.get_logger(__name__) lowercase__ : int = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } lowercase__ : int = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def __lowercase ( _a , _a , _a , _a , _a ): for attribute in key.split('''.''' ): snake_case_ : Optional[Any] = getattr(_a , _a ) if weight_type is not None: snake_case_ : Optional[int] = getattr(_a , _a ).shape else: snake_case_ : Union[str, Any] = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": snake_case_ : List[Any] = value elif weight_type == "weight_g": snake_case_ : Union[str, Any] = value elif weight_type == "weight_v": snake_case_ : Any = value elif weight_type == "bias": snake_case_ : List[str] = value else: snake_case_ : int = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __lowercase ( _a , _a ): snake_case_ : Any = [] snake_case_ : Any = fairseq_model.state_dict() snake_case_ : List[str] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight snake_case_ : Optional[Any] = None for name, value in fairseq_dict.items(): snake_case_ : Dict = False if "conv_layers" in name: load_conv_layer( _a , _a , _a , _a , hf_model.config.feat_extract_norm == '''group''' , ) snake_case_ : Optional[Any] = True elif name.split('''.''' )[0] == "proj": snake_case_ : Optional[int] = fairseq_model.proj snake_case_ : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: snake_case_ : str = True if "*" in mapped_key: snake_case_ : str = name.split(_a )[0].split('''.''' )[-2] snake_case_ : Any = mapped_key.replace('''*''' , _a ) if "weight_g" in name: snake_case_ : Union[str, Any] = '''weight_g''' elif "weight_v" in name: snake_case_ : List[Any] = '''weight_v''' elif "bias" in name: snake_case_ : Optional[int] = '''bias''' elif "weight" in name: snake_case_ : Any = '''weight''' else: snake_case_ : str = None set_recursively(_a , _a , _a , _a , _a ) continue if not is_used: unused_weights.append(_a ) logger.warning(f"Unused weights: {unused_weights}" ) return proj_weight def __lowercase ( _a , _a , _a , _a , _a ): snake_case_ : Union[str, Any] = full_name.split('''conv_layers.''' )[-1] snake_case_ : Optional[Any] = name.split('''.''' ) snake_case_ : Any = int(items[0] ) snake_case_ : Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) snake_case_ : Union[str, Any] = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) snake_case_ : Dict = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) snake_case_ : Any = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) snake_case_ : Optional[int] = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_a ) def __lowercase ( _a ): snake_case_, snake_case_ : Optional[Any] = emb.weight.shape snake_case_ : str = nn.Linear(_a , _a , bias=_a ) snake_case_ : List[Any] = emb.weight.data return lin_layer def __lowercase ( _a ): with open(_a , '''r''' , encoding='''utf-8''' ) as f: snake_case_ : Optional[Any] = f.readlines() snake_case_ : List[Any] = [line.split(''' ''' )[0] for line in lines] snake_case_ : Any = len(_a ) snake_case_ : str = { '''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3, } vocab_dict.update(dict(zip(_a , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def __lowercase ( _a , _a , _a , _a , _a , _a , _a , ): snake_case_ : Union[str, Any] = WavaVecaConfig.from_pretrained(_a ) snake_case_ : Any = SpeechaTextaConfig.from_pretrained( _a , vocab_size=_a , decoder_layers=_a , do_stable_layer_norm=_a ) snake_case_ : Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_a , return_attention_mask=_a , ) snake_case_, snake_case_, snake_case_ : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) snake_case_ : Any = model[0].eval() # set weights for wav2vec2 encoder snake_case_ : Tuple = WavaVecaModel(_a ) snake_case_ : Optional[int] = recursively_load_weights_wavaveca(model.encoder , _a ) snake_case_ : List[str] = SpeechaTextaForCausalLM(_a ) snake_case_, snake_case_ : Union[str, Any] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_a ) # set output linear layer unexpected_keys.remove('''embed_out''' ) snake_case_ : Union[str, Any] = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(f"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) snake_case_ : Dict = SpeechEncoderDecoderModel(encoder=_a , decoder=_a ) snake_case_ : List[Any] = False # add projection layer snake_case_ : List[Any] = nn.Parameter(projection_layer.weight ) snake_case_ : Optional[Any] = nn.Parameter(projection_layer.bias ) snake_case_ : Any = create_vocab_dict(_a ) with open(os.path.join(_a , '''vocab.json''' ) , '''w''' ) as fp: json.dump(_a , _a ) snake_case_ : Optional[Any] = SpeechaTextaTokenizer(os.path.join(_a , '''vocab.json''' ) ) tokenizer.save_pretrained(_a ) snake_case_ : Any = hf_wavavec.config.to_dict() snake_case_ : Optional[int] = tokenizer.pad_token_id snake_case_ : Tuple = tokenizer.bos_token_id snake_case_ : Tuple = tokenizer.eos_token_id snake_case_ : Union[str, Any] = '''speech_to_text_2''' snake_case_ : List[Any] = '''wav2vec2''' snake_case_ : Optional[int] = SpeechEncoderDecoderConfig.from_dict(_a ) hf_wavavec.save_pretrained(_a ) feature_extractor.save_pretrained(_a ) if __name__ == "__main__": lowercase__ : List[Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=1_02_24, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') lowercase__ : List[Any] = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
123
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase_ : Any = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys lowerCAmelCase_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
692
0
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging A = logging.get_logger(__name__) logging.set_verbosity_info() def lowerCamelCase ( UpperCamelCase : str , UpperCamelCase : str ) -> Union[str, Any]: if "xprophetnet" in prophetnet_checkpoint_path: _lowerCamelCase = XLMProphetNetForConditionalGenerationOld.from_pretrained(UpperCamelCase ) _lowerCamelCase , _lowerCamelCase = XLMProphetNetForConditionalGeneration.from_pretrained( UpperCamelCase , output_loading_info=UpperCamelCase ) else: _lowerCamelCase = ProphetNetForConditionalGenerationOld.from_pretrained(UpperCamelCase ) _lowerCamelCase , _lowerCamelCase = ProphetNetForConditionalGeneration.from_pretrained( UpperCamelCase , output_loading_info=UpperCamelCase ) _lowerCamelCase = ['key_proj', 'value_proj', 'query_proj'] _lowerCamelCase = { 'self_attn': 'ngram_self_attn', 'cross_attn': 'encoder_attn', 'cross_attn_layer_norm': 'encoder_attn_layer_norm', 'feed_forward_layer_norm': 'final_layer_norm', 'feed_forward': '', 'intermediate': 'fc1', 'output': 'fc2', 'key_proj': 'k_proj', 'query_proj': 'q_proj', 'value_proj': 'v_proj', 'word_embeddings': 'embed_tokens', 'embeddings_layer_norm': 'emb_layer_norm', 'relative_pos_embeddings': 'relative_linear', 'ngram_embeddings': 'ngram_input_embed', 'position_embeddings': 'embed_positions', } for key in loading_info["missing_keys"]: _lowerCamelCase = key.split('.' ) if attributes[0] == "lm_head": _lowerCamelCase = prophet _lowerCamelCase = prophet_old else: _lowerCamelCase = prophet.prophetnet _lowerCamelCase = prophet_old.model _lowerCamelCase = False for attribute in attributes: if attribute in mapping: _lowerCamelCase = mapping[attribute] if not hasattr(UpperCamelCase , UpperCamelCase ) and len(UpperCamelCase ) > 0: _lowerCamelCase = attribute elif hasattr(UpperCamelCase , UpperCamelCase ): _lowerCamelCase = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" _lowerCamelCase = old_model.weight logger.info(F"""{attribute} is initialized.""" ) _lowerCamelCase = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" _lowerCamelCase = old_model.bias logger.info(F"""{attribute} is initialized""" ) _lowerCamelCase = True break elif attribute in special_keys and hasattr(UpperCamelCase , 'in_proj_weight' ): _lowerCamelCase = old_model.in_proj_weight.shape[0] // 3 _lowerCamelCase = getattr(UpperCamelCase , UpperCamelCase ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": _lowerCamelCase = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) _lowerCamelCase = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": _lowerCamelCase = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) _lowerCamelCase = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": _lowerCamelCase = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) _lowerCamelCase = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) _lowerCamelCase = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 5_12, "We want 512 position_embeddings." _lowerCamelCase = nn.Parameter(old_model.embed_positions.weight[:5_12, :] ) _lowerCamelCase = True break if attribute.isdigit(): _lowerCamelCase = model[int(UpperCamelCase )] _lowerCamelCase = old_model[int(UpperCamelCase )] else: _lowerCamelCase = getattr(UpperCamelCase , UpperCamelCase ) if old_attribute == "": _lowerCamelCase = old_model else: if not hasattr(UpperCamelCase , UpperCamelCase ): raise ValueError(F"""{old_model} does not have {old_attribute}""" ) _lowerCamelCase = getattr(UpperCamelCase , UpperCamelCase ) if not is_key_init: raise ValueError(F"""{key} was not correctly initialized!""" ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) prophet.save_pretrained(UpperCamelCase ) if __name__ == "__main__": A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--prophetnet_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) A = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
544
'''simple docstring''' import gc import threading import time import psutil import torch class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[Any] ): _a = psutil.Process() _a = False def UpperCamelCase__ ( self : Tuple ): _a = -1 while True: _a = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def UpperCamelCase__ ( self : List[Any] ): _a = True _a = threading.Thread(target=self.peak_monitor ) _a = True self.thread.start() def UpperCamelCase__ ( self : Optional[int] ): _a = False self.thread.join() return self.cpu_memory_peak lowerCAmelCase_ : List[Any] = PeakCPUMemory() def _lowerCamelCase ( ) -> Tuple: # Time _a = {"time": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem _a = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): _a = torch.cuda.memory_allocated(lowercase ) torch.cuda.reset_peak_memory_stats() return measures def _lowerCamelCase ( lowercase : Any ) -> int: # Time _a = {"time": time.time() - start_measures["time"]} gc.collect() torch.cuda.empty_cache() # CPU mem _a = (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20 _a = (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): _a = (torch.cuda.memory_allocated(lowercase ) - start_measures[str(lowercase )]) / 2**20 _a = (torch.cuda.max_memory_allocated(lowercase ) - start_measures[str(lowercase )]) / 2**20 return measures def _lowerCamelCase ( lowercase : Optional[int] , lowercase : Dict ) -> str: print(F'{description}:' ) print(F'- Time: {measures["time"]:.2f}s' ) for i in range(torch.cuda.device_count() ): print(F'- GPU {i} allocated: {measures[str(lowercase )]:.2f}MiB' ) _a = measures[F'{i}-peak'] print(F'- GPU {i} peak: {peak:.2f}MiB' ) print(F'- CPU RAM allocated: {measures["cpu"]:.2f}MiB' ) print(F'- CPU RAM peak: {measures["cpu-peak"]:.2f}MiB' )
692
0
from __future__ import annotations from typing import Generic, TypeVar A : Optional[Any] = TypeVar('T') class UpperCamelCase( Generic[T] ): def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE : T ) -> Union[str, Any]: '''simple docstring''' __snake_case = data __snake_case = self __snake_case = 0 class UpperCamelCase( Generic[T] ): def __init__( self : Dict ) -> Dict: '''simple docstring''' __snake_case = {} def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE : T ) -> Dict: '''simple docstring''' __snake_case = DisjointSetTreeNode(__a ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE : T ) -> str: '''simple docstring''' __snake_case = self.map[data] if elem_ref != elem_ref.parent: __snake_case = self.find_set(elem_ref.parent.data ) return elem_ref.parent def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE : DisjointSetTreeNode[T] , SCREAMING_SNAKE_CASE : DisjointSetTreeNode[T] ) -> List[Any]: '''simple docstring''' if nodea.rank > nodea.rank: __snake_case = nodea else: __snake_case = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE : T , SCREAMING_SNAKE_CASE : T ) -> str: '''simple docstring''' self.link(self.find_set(__a ) , self.find_set(__a ) ) class UpperCamelCase( Generic[T] ): def __init__( self : Tuple ) -> int: '''simple docstring''' __snake_case = {} def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE : T ) -> Dict: '''simple docstring''' if node not in self.connections: __snake_case = {} def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE : T , SCREAMING_SNAKE_CASE : T , SCREAMING_SNAKE_CASE : int ) -> int: '''simple docstring''' self.add_node(__a ) self.add_node(__a ) __snake_case = weight __snake_case = weight def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' __snake_case = [] __snake_case = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : x[2] ) # creating the disjoint set __snake_case = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(__a ) # MST generation __snake_case = 0 __snake_case = 0 __snake_case = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: __snake_case , __snake_case , __snake_case = edges[index] index += 1 __snake_case = disjoint_set.find_set(__a ) __snake_case = disjoint_set.find_set(__a ) if parent_u != parent_v: num_edges += 1 graph.add_edge(__a , __a , __a ) disjoint_set.union(__a , __a ) return graph
371
'''simple docstring''' import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(DDIMParallelScheduler,) __a =(('eta', 0.0), ('num_inference_steps', 50)) def UpperCamelCase__ ( self : Optional[int] , **__a : Any ): _a = { "num_train_timesteps": 10_00, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[str] , **__a : Optional[int] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config(**__a ) _a = scheduler_class(**__a ) _a , _a = 10, 0.0 _a = self.dummy_model() _a = self.dummy_sample_deter scheduler.set_timesteps(__a ) for t in scheduler.timesteps: _a = model(__a , __a ) _a = scheduler.step(__a , __a , __a , __a ).prev_sample return sample def UpperCamelCase__ ( self : str ): for timesteps in [1_00, 5_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : Dict ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__a ) _a = self.scheduler_classes[0] _a = self.get_scheduler_config(steps_offset=1 ) _a = scheduler_class(**__a ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_01, 6_01, 4_01, 2_01, 1] ) ) def UpperCamelCase__ ( self : Tuple ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def UpperCamelCase__ ( self : Dict ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__a ) def UpperCamelCase__ ( self : Tuple ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def UpperCamelCase__ ( self : Dict ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__a ) def UpperCamelCase__ ( self : Optional[int] ): for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__a ) def UpperCamelCase__ ( self : Optional[Any] ): for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__a ) def UpperCamelCase__ ( self : List[Any] ): self.check_over_configs(thresholding=__a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__a , prediction_type=__a , sample_max_value=__a , ) def UpperCamelCase__ ( self : List[Any] ): for t in [1, 10, 49]: self.check_over_forward(time_step=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 5_00] ): self.check_over_forward(time_step=__a , num_inference_steps=__a ) def UpperCamelCase__ ( self : Union[str, Any] ): for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__a , eta=__a ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_20 , 4_00 ) - 0.14771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_80 , 9_60 ) - 0.32460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 , 4_86 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 , 9_98 ) - 0.02 ) ) < 1e-5 def UpperCamelCase__ ( self : List[str] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a , _a = 10, 0.0 scheduler.set_timesteps(__a ) _a = self.dummy_model() _a = self.dummy_sample_deter _a = self.dummy_sample_deter + 0.1 _a = self.dummy_sample_deter - 0.1 _a = samplea.shape[0] _a = torch.stack([samplea, samplea, samplea] , dim=0 ) _a = torch.arange(__a )[0:3, None].repeat(1 , __a ) _a = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _a = scheduler.batch_step_no_noise(__a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __a ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 1147.7904 ) < 1e-2 assert abs(result_mean.item() - 0.4982 ) < 1e-3 def UpperCamelCase__ ( self : List[str] ): _a = self.full_loop() _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 172.0067 ) < 1e-2 assert abs(result_mean.item() - 0.223967 ) < 1e-3 def UpperCamelCase__ ( self : str ): _a = self.full_loop(prediction_type="v_prediction" ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 52.5302 ) < 1e-2 assert abs(result_mean.item() - 0.0684 ) < 1e-3 def UpperCamelCase__ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _a = self.full_loop(set_alpha_to_one=__a , beta_start=0.01 ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 149.8295 ) < 1e-2 assert abs(result_mean.item() - 0.1951 ) < 1e-3 def UpperCamelCase__ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _a = self.full_loop(set_alpha_to_one=__a , beta_start=0.01 ) _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 149.0784 ) < 1e-2 assert abs(result_mean.item() - 0.1941 ) < 1e-3
692
0
import math lowercase_ : Tuple = 10 lowercase_ : Tuple = 7 lowercase_ : int = BALLS_PER_COLOUR * NUM_COLOURS def A__( __lowerCAmelCase = 20 ): _snake_case : Optional[int] = math.comb(__lowerCAmelCase , __lowerCAmelCase ) _snake_case : Tuple = math.comb(NUM_BALLS - BALLS_PER_COLOUR , __lowerCAmelCase ) _snake_case : Optional[int] = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(20))
304
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _lowerCamelCase ( lowercase : Any ) -> List[str]: return getitem, k def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Any: return setitem, k, v def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: return delitem, k def _lowerCamelCase ( lowercase : Tuple , lowercase : Dict , *lowercase : Union[str, Any] ) -> int: try: return fun(lowercase , *lowercase ), None except Exception as e: return None, e lowerCAmelCase_ : Optional[Any] = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) lowerCAmelCase_ : Optional[int] = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] lowerCAmelCase_ : int = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] lowerCAmelCase_ : List[Any] = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('key_a', 'val_b'), ] @pytest.mark.parametrize( "operations" , ( pytest.param(_add_items , id="add items" ), pytest.param(_overwrite_items , id="overwrite items" ), pytest.param(_delete_items , id="delete items" ), pytest.param(_access_absent_items , id="access absent items" ), pytest.param(_add_with_resize_up , id="add with resize up" ), pytest.param(_add_with_resize_down , id="add with resize down" ), ) , ) def _lowerCamelCase ( lowercase : Optional[int] ) -> Optional[int]: _a = HashMap(initial_block_size=4 ) _a = {} for _, (fun, *args) in enumerate(lowercase ): _a , _a = _run_operation(lowercase , lowercase , *lowercase ) _a , _a = _run_operation(lowercase , lowercase , *lowercase ) assert my_res == py_res assert str(lowercase ) == str(lowercase ) assert set(lowercase ) == set(lowercase ) assert len(lowercase ) == len(lowercase ) assert set(my.items() ) == set(py.items() ) def _lowerCamelCase ( ) -> str: def is_public(lowercase : str ) -> bool: return not name.startswith("_" ) _a = {name for name in dir({} ) if is_public(lowercase )} _a = {name for name in dir(HashMap() ) if is_public(lowercase )} assert dict_public_names > hash_public_names
692
0
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( lowerCamelCase_ ): def __init__( self , *_lowerCAmelCase , **_lowerCAmelCase ): warnings.warn( """The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use DeformableDetrImageProcessor instead.""" , __a , ) super().__init__(*__a , **__a )
79
'''simple docstring''' import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =PhobertTokenizer __a =False def UpperCamelCase__ ( self : int ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _a = ["T@@", "i", "I", "R@@", "r", "e@@"] _a = dict(zip(__a , range(len(__a ) ) ) ) _a = ["#version: 0.2", "l à</w>"] _a = {"unk_token": "<unk>"} _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(f'{token} {vocab_tokens[token]}\n' ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__a ) ) def UpperCamelCase__ ( self : str , **__a : List[str] ): kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ): _a = "Tôi là VinAI Research" _a = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>" return input_text, output_text def UpperCamelCase__ ( self : Dict ): _a = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _a = "Tôi là VinAI Research" _a = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split() _a = tokenizer.tokenize(__a ) print(__a ) self.assertListEqual(__a , __a ) _a = tokens + [tokenizer.unk_token] _a = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a )
692
0
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _lowerCAmelCase ( lowerCamelCase_ ): """simple docstring""" __magic_name__ :Tuple = ["""image_processor""", """tokenizer"""] __magic_name__ :Optional[Any] = """BlipImageProcessor""" __magic_name__ :List[Any] = """AutoTokenizer""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Tuple = False super().__init__(__a , __a ) lowerCAmelCase__ :Union[str, Any] = self.image_processor def __call__( self , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = False , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = 0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None: lowerCAmelCase__ :Tuple = self.tokenizer lowerCAmelCase__ :Dict = self.tokenizer( text=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_token_type_ids=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) return text_encoding # add pixel_values lowerCAmelCase__ :Union[str, Any] = self.image_processor(__a , return_tensors=__a ) if text is not None: lowerCAmelCase__ :Dict = self.tokenizer( text=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_token_type_ids=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) else: lowerCAmelCase__ :Optional[int] = None if text_encoding is not None: encoding_image_processor.update(__a ) return encoding_image_processor def snake_case ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.tokenizer.decode(*__a , **__a ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.tokenizer.model_input_names lowerCAmelCase__ :Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
93
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : str , *__a : Any , __a : str=None , __a : Union[str, Any]=None , **__a : Any ): super().__init__(*__a , **__a ) _a = eval_examples _a = post_process_function def UpperCamelCase__ ( self : Optional[Any] , __a : Dict=None , __a : Any=None , __a : str=None , __a : str = "eval" ): _a = self.eval_dataset if eval_dataset is None else eval_dataset _a = self.get_eval_dataloader(__a ) _a = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _a = self.compute_metrics _a = None _a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _a = time.time() try: _a = eval_loop( __a , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__a , metric_key_prefix=__a , ) finally: _a = compute_metrics _a = self.args.eval_batch_size * self.args.world_size if f'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( __a , __a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default _a = self.post_process_function(__a , __a , output.predictions ) _a = self.compute_metrics(__a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'{metric_key_prefix}_' ): _a = metrics.pop(__a ) metrics.update(output.metrics ) else: _a = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__a ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _a = self.callback_handler.on_evaluate(self.args , self.state , self.control , __a ) return metrics def UpperCamelCase__ ( self : Tuple , __a : Dict , __a : Optional[Any] , __a : Optional[Any]=None , __a : str = "test" ): _a = self.get_test_dataloader(__a ) # Temporarily disable metric computation, we will do it in the loop here. _a = self.compute_metrics _a = None _a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _a = time.time() try: _a = eval_loop( __a , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__a , metric_key_prefix=__a , ) finally: _a = compute_metrics _a = self.args.eval_batch_size * self.args.world_size if f'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( __a , __a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output _a = self.post_process_function(__a , __a , output.predictions , "predict" ) _a = self.compute_metrics(__a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'{metric_key_prefix}_' ): _a = metrics.pop(__a ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__a )
692
0
"""simple docstring""" from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class __snake_case ( lowerCamelCase_): snake_case__ : Any = "gptj" snake_case__ : Any = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Tuple , __lowerCAmelCase : str=5_0_4_0_0 , __lowerCAmelCase : int=2_0_4_8 , __lowerCAmelCase : Tuple=4_0_9_6 , __lowerCAmelCase : int=2_8 , __lowerCAmelCase : Tuple=1_6 , __lowerCAmelCase : Dict=6_4 , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Optional[int]="gelu_new" , __lowerCAmelCase : Optional[Any]=0.0 , __lowerCAmelCase : Union[str, Any]=0.0 , __lowerCAmelCase : Optional[int]=0.0 , __lowerCAmelCase : Optional[Any]=1E-5 , __lowerCAmelCase : int=0.02 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Dict=5_0_2_5_6 , __lowerCAmelCase : Dict=5_0_2_5_6 , __lowerCAmelCase : List[str]=False , **__lowerCAmelCase : str , ): """simple docstring""" _lowerCamelCase : Dict = vocab_size _lowerCamelCase : List[str] = n_positions _lowerCamelCase : Union[str, Any] = n_embd _lowerCamelCase : Optional[int] = n_layer _lowerCamelCase : List[str] = n_head _lowerCamelCase : Optional[Any] = n_inner _lowerCamelCase : Optional[int] = rotary_dim _lowerCamelCase : Dict = activation_function _lowerCamelCase : List[str] = resid_pdrop _lowerCamelCase : Optional[int] = embd_pdrop _lowerCamelCase : Optional[int] = attn_pdrop _lowerCamelCase : Dict = layer_norm_epsilon _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : List[str] = use_cache _lowerCamelCase : Dict = bos_token_id _lowerCamelCase : str = eos_token_id super().__init__( bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a ) class __snake_case ( lowerCamelCase_): def __init__( self : int , __lowerCAmelCase : PretrainedConfig , __lowerCAmelCase : str = "default" , __lowerCAmelCase : List[PatchingSpec] = None , __lowerCAmelCase : bool = False , ): """simple docstring""" super().__init__(__a , task=__a , patching_specs=__a , use_past=__a ) if not getattr(self._config , '''pad_token_id''' , __a ): # TODO: how to do that better? _lowerCamelCase : int = 0 @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Dict = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: self.fill_with_past_key_values_(__a , direction='''inputs''' ) _lowerCamelCase : List[Any] = {0: '''batch''', 1: '''past_sequence + sequence'''} else: _lowerCamelCase : Any = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self._config.n_layer @property def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self._config.n_head def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : PreTrainedTokenizer , __lowerCAmelCase : int = -1 , __lowerCAmelCase : int = -1 , __lowerCAmelCase : bool = False , __lowerCAmelCase : Optional[TensorType] = None , ): """simple docstring""" _lowerCamelCase : Any = super(__a , self ).generate_dummy_inputs( __a , batch_size=__a , seq_length=__a , is_pair=__a , framework=__a ) # We need to order the input in the way they appears in the forward() _lowerCamelCase : Optional[Any] = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch _lowerCamelCase , _lowerCamelCase : str = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values _lowerCamelCase : Tuple = seqlen + 2 _lowerCamelCase : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _lowerCamelCase : Tuple = [ (torch.zeros(__a ), torch.zeros(__a )) for _ in range(self.num_layers ) ] _lowerCamelCase : Tuple = common_inputs['''attention_mask'''] if self.use_past: _lowerCamelCase : List[Any] = ordered_inputs['''attention_mask'''].dtype _lowerCamelCase : Optional[int] = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(__a , __a , dtype=__a )] , dim=1 ) return ordered_inputs @property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return 1_3
83
'''simple docstring''' import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : Dict , **__a : List[Any] ): warnings.warn( "The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ChineseCLIPImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint A_ = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } A_ = { '169M': 768, '430M': 1024, '1B5': 2048, '3B': 2560, '7B': 4096, '14B': 5120, } def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ) -> Dict: snake_case__ : Tuple = list(state_dict.keys() ) for name in state_dict_keys: snake_case__ : Tuple = state_dict.pop(__SCREAMING_SNAKE_CASE ) # emb -> embedding if name.startswith('emb.' ): snake_case__ : str = name.replace('emb.' , 'embeddings.' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0' ): snake_case__ : List[Any] = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln' ) # att -> attention snake_case__ : Union[str, Any] = re.sub(r'blocks\.(\d+)\.att' , r'blocks.\1.attention' , __SCREAMING_SNAKE_CASE ) # ffn -> feed_forward snake_case__ : str = re.sub(r'blocks\.(\d+)\.ffn' , r'blocks.\1.feed_forward' , __SCREAMING_SNAKE_CASE ) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k' ): snake_case__ : Union[str, Any] = name.replace('.time_mix_k' , '.time_mix_key' ) # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v' ): snake_case__ : List[Any] = name.replace('.time_mix_v' , '.time_mix_value' ) # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r' ): snake_case__ : Union[str, Any] = name.replace('.time_mix_r' , '.time_mix_receptance' ) if name != "head.weight": snake_case__ : List[Any] = 'rwkv.' + name snake_case__ : Union[str, Any] = weight return state_dict def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=None ) -> Optional[Any]: # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.' ) snake_case__ : str = 5_0277 snake_case__ : str = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b' ) else: snake_case__ : Optional[int] = PreTrainedTokenizerFast(tokenizer_file=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = len(__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) # 2. Build the config snake_case__ : Optional[int] = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: snake_case__ : Optional[int] = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.' ) if size not in possible_sizes: raise ValueError(f"`size` should be one of {possible_sizes}, got {size}." ) snake_case__ : int = RwkvConfig( vocab_size=__SCREAMING_SNAKE_CASE , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(__SCREAMING_SNAKE_CASE ) # 3. Download model file then convert state_dict snake_case__ : Tuple = hf_hub_download(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = torch.load(__SCREAMING_SNAKE_CASE , map_location='cpu' ) snake_case__ : Dict = convert_state_dict(__SCREAMING_SNAKE_CASE ) # 4. Split in shards and save snake_case__ , snake_case__ : Optional[int] = shard_checkpoint(__SCREAMING_SNAKE_CASE ) for shard_file, shard in shards.items(): torch.save(__SCREAMING_SNAKE_CASE , os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if index is not None: snake_case__ : Union[str, Any] = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Save the index as well with open(__SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: snake_case__ : Any = json.dumps(__SCREAMING_SNAKE_CASE , indent=2 , sort_keys=__SCREAMING_SNAKE_CASE ) + '\n' f.write(__SCREAMING_SNAKE_CASE ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.' ) snake_case__ : Tuple = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: snake_case__ : List[Any] = torch.load(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.' ) snake_case__ : List[Any] = AutoModelForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE ) model.push_to_hub(__SCREAMING_SNAKE_CASE , max_shard_size='2GB' ) tokenizer.push_to_hub(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--repo_id", default=None, type=str, required=True, help="Repo ID from which to pull the checkpoint." ) parser.add_argument( "--checkpoint_file", default=None, type=str, required=True, help="Name of the checkpoint file in the repo." ) parser.add_argument( "--output_dir", default=None, type=str, required=True, help="Where to save the converted model." ) parser.add_argument( "--tokenizer_file", default=None, type=str, help="Path to the tokenizer file to use (if not provided, only the model is converted).", ) parser.add_argument( "--size", default=None, type=str, help="Size of the model. Will be inferred from the `checkpoint_file` if not passed.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Push to the Hub the converted model.", ) parser.add_argument( "--model_name", default=None, type=str, help="Name of the pushed model on the Hub, including the username / organization.", ) A_ = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
270
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[int] , __a : int , __a : int , __a : int , __a : str=0.0 , __a : Optional[int] = None , __a : str = "geglu" , __a : Optional[int] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : str = "layer_norm" , __a : bool = False , ): super().__init__() _a = only_cross_attention _a = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" _a = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f'`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to' f' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _a = AdaLayerNorm(__a , __a ) elif self.use_ada_layer_norm_zero: _a = AdaLayerNormZero(__a , __a ) else: _a = nn.LayerNorm(__a , elementwise_affine=__a ) _a = Attention( query_dim=__a , heads=__a , dim_head=__a , dropout=__a , bias=__a , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__a , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _a = ( AdaLayerNorm(__a , __a ) if self.use_ada_layer_norm else nn.LayerNorm(__a , elementwise_affine=__a ) ) _a = Attention( query_dim=__a , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__a , dim_head=__a , dropout=__a , bias=__a , upcast_attention=__a , ) # is self-attn if encoder_hidden_states is none else: _a = None _a = None # 3. Feed-forward _a = nn.LayerNorm(__a , elementwise_affine=__a ) _a = FeedForward(__a , dropout=__a , activation_fn=__a , final_dropout=__a ) # let chunk size default to None _a = None _a = 0 def UpperCamelCase__ ( self : int , __a : Optional[int] , __a : int ): # Sets chunk feed-forward _a = chunk_size _a = dim def UpperCamelCase__ ( self : List[str] , __a : torch.FloatTensor , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.LongTensor] = None , __a : Dict[str, Any] = None , __a : Optional[torch.LongTensor] = None , ): # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: _a = self.norma(__a , __a ) elif self.use_ada_layer_norm_zero: _a , _a , _a , _a , _a = self.norma( __a , __a , __a , hidden_dtype=hidden_states.dtype ) else: _a = self.norma(__a ) _a = cross_attention_kwargs if cross_attention_kwargs is not None else {} _a = self.attna( __a , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__a , **__a , ) if self.use_ada_layer_norm_zero: _a = gate_msa.unsqueeze(1 ) * attn_output _a = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _a = ( self.norma(__a , __a ) if self.use_ada_layer_norm else self.norma(__a ) ) _a = self.attna( __a , encoder_hidden_states=__a , attention_mask=__a , **__a , ) _a = attn_output + hidden_states # 3. Feed-forward _a = self.norma(__a ) if self.use_ada_layer_norm_zero: _a = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f'`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.' ) _a = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _a = torch.cat( [self.ff(__a ) for hid_slice in norm_hidden_states.chunk(__a , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: _a = self.ff(__a ) if self.use_ada_layer_norm_zero: _a = gate_mlp.unsqueeze(1 ) * ff_output _a = ff_output + hidden_states return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[Any] , __a : int , __a : Optional[int] = None , __a : int = 4 , __a : float = 0.0 , __a : str = "geglu" , __a : bool = False , ): super().__init__() _a = int(dim * mult ) _a = dim_out if dim_out is not None else dim if activation_fn == "gelu": _a = GELU(__a , __a ) if activation_fn == "gelu-approximate": _a = GELU(__a , __a , approximate="tanh" ) elif activation_fn == "geglu": _a = GEGLU(__a , __a ) elif activation_fn == "geglu-approximate": _a = ApproximateGELU(__a , __a ) _a = nn.ModuleList([] ) # project in self.net.append(__a ) # project dropout self.net.append(nn.Dropout(__a ) ) # project out self.net.append(nn.Linear(__a , __a ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(__a ) ) def UpperCamelCase__ ( self : List[Any] , __a : Tuple ): for module in self.net: _a = module(__a ) return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : int , __a : int , __a : str = "none" ): super().__init__() _a = nn.Linear(__a , __a ) _a = approximate def UpperCamelCase__ ( self : Union[str, Any] , __a : List[Any] ): if gate.device.type != "mps": return F.gelu(__a , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def UpperCamelCase__ ( self : str , __a : Optional[int] ): _a = self.proj(__a ) _a = self.gelu(__a ) return hidden_states class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : str , __a : int , __a : int ): super().__init__() _a = nn.Linear(__a , dim_out * 2 ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[int] ): if gate.device.type != "mps": return F.gelu(__a ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def UpperCamelCase__ ( self : List[str] , __a : Any ): _a , _a = self.proj(__a ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(__a ) class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[Any] , __a : int , __a : int ): super().__init__() _a = nn.Linear(__a , __a ) def UpperCamelCase__ ( self : Union[str, Any] , __a : Dict ): _a = self.proj(__a ) return x * torch.sigmoid(1.702 * x ) class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : int , __a : str , __a : str ): super().__init__() _a = nn.Embedding(__a , __a ) _a = nn.SiLU() _a = nn.Linear(__a , embedding_dim * 2 ) _a = nn.LayerNorm(__a , elementwise_affine=__a ) def UpperCamelCase__ ( self : Tuple , __a : Any , __a : Optional[Any] ): _a = self.linear(self.silu(self.emb(__a ) ) ) _a , _a = torch.chunk(__a , 2 ) _a = self.norm(__a ) * (1 + scale) + shift return x class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : List[Any] , __a : List[Any] , __a : Any ): super().__init__() _a = CombinedTimestepLabelEmbeddings(__a , __a ) _a = nn.SiLU() _a = nn.Linear(__a , 6 * embedding_dim , bias=__a ) _a = nn.LayerNorm(__a , elementwise_affine=__a , eps=1e-6 ) def UpperCamelCase__ ( self : Optional[Any] , __a : Dict , __a : List[Any] , __a : Union[str, Any] , __a : List[Any]=None ): _a = self.linear(self.silu(self.emb(__a , __a , hidden_dtype=__a ) ) ) _a , _a , _a , _a , _a , _a = emb.chunk(6 , dim=1 ) _a = self.norm(__a ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Optional[int] , __a : int , __a : int , __a : int , __a : Optional[str] = None , __a : float = 1e-5 ): super().__init__() _a = num_groups _a = eps if act_fn is None: _a = None else: _a = get_activation(__a ) _a = nn.Linear(__a , out_dim * 2 ) def UpperCamelCase__ ( self : List[Any] , __a : Optional[Any] , __a : List[Any] ): if self.act: _a = self.act(__a ) _a = self.linear(__a ) _a = emb[:, :, None, None] _a , _a = emb.chunk(2 , dim=1 ) _a = F.group_norm(__a , self.num_groups , eps=self.eps ) _a = x * (1 + scale) + shift return x
692
0
"""simple docstring""" def a ( __UpperCAmelCase : int=2_8_1_2_3 ) -> List[Any]: __magic_name__: Any = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i __magic_name__: int = set() __magic_name__: Union[str, Any] = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(__UpperCAmelCase ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
96
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class __SCREAMING_SNAKE_CASE : """simple docstring""" __a =42 __a =42 class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] , __a : int ): _a = [[] for _ in range(__a )] _a = size def __getitem__( self : int , __a : int ): return iter(self._graph[vertex] ) @property def UpperCamelCase__ ( self : Dict ): return self._size def UpperCamelCase__ ( self : Union[str, Any] , __a : int , __a : int , __a : int ): if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(__a , __a ) ) def UpperCamelCase__ ( self : Tuple , __a : int , __a : int ): _a = deque([start_vertex] ) _a = [None] * self.size _a = 0 while queue: _a = queue.popleft() _a = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _a = current_distance + edge.weight _a = distances[edge.destination_vertex] if ( isinstance(__a , __a ) and new_distance >= dest_vertex_distance ): continue _a = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
692
0
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels lowercase_ = object() # For specifying empty leaf dict `{}` lowercase_ = object() def A_ ( lowercase , lowercase ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(lowercase ) - len(lowercase ) + 1 ): UpperCAmelCase_ : Optional[Any] = [x.match(lowercase ) for x, y in zip(lowercase , ks[i:] )] if matches and all(lowercase ): return True return False def A_ ( lowercase ) -> List[Any]: """simple docstring""" def replace(lowercase , lowercase ): for rule, replacement in rules: if _match(lowercase , lowercase ): return replacement return val return replace def A_ ( ) -> Optional[int]: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""" , lowercase )), (("transformer", "wte", "embedding"), P("""mp""" , lowercase )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowercase , """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""" , lowercase )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowercase , """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""" , lowercase )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def A_ ( lowercase ) -> Any: """simple docstring""" UpperCAmelCase_ : Dict = _get_partition_rules() UpperCAmelCase_ : str = _replacement_rules(lowercase ) UpperCAmelCase_ : str = {k: _unmatched for k in flatten_dict(lowercase )} UpperCAmelCase_ : List[Any] = {k: replace(lowercase , lowercase ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowercase ) )
470
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =FlaxAutoencoderKL @property def UpperCamelCase__ ( self : str ): _a = 4 _a = 3 _a = (32, 32) _a = jax.random.PRNGKey(0 ) _a = jax.random.uniform(__a , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCamelCase__ ( self : List[Any] ): _a = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } _a = self.dummy_input return init_dict, inputs_dict
692
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A : Union[str, Any] = { 'configuration_roformer': ['ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoFormerConfig', 'RoFormerOnnxConfig'], 'tokenization_roformer': ['RoFormerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Union[str, Any] = ['RoFormerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = [ 'ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoFormerForCausalLM', 'RoFormerForMaskedLM', 'RoFormerForMultipleChoice', 'RoFormerForQuestionAnswering', 'RoFormerForSequenceClassification', 'RoFormerForTokenClassification', 'RoFormerLayer', 'RoFormerModel', 'RoFormerPreTrainedModel', 'load_tf_weights_in_roformer', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Dict = [ 'TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRoFormerForCausalLM', 'TFRoFormerForMaskedLM', 'TFRoFormerForMultipleChoice', 'TFRoFormerForQuestionAnswering', 'TFRoFormerForSequenceClassification', 'TFRoFormerForTokenClassification', 'TFRoFormerLayer', 'TFRoFormerModel', 'TFRoFormerPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[int] = [ 'FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'FlaxRoFormerForMaskedLM', 'FlaxRoFormerForMultipleChoice', 'FlaxRoFormerForQuestionAnswering', 'FlaxRoFormerForSequenceClassification', 'FlaxRoFormerForTokenClassification', 'FlaxRoFormerModel', 'FlaxRoFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys A : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
287
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration lowerCAmelCase_ : List[Any] = [ # tf -> hf ('/', '.'), ('layer_', 'layers.'), ('kernel', 'weight'), ('beta', 'bias'), ('gamma', 'weight'), ('pegasus', 'model'), ] lowerCAmelCase_ : Optional[int] = [ ('.output.dense', '.fc2'), ('intermediate.LayerNorm', 'final_layer_norm'), ('intermediate.dense', 'fc1'), ] lowerCAmelCase_ : Any = ( INIT_COMMON + [ ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.out_proj'), ('attention.self', 'self_attn'), ('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'), ('attention.encdec_output.dense', 'encoder_attn.out_proj'), ('attention.encdec', 'encoder_attn'), ('key', 'k_proj'), ('value', 'v_proj'), ('query', 'q_proj'), ('decoder.LayerNorm', 'decoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Tuple = ( INIT_COMMON + [ ('embeddings.word_embeddings', 'shared.weight'), ('embeddings.position_embeddings', 'embed_positions.weight'), ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.output'), ('attention.self', 'self_attn.self'), ('encoder.LayerNorm', 'encoder.layernorm_embedding'), ] + END_COMMON ) lowerCAmelCase_ : Optional[int] = [ 'encdec/key/bias', 'encdec/query/bias', 'encdec/value/bias', 'self/key/bias', 'self/query/bias', 'self/value/bias', 'encdec_output/dense/bias', 'attention/output/dense/bias', ] def _lowerCamelCase ( lowercase : Any , lowercase : Any ) -> Optional[Any]: for tf_name, hf_name in patterns: _a = k.replace(lowercase , lowercase ) return k def _lowerCamelCase ( lowercase : dict , lowercase : dict ) -> BigBirdPegasusForConditionalGeneration: _a = BigBirdPegasusConfig(**lowercase ) _a = BigBirdPegasusForConditionalGeneration(lowercase ) _a = torch_model.state_dict() _a = {} # separating decoder weights _a = {k: tf_weights[k] for k in tf_weights if k.startswith("pegasus/decoder" )} _a = {k: tf_weights[k] for k in tf_weights if not k.startswith("pegasus/decoder" )} for k, v in tqdm(decoder_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = DECODER_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict: raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' for k, v in tqdm(remaining_weights.items() , "tf -> hf conversion" ): _a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE] if any(lowercase ): continue _a = REMAINING_PATTERNS _a = rename_state_dict_key(lowercase , lowercase ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _a = v.T _a = torch.from_numpy(lowercase ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' _a = mapping["model.embed_positions.weight"] _a = mapping.pop("model.embed_positions.weight" ) _a , _a = torch_model.load_state_dict(lowercase , strict=lowercase ) _a = [ k for k in missing if k not in [ "final_logits_bias", "model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight", ] ] assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}' assert extra == [], F'no matches found for the following tf keys {extra}' return torch_model def _lowerCamelCase ( lowercase : List[Any] ) -> Dict: _a = tf.train.list_variables(lowercase ) _a = {} _a = ["global_step"] for name, shape in tqdm(lowercase , desc="converting tf checkpoint to dict" ): _a = any(pat in name for pat in ignore_name ) if skip_key: continue _a = tf.train.load_variable(lowercase , lowercase ) _a = array return tf_weights def _lowerCamelCase ( lowercase : str , lowercase : str , lowercase : dict ) -> Union[str, Any]: _a = get_tf_weights_as_numpy(lowercase ) _a = convert_bigbird_pegasus(lowercase , lowercase ) torch_model.save_pretrained(lowercase ) if __name__ == "__main__": lowerCAmelCase_ : str = argparse.ArgumentParser() parser.add_argument('--tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('--save_dir', default=None, type=str, help='Path to the output PyTorch model.') lowerCAmelCase_ : Optional[Any] = parser.parse_args() lowerCAmelCase_ : Optional[Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
0
"""simple docstring""" import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def __lowercase ( _a , _a , _a , _a=5 ): # Adapted from https://github.com/pytorch/fairseq/blob/master/fairseq/models/roberta/hub_interface.py assert masked_input.count('''<mask>''' ) == 1 snake_case_ : List[Any] = torch.tensor(tokenizer.encode(_a , add_special_tokens=_a ) ).unsqueeze(0 ) # Batch size 1 snake_case_ : Optional[int] = model(_a )[0] # The last hidden-state is the first element of the output tuple snake_case_ : str = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() snake_case_ : int = logits[0, masked_index, :] snake_case_ : List[Any] = logits.softmax(dim=0 ) snake_case_, snake_case_ : List[Any] = prob.topk(k=_a , dim=0 ) snake_case_ : Dict = ''' '''.join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(_a ) )] ) snake_case_ : List[str] = tokenizer.mask_token snake_case_ : int = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(''' ''' ) ): snake_case_ : str = predicted_token_bpe.replace('''\u2581''' , ''' ''' ) if " {0}".format(_a ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(''' {0}'''.format(_a ) , _a ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(_a , _a ), values[index].item(), predicted_token, ) ) return topk_filled_outputs lowercase__ : int = CamembertTokenizer.from_pretrained('''camembert-base''') lowercase__ : Optional[Any] = CamembertForMaskedLM.from_pretrained('''camembert-base''') model.eval() lowercase__ : Dict = 'Le camembert est <mask> :)' print(fill_mask(masked_input, model, tokenizer, topk=3))
123
'''simple docstring''' def _lowerCamelCase ( lowercase : str , lowercase : list[str] ) -> str: _a = "" for word_or_phrase in separated: if not isinstance(lowercase , lowercase ): raise Exception("join() accepts only strings to be joined" ) joined += word_or_phrase + separator return joined.strip(lowercase ) if __name__ == "__main__": from doctest import testmod testmod()
692
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A = logging.get_logger(__name__) A = { 'microsoft/beit-base-patch16-224-pt22k': ( 'https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class lowerCAmelCase__ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ = 'beit' def __init__( self : Optional[int] , snake_case__ : Union[str, Any]=8_1_9_2 , snake_case__ : List[Any]=7_6_8 , snake_case__ : List[str]=1_2 , snake_case__ : Union[str, Any]=1_2 , snake_case__ : Optional[Any]=3_0_7_2 , snake_case__ : Optional[Any]="gelu" , snake_case__ : List[Any]=0.0 , snake_case__ : Dict=0.0 , snake_case__ : str=0.02 , snake_case__ : List[Any]=1e-12 , snake_case__ : Optional[int]=2_2_4 , snake_case__ : Dict=1_6 , snake_case__ : Tuple=3 , snake_case__ : Tuple=False , snake_case__ : Union[str, Any]=False , snake_case__ : int=False , snake_case__ : Optional[int]=False , snake_case__ : Optional[int]=0.1 , snake_case__ : List[Any]=0.1 , snake_case__ : Optional[Any]=True , snake_case__ : int=[3, 5, 7, 1_1] , snake_case__ : Any=[1, 2, 3, 6] , snake_case__ : List[Any]=True , snake_case__ : List[str]=0.4 , snake_case__ : int=2_5_6 , snake_case__ : str=1 , snake_case__ : Union[str, Any]=False , snake_case__ : Any=2_5_5 , **snake_case__ : List[str] , ) -> List[str]: super().__init__(**__a ) _lowerCamelCase = vocab_size _lowerCamelCase = hidden_size _lowerCamelCase = num_hidden_layers _lowerCamelCase = num_attention_heads _lowerCamelCase = intermediate_size _lowerCamelCase = hidden_act _lowerCamelCase = hidden_dropout_prob _lowerCamelCase = attention_probs_dropout_prob _lowerCamelCase = initializer_range _lowerCamelCase = layer_norm_eps _lowerCamelCase = image_size _lowerCamelCase = patch_size _lowerCamelCase = num_channels _lowerCamelCase = use_mask_token _lowerCamelCase = use_absolute_position_embeddings _lowerCamelCase = use_relative_position_bias _lowerCamelCase = use_shared_relative_position_bias _lowerCamelCase = layer_scale_init_value _lowerCamelCase = drop_path_rate _lowerCamelCase = use_mean_pooling # decode head attributes (semantic segmentation) _lowerCamelCase = out_indices _lowerCamelCase = pool_scales # auxiliary head attributes (semantic segmentation) _lowerCamelCase = use_auxiliary_head _lowerCamelCase = auxiliary_loss_weight _lowerCamelCase = auxiliary_channels _lowerCamelCase = auxiliary_num_convs _lowerCamelCase = auxiliary_concat_input _lowerCamelCase = semantic_loss_ignore_index class lowerCAmelCase__ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ = version.parse('1.11' ) @property def _snake_case ( self : List[Any] ) -> Optional[Any]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _snake_case ( self : List[Any] ) -> Tuple: return 1e-4
544
'''simple docstring''' lowerCAmelCase_ : Optional[Any] = '\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' lowerCAmelCase_ : List[Any] = [{'type': 'code', 'content': INSTALL_CONTENT}] lowerCAmelCase_ : Dict = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
692
0
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: '''simple docstring''' def update_area_of_max_square(_lowerCAmelCase , _lowerCAmelCase ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 __snake_case = update_area_of_max_square(_lowerCAmelCase , col + 1 ) __snake_case = update_area_of_max_square(row + 1 , col + 1 ) __snake_case = update_area_of_max_square(row + 1 , _lowerCAmelCase ) if mat[row][col]: __snake_case = 1 + min([right, diagonal, down] ) __snake_case = max(largest_square_area[0] , _lowerCAmelCase ) return sub_problem_sol else: return 0 __snake_case = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: '''simple docstring''' def update_area_of_max_square_using_dp_array( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] __snake_case = update_area_of_max_square_using_dp_array(_lowerCAmelCase , col + 1 , _lowerCAmelCase ) __snake_case = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , _lowerCAmelCase ) __snake_case = update_area_of_max_square_using_dp_array(row + 1 , _lowerCAmelCase , _lowerCAmelCase ) if mat[row][col]: __snake_case = 1 + min([right, diagonal, down] ) __snake_case = max(largest_square_area[0] , _lowerCAmelCase ) __snake_case = sub_problem_sol return sub_problem_sol else: return 0 __snake_case = [0] __snake_case = [[-1] * cols for _ in range(_lowerCAmelCase )] update_area_of_max_square_using_dp_array(0 , 0 , _lowerCAmelCase ) return largest_square_area[0] def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: '''simple docstring''' __snake_case = [[0] * (cols + 1) for _ in range(rows + 1 )] __snake_case = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __snake_case = dp_array[row][col + 1] __snake_case = dp_array[row + 1][col + 1] __snake_case = dp_array[row + 1][col] if mat[row][col] == 1: __snake_case = 1 + min(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) __snake_case = max(dp_array[row][col] , _lowerCAmelCase ) else: __snake_case = 0 return largest_square_area def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: '''simple docstring''' __snake_case = [0] * (cols + 1) __snake_case = [0] * (cols + 1) __snake_case = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __snake_case = current_row[col + 1] __snake_case = next_row[col + 1] __snake_case = next_row[col] if mat[row][col] == 1: __snake_case = 1 + min(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) __snake_case = max(current_row[col] , _lowerCAmelCase ) else: __snake_case = 0 __snake_case = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
371
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') lowerCAmelCase_ : Optional[Any] = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) lowerCAmelCase_ : Dict = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) lowerCAmelCase_ : Dict = BeautifulSoup(res.text, 'html.parser') lowerCAmelCase_ : Optional[int] = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f"""https://google.com{link.get('href')}""")
692
0
from math import loga def A__( __lowerCAmelCase ): if a < 0: raise ValueError('Input value must be a positive integer' ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError('Input value must be a \'int\' type' ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
304
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets lowerCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) lowerCAmelCase_ : Tuple = '\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n author = "Moosavi, Nafise Sadat and\n Strube, Michael",\n booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/P16-1060",\n doi = "10.18653/v1/P16-1060",\n pages = "632--642",\n}\n\n' lowerCAmelCase_ : Union[str, Any] = '\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n' lowerCAmelCase_ : Union[str, Any] = '\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting \'keep_singletons=False\', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n \'mentions\': mentions\n \'muc\': MUC metric [Vilain et al, 1995]\n \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n \'ceafe\': CEAFe [Luo et al., 2005]\n \'lea\': LEA [Moosavi and Strube, 2016]\n \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric(\'coval\')\n >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\',\n ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\',\n ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\',\n ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\',\n ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\',\n ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n' def _lowerCamelCase ( lowercase : Tuple , lowercase : List[Any] , lowercase : Optional[int]=False , lowercase : Dict=False , lowercase : Optional[int]=True , lowercase : Union[str, Any]=False , lowercase : int="dummy_doc" ) -> Union[str, Any]: _a = {doc: key_lines} _a = {doc: sys_lines} _a = {} _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a = 0 _a , _a = reader.get_doc_mentions(lowercase , key_doc_lines[doc] , lowercase ) key_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) _a , _a = reader.get_doc_mentions(lowercase , sys_doc_lines[doc] , lowercase ) sys_singletons_num += singletons_num if NP_only or min_span: _a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase ) if remove_nested: _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters _a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters _a = reader.get_mention_assignments(lowercase , lowercase ) _a = reader.get_mention_assignments(lowercase , lowercase ) _a = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( "Number of removed nested coreferring mentions in the key " F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( "Number of resulting singleton clusters in the key " F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' "files, respectively" ) return doc_coref_infos def _lowerCamelCase ( lowercase : List[Any] , lowercase : Any , lowercase : Optional[Any] , lowercase : Union[str, Any] , lowercase : Any , lowercase : List[str] , lowercase : Dict ) -> str: _a = get_coref_infos(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) _a = {} _a = 0 _a = 0 for name, metric in metrics: _a , _a , _a = evaluator.evaluate_documents(lowercase , lowercase , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} ) logger.info( name.ljust(10 ) , F'Recall: {recall * 100:.2f}' , F' Precision: {precision * 100:.2f}' , F' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: _a = (conll / 3) * 100 logger.info(F'CoNLL score: {conll:.2f}' ) output_scores.update({"conll_score": conll} ) return output_scores def _lowerCamelCase ( lowercase : Any ) -> str: _a = False for line in key_lines: if not line.startswith("#" ): if len(line.split() ) > 6: _a = line.split()[5] if not parse_col == "-": _a = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE (datasets.Metric ): """simple docstring""" def UpperCamelCase__ ( self : str ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Sequence(datasets.Value("string" ) ), } ) , codebase_urls=["https://github.com/ns-moosavi/coval"] , reference_urls=[ "https://github.com/ns-moosavi/coval", "https://www.aclweb.org/anthology/P16-1060", "http://www.conll.cemantix.org/2012/data.html", ] , ) def UpperCamelCase__ ( self : int , __a : Any , __a : int , __a : Optional[Any]=True , __a : Optional[Any]=False , __a : str=False , __a : List[str]=False ): _a = [ ("mentions", evaluator.mentions), ("muc", evaluator.muc), ("bcub", evaluator.b_cubed), ("ceafe", evaluator.ceafe), ("lea", evaluator.lea), ] if min_span: _a = util.check_gold_parse_annotation(__a ) if not has_gold_parse: raise NotImplementedError("References should have gold parse annotation to use 'min_span'." ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" _a = evaluate( key_lines=__a , sys_lines=__a , metrics=__a , NP_only=__a , remove_nested=__a , keep_singletons=__a , min_span=__a , ) return score
692
0
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( """compression_format, is_archive""" , [ ("""7z""", True), ("""bz2""", False), ("""gzip""", False), ("""lz4""", False), ("""tar""", True), ("""xz""", False), ("""zip""", True), ("""zstd""", False), ] , ) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = { """7z""": (seven_zip_file, SevenZipExtractor), """bz2""": (bza_file, BzipaExtractor), """gzip""": (gz_file, GzipExtractor), """lz4""": (lza_file, LzaExtractor), """tar""": (tar_file, TarExtractor), """xz""": (xz_file, XzExtractor), """zip""": (zip_file, ZipExtractor), """zstd""": (zstd_file, ZstdExtractor), } UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = input_paths_and_base_extractors[compression_format] if input_path is None: UpperCAmelCase__ : Union[str, Any] = F"for \'{compression_format}\' compression_format, " if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(__lowerCamelCase ) assert base_extractor.is_extractable(__lowerCamelCase ) UpperCAmelCase__ : int = tmp_path / ("""extracted""" if is_archive else """extracted.txt""") base_extractor.extract(__lowerCamelCase , __lowerCamelCase ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name UpperCAmelCase__ : Union[str, Any] = file_path.read_text(encoding="""utf-8""" ) else: UpperCAmelCase__ : List[str] = output_path.read_text(encoding="""utf-8""" ) UpperCAmelCase__ : int = text_file.read_text(encoding="""utf-8""" ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( """compression_format, is_archive""" , [ ("""7z""", True), ("""bz2""", False), ("""gzip""", False), ("""lz4""", False), ("""tar""", True), ("""xz""", False), ("""zip""", True), ("""zstd""", False), ] , ) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ : Any = { """7z""": seven_zip_file, """bz2""": bza_file, """gzip""": gz_file, """lz4""": lza_file, """tar""": tar_file, """xz""": xz_file, """zip""": zip_file, """zstd""": zstd_file, } UpperCAmelCase__ : Dict = input_paths[compression_format] if input_path is None: UpperCAmelCase__ : Union[str, Any] = F"for \'{compression_format}\' compression_format, " if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(__lowerCamelCase ) UpperCAmelCase__ : List[Any] = Extractor.infer_extractor_format(__lowerCamelCase ) assert extractor_format is not None UpperCAmelCase__ : Optional[Any] = tmp_path / ("""extracted""" if is_archive else """extracted.txt""") Extractor.extract(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name UpperCAmelCase__ : List[str] = file_path.read_text(encoding="""utf-8""" ) else: UpperCAmelCase__ : List[Any] = output_path.read_text(encoding="""utf-8""" ) UpperCAmelCase__ : int = text_file.read_text(encoding="""utf-8""" ) assert extracted_file_content == expected_file_content @pytest.fixture def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ) -> str: '''simple docstring''' import tarfile UpperCAmelCase__ : Dict = tmp_path / """data_dot_dot""" directory.mkdir() UpperCAmelCase__ : Union[str, Any] = directory / """tar_file_with_dot_dot.tar""" with tarfile.TarFile(__lowerCamelCase , """w""" ) as f: f.add(__lowerCamelCase , arcname=os.path.join("""..""" , text_file.name ) ) return path @pytest.fixture def _lowerCamelCase ( __lowerCamelCase ) -> Any: '''simple docstring''' import tarfile UpperCAmelCase__ : int = tmp_path / """data_sym_link""" directory.mkdir() UpperCAmelCase__ : Any = directory / """tar_file_with_sym_link.tar""" os.symlink("""..""" , directory / """subdir""" , target_is_directory=__lowerCamelCase ) with tarfile.TarFile(__lowerCamelCase , """w""" ) as f: f.add(str(directory / """subdir""" ) , arcname="""subdir""" ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( """insecure_tar_file, error_log""" , [("""tar_file_with_dot_dot""", """illegal path"""), ("""tar_file_with_sym_link""", """Symlink""")] , ) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ : Dict = { """tar_file_with_dot_dot""": tar_file_with_dot_dot, """tar_file_with_sym_link""": tar_file_with_sym_link, } UpperCAmelCase__ : Tuple = insecure_tar_files[insecure_tar_file] UpperCAmelCase__ : List[Any] = tmp_path / """extracted""" TarExtractor.extract(__lowerCamelCase , __lowerCamelCase ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def _lowerCamelCase ( __lowerCamelCase ) -> Tuple: '''simple docstring''' # We should have less false positives than zipfile.is_zipfile # We do that by checking only the magic number UpperCAmelCase__ : Dict = tmpdir / """not_a_zip_file""" # From: https://github.com/python/cpython/pull/5053 UpperCAmelCase__ : Union[str, Any] = ( B"""\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00""" B"""\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I""" B"""DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07""" B"""\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82""" ) with not_a_zip_file.open("""wb""" ) as f: f.write(__lowerCamelCase ) assert zipfile.is_zipfile(str(__lowerCamelCase ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(__lowerCamelCase ) # but we're right
79
'''simple docstring''' import math def _lowerCamelCase ( lowercase : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowercase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCamelCase ( lowercase : float = 0.1 ) -> int: _a = 3 _a = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowercase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
0
"""simple docstring""" import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @property def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :str = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :str = VQModel( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def snake_case ( self ): '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase__ :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(__a ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = self.dummy_uncond_unet lowerCAmelCase__ :Tuple = DDIMScheduler() lowerCAmelCase__ :List[Any] = self.dummy_vq_model lowerCAmelCase__ :str = LDMPipeline(unet=__a , vqvae=__a , scheduler=__a ) ldm.to(__a ) ldm.set_progress_bar_config(disable=__a ) lowerCAmelCase__ :int = torch.manual_seed(0 ) lowerCAmelCase__ :str = ldm(generator=__a , num_inference_steps=2 , output_type='numpy' ).images lowerCAmelCase__ :List[str] = torch.manual_seed(0 ) lowerCAmelCase__ :int = ldm(generator=__a , num_inference_steps=2 , output_type='numpy' , return_dict=__a )[0] lowerCAmelCase__ :str = image[0, -3:, -3:, -1] lowerCAmelCase__ :Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowerCAmelCase__ :int = np.array([0.85_12, 0.8_18, 0.64_11, 0.68_08, 0.44_65, 0.56_18, 0.46, 0.62_31, 0.51_72] ) lowerCAmelCase__ :Union[str, Any] = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(__a ) ldm.set_progress_bar_config(disable=__a ) lowerCAmelCase__ :Union[str, Any] = torch.manual_seed(0 ) lowerCAmelCase__ :Optional[int] = ldm(generator=__a , num_inference_steps=5 , output_type='numpy' ).images lowerCAmelCase__ :Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) lowerCAmelCase__ :Optional[Any] = np.array([0.43_99, 0.4_49_75, 0.4_68_25, 0.4_74, 0.43_59, 0.45_81, 0.4_50_95, 0.43_41, 0.44_47] ) lowerCAmelCase__ :Any = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
93
'''simple docstring''' import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =(CMStochasticIterativeScheduler,) __a =10 def UpperCamelCase__ ( self : Union[str, Any] , **__a : str ): _a = { "num_train_timesteps": 2_01, "sigma_min": 0.002, "sigma_max": 80.0, } config.update(**__a ) return config def UpperCamelCase__ ( self : List[Any] ): _a = 10 _a = self.get_scheduler_config() _a = self.scheduler_classes[0](**__a ) scheduler.set_timesteps(__a ) _a = scheduler.timesteps[0] _a = scheduler.timesteps[1] _a = self.dummy_sample _a = 0.1 * sample _a = scheduler.step(__a , __a , __a ).prev_sample _a = scheduler.step(__a , __a , __a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase__ ( self : Any ): for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__a ) def UpperCamelCase__ ( self : int ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = 1 scheduler.set_timesteps(__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(__a ): # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCamelCase__ ( self : Union[str, Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [1_06, 0] scheduler.set_timesteps(timesteps=__a ) _a = scheduler.timesteps _a = torch.manual_seed(0 ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input _a = scheduler.scale_model_input(__a , __a ) # 2. predict noise residual _a = model(__a , __a ) # 3. predict previous sample x_t-1 _a = scheduler.step(__a , __a , __a , generator=__a ).prev_sample _a = pred_prev_sample _a = torch.sum(torch.abs(__a ) ) _a = torch.mean(torch.abs(__a ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCamelCase__ ( self : List[Any] ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 15, 0] with self.assertRaises(__a , msg="`timesteps` must be in descending order." ): scheduler.set_timesteps(timesteps=__a ) def UpperCamelCase__ ( self : Tuple ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [39, 30, 12, 1, 0] _a = len(__a ) with self.assertRaises(__a , msg="Can only pass one of `num_inference_steps` or `timesteps`." ): scheduler.set_timesteps(num_inference_steps=__a , timesteps=__a ) def UpperCamelCase__ ( self : str ): _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**__a ) _a = [scheduler.config.num_train_timesteps] with self.assertRaises( __a , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=__a )
692
0
"""simple docstring""" def snake_case_ ( A_ : int = 10_00 ): '''simple docstring''' _lowerCamelCase , _lowerCamelCase : List[str] = 1, 1 _lowerCamelCase : List[Any] = 2 while True: _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = fa + fa _lowerCamelCase , _lowerCamelCase : Tuple = fa, f index += 1 for _ in str(A_ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
83
'''simple docstring''' import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , *__a : int , **__a : Optional[Any] ): warnings.warn( "The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use YolosImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
692
0
'''simple docstring''' def UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ) -> int: assert ( isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and number_of_steps > 0 ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" if number_of_steps == 1: return 1 snake_case__ , snake_case__ : Dict = 1, 1 for _ in range(number_of_steps - 1 ): snake_case__ , snake_case__ : Union[str, Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
270
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) lowerCAmelCase_ : str = { 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a ='timesformer' def __init__( self : Optional[int] , __a : Optional[int]=2_24 , __a : Tuple=16 , __a : int=3 , __a : Union[str, Any]=8 , __a : Union[str, Any]=7_68 , __a : List[str]=12 , __a : Union[str, Any]=12 , __a : Optional[Any]=30_72 , __a : Tuple="gelu" , __a : str=0.0 , __a : List[Any]=0.0 , __a : Any=0.02 , __a : List[str]=1e-6 , __a : Any=True , __a : Union[str, Any]="divided_space_time" , __a : str=0 , **__a : Tuple , ): super().__init__(**__a ) _a = image_size _a = patch_size _a = num_channels _a = num_frames _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = initializer_range _a = layer_norm_eps _a = qkv_bias _a = attention_type _a = drop_path_rate
692
0
"""simple docstring""" from queue import PriorityQueue from typing import Any import numpy as np def a ( __UpperCAmelCase : dict , __UpperCAmelCase : str , __UpperCAmelCase : set , __UpperCAmelCase : set , __UpperCAmelCase : dict , __UpperCAmelCase : dict , __UpperCAmelCase : PriorityQueue , __UpperCAmelCase : dict , __UpperCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __magic_name__: List[str] = cst_fwd.get(__UpperCAmelCase , np.inf ) __magic_name__: Dict = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __magic_name__: List[Any] = new_cost_f __magic_name__: int = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __magic_name__: Any = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def a ( __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : dict , __UpperCAmelCase : dict ) -> int: __magic_name__: Any = -1 __magic_name__: List[Any] = set() __magic_name__: List[Any] = set() __magic_name__: List[str] = {source: 0} __magic_name__: Optional[Any] = {destination: 0} __magic_name__: List[Any] = {source: None} __magic_name__: List[str] = {destination: None} __magic_name__: List[Any] = PriorityQueue() __magic_name__: str = PriorityQueue() __magic_name__: List[str] = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __magic_name__, __magic_name__: str = queue_forward.get() visited_forward.add(__UpperCAmelCase ) __magic_name__, __magic_name__: Optional[Any] = queue_backward.get() visited_backward.add(__UpperCAmelCase ) __magic_name__: Optional[int] = pass_and_relaxation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) __magic_name__: Dict = pass_and_relaxation( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __magic_name__: Dict = shortest_distance return shortest_path_distance __lowerCamelCase = { 'B': [['C', 1]], 'C': [['D', 1]], 'D': [['F', 1]], 'E': [['B', 1], ['G', 2]], 'F': [], 'G': [['F', 1]], } __lowerCamelCase = { 'B': [['E', 1]], 'C': [['B', 1]], 'D': [['C', 1]], 'F': [['D', 1], ['G', 1]], 'E': [[None, np.inf]], 'G': [['E', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
96
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase__ ( self : Dict ): _a = 1 _a = 3 _a = (32, 32) _a = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__a ) return image @property def UpperCamelCase__ ( self : Dict ): torch.manual_seed(0 ) _a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def UpperCamelCase__ ( self : Optional[int] ): torch.manual_seed(0 ) _a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def UpperCamelCase__ ( self : Optional[Any] ): torch.manual_seed(0 ) _a = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=50_06 , ) return RobertaSeriesModelWithTransformation(__a ) @property def UpperCamelCase__ ( self : str ): def extract(*__a : Tuple , **__a : str ): class __SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict ): _a = torch.ones([0] ) def UpperCamelCase__ ( self : List[str] , __a : Dict ): self.pixel_values.to(__a ) return self return Out() return extract def UpperCamelCase__ ( self : Optional[int] ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) _a = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , ) _a = output.images _a = torch.Generator(device=__a ).manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=__a , return_dict=__a , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _a = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[int] ): _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=__a ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _a = 77 _a = self.dummy_image.to(__a ) # put models in fp16 _a = unet.half() _a = vae.half() _a = bert.half() # make sure here that pndm scheduler skips prk _a = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _a = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _a = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _a = "A painting of a squirrel eating a burger" _a = torch.manual_seed(0 ) _a = alt_pipe( [prompt] , generator=__a , num_inference_steps=2 , output_type="np" , image=__a , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase__ ( self : Optional[Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 _a = init_image.resize((7_60, 5_04) ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] _a = image[2_55:2_58, 3_83:3_86, -1] assert image.shape == (5_04, 7_60, 3) _a = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : Union[str, Any] ): _a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) _a = init_image.resize((7_68, 5_12) ) _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) _a = "BAAI/AltDiffusion" _a = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = "A fantasy landscape, trending on artstation" _a = torch.manual_seed(0 ) _a = pipe( prompt=__a , image=__a , strength=0.75 , guidance_scale=7.5 , generator=__a , output_type="np" , ) _a = output.images[0] assert image.shape == (5_12, 7_68, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
692
0