code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = [False] * len(UpperCAmelCase_ ) UpperCamelCase_ = [-1] * len(UpperCAmelCase_ ) def dfs(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = True UpperCamelCase_ = c for u in graph[v]: if not visited[u]: dfs(UpperCAmelCase_ , 1 - c ) for i in range(len(UpperCAmelCase_ ) ): if not visited[i]: dfs(UpperCAmelCase_ , 0 ) for i in range(len(UpperCAmelCase_ ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph _UpperCAmelCase = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
353
def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = int(UpperCamelCase_ ) if n_element < 1: UpperCamelCase_ = ValueError("a should be a positive number" ) raise my_error UpperCamelCase_ = [1] UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = (0, 0, 0) UpperCamelCase_ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _UpperCAmelCase = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') _UpperCAmelCase = hamming(int(n)) print('-----------------------------------------------------') print(f'''The list with nth numbers is: {hamming_numbers}''') print('-----------------------------------------------------')
328
0
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES _UpperCAmelCase = '''tiny-wmt19-en-ru''' # Build # borrowed from a test _UpperCAmelCase = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] _UpperCAmelCase = dict(zip(vocab, range(len(vocab)))) _UpperCAmelCase = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = Path(tmpdirname) _UpperCAmelCase = build_dir / VOCAB_FILES_NAMES['''src_vocab_file'''] _UpperCAmelCase = build_dir / VOCAB_FILES_NAMES['''tgt_vocab_file'''] _UpperCAmelCase = build_dir / VOCAB_FILES_NAMES['''merges_file'''] with open(src_vocab_file, 'w') as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, 'w') as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, 'w') as fp: fp.write('\n'.join(merges)) _UpperCAmelCase = FSMTTokenizer( langs=['en', 'ru'], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) _UpperCAmelCase = FSMTConfig( langs=['ru', 'en'], src_vocab_size=1_0_0_0, tgt_vocab_size=1_0_0_0, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) _UpperCAmelCase = FSMTForConditionalGeneration(config) print(f'''num of params {tiny_model.num_parameters()}''') # Test _UpperCAmelCase = tokenizer(['Making tiny model'], return_tensors='pt') _UpperCAmelCase = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(f'''Generated {mname_tiny}''') # Upload # transformers-cli upload tiny-wmt19-en-ru
354
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : List[Any] = IFImgaImgSuperResolutionPipeline _UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} _UpperCamelCase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) _UpperCamelCase : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowercase ( self: List[str] ) -> Any: """simple docstring""" return self._get_superresolution_dummy_components() def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[int]=0 ) -> List[Any]: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Any ) -> Union[str, Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowercase ( self: int ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowercase ( self: Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowercase ( self: List[Any] ) -> Union[str, Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowercase ( self: Dict ) -> Any: """simple docstring""" self._test_save_load_local() def lowercase ( self: Any ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
328
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _UpperCAmelCase = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure)
355
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent _UpperCAmelCase = {'UserAgent': UserAgent().random} def lowerCAmelCase_ ( UpperCamelCase_ ) -> dict: UpperCamelCase_ = script.contents[0] UpperCamelCase_ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class _UpperCamelCase : def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = f'''https://www.instagram.com/{username}/''' UpperCamelCase_ = self.get_json() def lowercase ( self: Union[str, Any] ) -> dict: """simple docstring""" UpperCamelCase_ = requests.get(self.url , headers=_SCREAMING_SNAKE_CASE ).text UpperCamelCase_ = BeautifulSoup(_SCREAMING_SNAKE_CASE , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self: Tuple ) -> str: """simple docstring""" return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self: List[Any] ) -> str: """simple docstring""" return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["username"] @property def lowercase ( self: int ) -> str: """simple docstring""" return self.user_data["full_name"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["biography"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["business_email"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["external_url"] @property def lowercase ( self: List[Any] ) -> int: """simple docstring""" return self.user_data["edge_followed_by"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_follow"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["profile_pic_url_hd"] @property def lowercase ( self: Optional[int] ) -> bool: """simple docstring""" return self.user_data["is_verified"] @property def lowercase ( self: List[str] ) -> bool: """simple docstring""" return self.user_data["is_private"] def lowerCAmelCase_ ( UpperCamelCase_ = "github" ) -> None: import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase_ = InstagramUser(UpperCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , UpperCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = InstagramUser('github') print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
328
0
def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Any: _enforce_args(__UpperCAmelCase , __UpperCAmelCase ) if n == 0: return 0 UpperCamelCase_ = float("-inf" ) for i in range(1 , n + 1 ): UpperCamelCase_ = max( __UpperCAmelCase , prices[i - 1] + naive_cut_rod_recursive(n - i , __UpperCAmelCase ) ) return max_revue def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Any: _enforce_args(__UpperCAmelCase , __UpperCAmelCase ) UpperCamelCase_ = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: UpperCamelCase_ = float("-inf" ) for i in range(1 , n + 1 ): UpperCamelCase_ = max( __UpperCAmelCase , prices[i - 1] + _top_down_cut_rod_recursive(n - i , __UpperCAmelCase , __UpperCAmelCase ) , ) UpperCamelCase_ = max_revenue return max_rev[n] def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Any: _enforce_args(__UpperCAmelCase , __UpperCAmelCase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. UpperCamelCase_ = [float("-inf" ) for _ in range(n + 1 )] UpperCamelCase_ = 0 for i in range(1 , n + 1 ): UpperCamelCase_ = max_rev[i] for j in range(1 , i + 1 ): UpperCamelCase_ = max(__UpperCAmelCase , prices[j - 1] + max_rev[i - j] ) UpperCamelCase_ = max_revenue_i return max_rev[n] def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> int: if n < 0: UpperCamelCase_ = F'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(__UpperCAmelCase ) if n > len(__UpperCAmelCase ): UpperCamelCase_ = ( "Each integral piece of rod must have a corresponding price. " F'''Got n = {n} but length of prices = {len(__UpperCAmelCase )}''' ) raise ValueError(__UpperCAmelCase ) def lowerCAmelCase_ ( ) -> Optional[int]: UpperCamelCase_ = [6, 10, 12, 15, 20, 23] UpperCamelCase_ = len(__UpperCAmelCase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. UpperCamelCase_ = 36 UpperCamelCase_ = top_down_cut_rod(__UpperCAmelCase , __UpperCAmelCase ) UpperCamelCase_ = bottom_up_cut_rod(__UpperCAmelCase , __UpperCAmelCase ) UpperCamelCase_ = naive_cut_rod_recursive(__UpperCAmelCase , __UpperCAmelCase ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
356
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _UpperCAmelCase = False _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = 'ybelkada/fonts' def lowerCAmelCase_ ( ) -> Dict: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: requires_backends(UpperCamelCase_ , ["torch"] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase_ , UpperCamelCase_ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = 36 , UpperCamelCase_ = "black" , UpperCamelCase_ = "white" , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> Image.Image: requires_backends(UpperCamelCase_ , "vision" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase_ ) UpperCamelCase_ = "\n".join(UpperCamelCase_ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase_ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase_ , "Arial.TTF" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase_ , encoding="UTF-8" , size=UpperCamelCase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , UpperCamelCase_ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase_ , UpperCamelCase_ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("RGB" , (image_width, image_height) , UpperCamelCase_ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase_ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase_ , fill=UpperCamelCase_ , font=UpperCamelCase_ ) return image def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> Union[str, Any]: requires_backends(UpperCamelCase_ , "vision" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase_ ) UpperCamelCase_ = render_text(UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase_ ) if infer_channel_dimension_format(UpperCamelCase_ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase_ , ChannelDimension.LAST ) return new_image class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''flattened_patches'''] def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: Optional[Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: dict , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = patch_size["height"], patch_size["width"] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_SCREAMING_SNAKE_CASE ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_SCREAMING_SNAKE_CASE , antialias=_SCREAMING_SNAKE_CASE , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([rows, 1] ).repeat(1 , _SCREAMING_SNAKE_CASE ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([1, columns] ).repeat(_SCREAMING_SNAKE_CASE , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_SCREAMING_SNAKE_CASE , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) return result def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: List[str] ) -> np.ndarray: """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = np.std(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: Optional[Dict[str, int]] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> ImageInput: """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("data_format" , _SCREAMING_SNAKE_CASE ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) UpperCamelCase_ = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) UpperCamelCase_ = kwargs.pop("font_bytes" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("font_path" , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [header_text] * len(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [ render_header(_SCREAMING_SNAKE_CASE , header_text[i] , font_bytes=_SCREAMING_SNAKE_CASE , font_path=_SCREAMING_SNAKE_CASE ) for i, image in enumerate(_SCREAMING_SNAKE_CASE ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_SCREAMING_SNAKE_CASE , max_patches=_SCREAMING_SNAKE_CASE , patch_size=_SCREAMING_SNAKE_CASE ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_outputs
328
0
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) _UpperCAmelCase = pytest.mark.integration @pytest.mark.parametrize("path" , ["paws", "csv"] ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: inspect_dataset(lowercase_ , lowercase_ ) UpperCamelCase_ = path + ".py" assert script_name in os.listdir(lowercase_ ) assert "__pycache__" not in os.listdir(lowercase_ ) @pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.parametrize("path" , ["accuracy"] ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: inspect_metric(lowercase_ , lowercase_ ) UpperCamelCase_ = path + ".py" assert script_name in os.listdir(lowercase_ ) assert "__pycache__" not in os.listdir(lowercase_ ) @pytest.mark.parametrize( "path, config_name, expected_splits" , [ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "dalle-mini--wit", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ] , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: UpperCamelCase_ = get_dataset_config_info(lowercase_ , config_name=lowercase_ ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception" , [ ("paws", None, ValueError), ] , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: with pytest.raises(lowercase_ ): get_dataset_config_info(lowercase_ , config_name=lowercase_ ) @pytest.mark.parametrize( "path, expected" , [ ("squad", "plain_text"), ("acronym_identification", "default"), ("lhoestq/squad", "plain_text"), ("lhoestq/test", "default"), ("lhoestq/demo1", "lhoestq--demo1"), ("dalle-mini/wit", "dalle-mini--wit"), ] , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> int: UpperCamelCase_ = get_dataset_config_names(lowercase_ ) assert expected in config_names @pytest.mark.parametrize( "path, expected_configs, expected_splits_in_first_config" , [ ("squad", ["plain_text"], ["train", "validation"]), ("dalle-mini/wit", ["dalle-mini--wit"], ["train"]), ("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]), ] , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Any: UpperCamelCase_ = get_dataset_infos(lowercase_ ) assert list(infos.keys() ) == expected_configs UpperCamelCase_ = expected_configs[0] assert expected_config in infos UpperCamelCase_ = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( "path, expected_config, expected_splits" , [ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "dalle-mini--wit", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ] , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: UpperCamelCase_ = get_dataset_infos(lowercase_ ) assert expected_config in infos UpperCamelCase_ = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception" , [ ("paws", None, ValueError), ] , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> str: with pytest.raises(lowercase_ ): get_dataset_split_names(lowercase_ , config_name=lowercase_ )
357
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: Any , _SCREAMING_SNAKE_CASE: int = 768 , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(1 , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(torch.ones(1 , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[Union[str, torch.device]] = None , _SCREAMING_SNAKE_CASE: Optional[torch.dtype] = None , ) -> List[Any]: """simple docstring""" UpperCamelCase_ = nn.Parameter(self.mean.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(self.std.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) return self def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = (embeds - self.mean) * 1.0 / self.std return embeds def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Dict: """simple docstring""" UpperCamelCase_ = (embeds * self.std) + self.mean return embeds
328
0
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy _UpperCAmelCase = logging.getLogger(__name__) _UpperCAmelCase = '''pytorch_model.bin''' @dataclasses.dataclass class _UpperCamelCase : _UpperCamelCase : List[str] = dataclasses.field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models.'''} ) _UpperCamelCase : Optional[int] = dataclasses.field( default=a_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co.'''} , ) @dataclasses.dataclass class _UpperCamelCase : _UpperCamelCase : Any = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the training data.'''} ) _UpperCamelCase : Union[str, Any] = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the data to predict on.'''} ) _UpperCamelCase : Dict = dataclasses.field( default=a_ , metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) _UpperCamelCase : str = dataclasses.field( default=a_ , metadata={'''help''': '''The name of the task to train on.'''} , ) _UpperCamelCase : Any = dataclasses.field( default=a_ , metadata={'''help''': '''The list of labels for the task.'''} ) @dataclasses.dataclass class _UpperCamelCase : _UpperCamelCase : Optional[Any] = dataclasses.field( metadata={'''help''': '''The output directory where the model predictions and checkpoints will be written.'''} ) _UpperCamelCase : Tuple = dataclasses.field( default='''accuracy''' , metadata={'''help''': '''The evaluation metric used for the task.'''} ) _UpperCamelCase : int = dataclasses.field( default='''no''' , metadata={ '''help''': '''The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]''' } , ) _UpperCamelCase : Union[str, Any] = dataclasses.field( default=1_0 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) _UpperCamelCase : List[str] = dataclasses.field( default=0.0 , metadata={ '''help''': '''How much the specified evaluation metric must improve to satisfy early stopping conditions.''' } , ) _UpperCamelCase : int = dataclasses.field( default=a_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the confidence score.'''} , ) _UpperCamelCase : Optional[Any] = dataclasses.field( default=a_ , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the validation performance.'''} , ) _UpperCamelCase : List[str] = dataclasses.field( default=a_ , metadata={'''help''': '''Whether to fine-tune on labeled data after pseudo training.'''} , ) _UpperCamelCase : List[str] = dataclasses.field( default=0.0 , metadata={'''help''': '''Confidence threshold for pseudo-labeled data filtering.'''} , ) _UpperCamelCase : List[Any] = dataclasses.field( default=1_0_0 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , ) _UpperCamelCase : int = dataclasses.field( default=a_ , metadata={'''help''': '''Random seed for initialization.'''} , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: UpperCamelCase_ = dataset.filter(lambda UpperCamelCase_ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 UpperCamelCase_ = int(eval_result * len(A_ ) ) print(A_ ) UpperCamelCase_ = dataset.sort("probability" , reverse=A_ ) UpperCamelCase_ = dataset.select(range(A_ ) ) UpperCamelCase_ = dataset.remove_columns(["label", "probability"] ) UpperCamelCase_ = dataset.rename_column("prediction" , "label" ) UpperCamelCase_ = dataset.map(lambda UpperCamelCase_ : {"label": idalabel[example["label"]]} ) UpperCamelCase_ = dataset.shuffle(seed=args.seed ) UpperCamelCase_ = os.path.join(A_ , F'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(A_ , index=A_ ) else: dataset.to_json(A_ ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> List[str]: UpperCamelCase_ = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() UpperCamelCase_ = STModelArguments(model_name_or_path=A_ ) UpperCamelCase_ = STDataArguments(train_file=A_ , infer_file=A_ ) UpperCamelCase_ = STTrainingArguments(output_dir=A_ ) UpperCamelCase_ = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(A_ ).items(): setattr(A_ , A_ , A_ ) for key, value in kwargs.items(): if hasattr(A_ , A_ ): setattr(A_ , A_ , A_ ) # Sanity checks UpperCamelCase_ = {} UpperCamelCase_ = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None UpperCamelCase_ = args.train_file UpperCamelCase_ = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None UpperCamelCase_ = args.eval_file for key in data_files: UpperCamelCase_ = data_files[key].split("." )[-1] assert extension in ["csv", "json"], F'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: UpperCamelCase_ = extension else: assert extension == args.data_file_extension, F'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), F'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("Creating the initial data directory for self-training..." ) UpperCamelCase_ = F'''{args.output_dir}/self-train_iter-{{}}'''.format UpperCamelCase_ = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=A_ ) os.makedirs(A_ , exist_ok=A_ ) accelerator.wait_for_everyone() UpperCamelCase_ = None UpperCamelCase_ = None UpperCamelCase_ = 0 UpperCamelCase_ = False # Show the progress bar UpperCamelCase_ = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): UpperCamelCase_ = data_dir_format(A_ ) assert os.path.exists(A_ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 UpperCamelCase_ = os.path.join(A_ , "stage-1" ) UpperCamelCase_ = { '''accelerator''': accelerator, '''model_name_or_path''': args.model_name_or_path, '''cache_dir''': args.cache_dir, '''do_train''': True, '''train_file''': data_files['''train'''] if iteration == 0 else data_files['''train_pseudo'''], '''do_eval''': True if args.eval_file is not None else False, '''eval_file''': data_files['''eval'''], '''do_predict''': True, '''infer_file''': data_files['''infer'''], '''task_name''': args.task_name, '''label_list''': args.label_list, '''output_dir''': current_output_dir, '''eval_metric''': args.eval_metric, '''evaluation_strategy''': args.evaluation_strategy, '''early_stopping_patience''': args.early_stopping_patience, '''early_stopping_threshold''': args.early_stopping_threshold, '''seed''': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(A_ , A_ ): arguments_dict.update({key: value} ) UpperCamelCase_ = os.path.join(A_ , "best-checkpoint" , A_ ) if os.path.exists(A_ ): logger.info( "Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1." , A_ , A_ , ) else: logger.info("***** Running self-training: iteration: %d, stage: 1 *****" , A_ ) finetune(**A_ ) accelerator.wait_for_everyone() assert os.path.exists(A_ ) logger.info("Self-training job completed: iteration: %d, stage: 1." , A_ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data UpperCamelCase_ = os.path.join(A_ , "best-checkpoint" ) UpperCamelCase_ = os.path.join(A_ , "stage-2" ) # Update arguments_dict UpperCamelCase_ = model_path UpperCamelCase_ = data_files['''train'''] UpperCamelCase_ = current_output_dir UpperCamelCase_ = os.path.join(A_ , "best-checkpoint" , A_ ) if os.path.exists(A_ ): logger.info( "Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2." , A_ , A_ , ) else: logger.info("***** Running self-training: iteration: %d, stage: 2 *****" , A_ ) finetune(**A_ ) accelerator.wait_for_everyone() assert os.path.exists(A_ ) logger.info("Self-training job completed: iteration: %d, stage: 2." , A_ ) UpperCamelCase_ = iteration UpperCamelCase_ = data_dir_format(iteration + 1 ) UpperCamelCase_ = AutoConfig.from_pretrained(os.path.join(A_ , "best-checkpoint" ) ) UpperCamelCase_ = config.idalabel UpperCamelCase_ = os.path.join(A_ , "eval_results_best-checkpoint.json" ) UpperCamelCase_ = os.path.join(A_ , "test_results_best-checkpoint.json" ) assert os.path.exists(A_ ) with open(A_ , "r" ) as f: UpperCamelCase_ = float(json.load(A_ )[args.eval_metric] ) UpperCamelCase_ = os.path.join(A_ , "infer_output_best-checkpoint.csv" ) assert os.path.exists(A_ ) # Loading the dataset from local csv or json files. UpperCamelCase_ = load_dataset(args.data_file_extension , data_files={"data": data_files["infer"]} )['''data'''] UpperCamelCase_ = load_dataset("csv" , data_files={"data": infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(A_ , exist_ok=A_ ) shutil.copy(A_ , os.path.join(A_ , F'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(A_ ): shutil.copy(A_ , os.path.join(A_ , F'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(A_ , A_ , A_ , A_ , A_ , A_ ) accelerator.wait_for_everyone() UpperCamelCase_ = os.path.join(A_ , F'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: UpperCamelCase_ = eval_result if best_iteration is None: UpperCamelCase_ = new_iteration UpperCamelCase_ = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: UpperCamelCase_ = new_iteration UpperCamelCase_ = new_eval_result UpperCamelCase_ = 0 else: if new_eval_result == best_eval_result: UpperCamelCase_ = new_iteration UpperCamelCase_ = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: UpperCamelCase_ = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("Best iteration: %d" , A_ ) logger.info("Best evaluation result: %s = %f" , args.eval_metric , A_ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(A_ , F'''eval_results_iter-{iteration}.json''' ) , os.path.join(A_ , "eval_results_best-iteration.json" ) , ) else: # Assume that the last iteration is the best logger.info("Best iteration: %d" , args.max_selftrain_iterations - 1 ) logger.info("Best evaluation result: %s = %f" , args.eval_metric , A_ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(A_ , F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(A_ , "eval_results_best-iteration.json" ) , )
358
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _UpperCAmelCase = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) _UpperCAmelCase = logging.getLogger() def lowerCAmelCase_ ( ) -> Optional[int]: UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCamelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_="eval" ) -> Any: UpperCamelCase_ = os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) if os.path.exists(UpperCamelCase_ ): with open(UpperCamelCase_ , "r" ) as f: return json.load(UpperCamelCase_ ) raise ValueError(F'''can\'t find {path}''' ) _UpperCAmelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _UpperCamelCase ( lowerCAmelCase_ ): def lowercase ( self: Optional[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_glue.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) @slow def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_clm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 100 ) @slow def lowercase ( self: Any ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_summarization_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE , split="test" ) self.assertGreaterEqual(result["test_rouge1"] , 10 ) self.assertGreaterEqual(result["test_rouge2"] , 2 ) self.assertGreaterEqual(result["test_rougeL"] , 7 ) self.assertGreaterEqual(result["test_rougeLsum"] , 7 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 42 ) @slow def lowercase ( self: Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_ta_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.42 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_ner.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertGreaterEqual(result["eval_f1"] , 0.3 ) @slow def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_qa.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_f1"] , 30 ) self.assertGreaterEqual(result["eval_exact"] , 30 )
328
0
def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> int: if len(_lowercase ) != len(_lowercase ): raise ValueError("The length of profit and weight must be same." ) if max_weight <= 0: raise ValueError("max_weight must greater than zero." ) if any(p < 0 for p in profit ): raise ValueError("Profit can not be negative." ) if any(w < 0 for w in weight ): raise ValueError("Weight can not be negative." ) # List created to store profit gained for the 1kg in case of each weight # respectively. Calculate and append profit/weight for each element. UpperCamelCase_ = [p / w for p, w in zip(_lowercase , _lowercase )] # Creating a copy of the list and sorting profit/weight in ascending order UpperCamelCase_ = sorted(_lowercase ) # declaring useful variables UpperCamelCase_ = len(_lowercase ) UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 # loop till the total weight do not reach max limit e.g. 15 kg and till i<length while limit <= max_weight and i < length: # flag value for encountered greatest element in sorted_profit_by_weight UpperCamelCase_ = sorted_profit_by_weight[length - i - 1] UpperCamelCase_ = profit_by_weight.index(_lowercase ) UpperCamelCase_ = -1 # check if the weight encountered is less than the total weight # encountered before. if max_weight - limit >= weight[index]: limit += weight[index] # Adding profit gained for the given weight 1 === # weight[index]/weight[index] gain += 1 * profit[index] else: # Since the weight encountered is greater than limit, therefore take the # required number of remaining kgs and calculate profit for it. # weight remaining / weight[index] gain += (max_weight - limit) / weight[index] * profit[index] break i += 1 return gain if __name__ == "__main__": print( 'Input profits, weights, and then max_weight (all positive ints) separated by ' 'spaces.' ) _UpperCAmelCase = [int(x) for x in input('Input profits separated by spaces: ').split()] _UpperCAmelCase = [int(x) for x in input('Input weights separated by spaces: ').split()] _UpperCAmelCase = int(input('Max weight allowed: ')) # Function Call calc_profit(profit, weight, max_weight)
359
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: for param in module.parameters(): UpperCamelCase_ = False def lowerCAmelCase_ ( ) -> Dict: UpperCamelCase_ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): UpperCamelCase_ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def lowerCAmelCase_ ( ) -> List[str]: UpperCamelCase_ = datetime.now() UpperCamelCase_ = current_time.strftime("%H:%M:%S" ) return timestamp
328
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = SwinConfig( embed_dim=192 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=["stage2", "stage3", "stage4"] , ) UpperCamelCase_ = DetaConfig( backbone_config=UpperCamelCase_ , num_queries=900 , encoder_ffn_dim=2048 , decoder_ffn_dim=2048 , num_feature_levels=5 , assign_first_stage=UpperCamelCase_ , with_box_refine=UpperCamelCase_ , two_stage=UpperCamelCase_ , ) # set labels UpperCamelCase_ = """huggingface/label-files""" if "o365" in model_name: UpperCamelCase_ = 366 UpperCamelCase_ = """object365-id2label.json""" else: UpperCamelCase_ = 91 UpperCamelCase_ = """coco-detection-id2label.json""" UpperCamelCase_ = num_labels UpperCamelCase_ = json.load(open(cached_download(hf_hub_url(UpperCamelCase_ , UpperCamelCase_ , repo_type="dataset" ) ) , "r" ) ) UpperCamelCase_ = {int(UpperCamelCase_ ): v for k, v in idalabel.items()} UpperCamelCase_ = idalabel UpperCamelCase_ = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase_ ( UpperCamelCase_ ) -> Optional[int]: UpperCamelCase_ = [] # stem # fmt: off rename_keys.append(("backbone.0.body.patch_embed.proj.weight", "model.backbone.model.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("backbone.0.body.patch_embed.proj.bias", "model.backbone.model.embeddings.patch_embeddings.projection.bias") ) rename_keys.append(("backbone.0.body.patch_embed.norm.weight", "model.backbone.model.embeddings.norm.weight") ) rename_keys.append(("backbone.0.body.patch_embed.norm.bias", "model.backbone.model.embeddings.norm.bias") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.reduction.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.bias''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append(("backbone.0.body.norm1.weight", "model.backbone.model.hidden_states_norms.stage2.weight") ) rename_keys.append(("backbone.0.body.norm1.bias", "model.backbone.model.hidden_states_norms.stage2.bias") ) rename_keys.append(("backbone.0.body.norm2.weight", "model.backbone.model.hidden_states_norms.stage3.weight") ) rename_keys.append(("backbone.0.body.norm2.bias", "model.backbone.model.hidden_states_norms.stage3.bias") ) rename_keys.append(("backbone.0.body.norm3.weight", "model.backbone.model.hidden_states_norms.stage4.weight") ) rename_keys.append(("backbone.0.body.norm3.bias", "model.backbone.model.hidden_states_norms.stage4.bias") ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', F'''model.encoder.layers.{i}.self_attn.attention_weights.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', F'''model.encoder.layers.{i}.self_attn.attention_weights.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', F'''model.encoder.layers.{i}.self_attn.value_proj.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', F'''model.encoder.layers.{i}.self_attn.value_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', F'''model.encoder.layers.{i}.self_attn.output_proj.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', F'''model.encoder.layers.{i}.self_attn.output_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.weight''', F'''model.encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''model.encoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''model.encoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''model.encoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''model.encoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''model.encoder.layers.{i}.fc2.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''model.encoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''model.encoder.layers.{i}.final_layer_norm.bias''') ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.weight''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''model.decoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''model.decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.weight''', F'''model.decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.bias''', F'''model.decoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''model.decoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''model.decoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''model.decoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''model.decoder.layers.{i}.fc2.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''model.decoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''model.decoder.layers.{i}.final_layer_norm.bias''') ) # fmt: on return rename_keys def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = dct.pop(UpperCamelCase_ ) UpperCamelCase_ = val def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): UpperCamelCase_ = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) UpperCamelCase_ = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight''' ) UpperCamelCase_ = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict UpperCamelCase_ = in_proj_weight[:dim, :] UpperCamelCase_ = in_proj_bias[: dim] UpperCamelCase_ = in_proj_weight[ dim : dim * 2, : ] UpperCamelCase_ = in_proj_bias[ dim : dim * 2 ] UpperCamelCase_ = in_proj_weight[ -dim :, : ] UpperCamelCase_ = in_proj_bias[-dim :] # fmt: on def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: # transformer decoder self-attention layers UpperCamelCase_ = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention UpperCamelCase_ = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) UpperCamelCase_ = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict UpperCamelCase_ = in_proj_weight[:hidden_size, :] UpperCamelCase_ = in_proj_bias[:hidden_size] UpperCamelCase_ = in_proj_weight[ hidden_size : hidden_size * 2, : ] UpperCamelCase_ = in_proj_bias[hidden_size : hidden_size * 2] UpperCamelCase_ = in_proj_weight[-hidden_size:, :] UpperCamelCase_ = in_proj_bias[-hidden_size:] def lowerCAmelCase_ ( ) -> Tuple: UpperCamelCase_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCamelCase_ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: UpperCamelCase_ = get_deta_config(UpperCamelCase_ ) # load original state dict if model_name == "deta-swin-large": UpperCamelCase_ = hf_hub_download(repo_id="nielsr/deta-checkpoints" , filename="adet_swin_ft.pth" ) elif model_name == "deta-swin-large-o365": UpperCamelCase_ = hf_hub_download(repo_id="jozhang97/deta-swin-l-o365" , filename="deta_swin_pt_o365.pth" ) else: raise ValueError(F'''Model name {model_name} not supported''' ) UpperCamelCase_ = torch.load(UpperCamelCase_ , map_location="cpu" )["""model"""] # original state dict for name, param in state_dict.items(): print(UpperCamelCase_ , param.shape ) # rename keys UpperCamelCase_ = create_rename_keys(UpperCamelCase_ ) for src, dest in rename_keys: rename_key(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) read_in_swin_q_k_v(UpperCamelCase_ , config.backbone_config ) read_in_decoder_q_k_v(UpperCamelCase_ , UpperCamelCase_ ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: UpperCamelCase_ = state_dict.pop(UpperCamelCase_ ) UpperCamelCase_ = val if "input_proj" in key: UpperCamelCase_ = state_dict.pop(UpperCamelCase_ ) UpperCamelCase_ = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: UpperCamelCase_ = state_dict.pop(UpperCamelCase_ ) UpperCamelCase_ = val # finally, create HuggingFace model and load state dict UpperCamelCase_ = DetaForObjectDetection(UpperCamelCase_ ) model.load_state_dict(UpperCamelCase_ ) model.eval() UpperCamelCase_ = """cuda""" if torch.cuda.is_available() else """cpu""" model.to(UpperCamelCase_ ) # load image processor UpperCamelCase_ = DetaImageProcessor(format="coco_detection" ) # verify our conversion on image UpperCamelCase_ = prepare_img() UpperCamelCase_ = processor(images=UpperCamelCase_ , return_tensors="pt" ) UpperCamelCase_ = encoding["""pixel_values"""] UpperCamelCase_ = model(pixel_values.to(UpperCamelCase_ ) ) # verify logits print("Logits:" , outputs.logits[0, :3, :3] ) print("Boxes:" , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": UpperCamelCase_ = torch.tensor( [[-7.63_08, -2.84_85, -5.37_37], [-7.20_37, -4.55_05, -4.80_27], [-7.29_43, -4.26_11, -4.66_17]] ) UpperCamelCase_ = torch.tensor([[0.49_87, 0.49_69, 0.99_99], [0.25_49, 0.54_98, 0.48_05], [0.54_98, 0.27_57, 0.05_69]] ) elif model_name == "deta-swin-large-o365": UpperCamelCase_ = torch.tensor( [[-8.01_22, -3.57_20, -4.97_17], [-8.15_47, -3.68_86, -4.63_89], [-7.66_10, -3.61_94, -5.01_34]] ) UpperCamelCase_ = torch.tensor([[0.25_23, 0.55_49, 0.48_81], [0.77_15, 0.41_49, 0.46_01], [0.55_03, 0.27_53, 0.05_75]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(UpperCamelCase_ ) , atol=1e-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(UpperCamelCase_ ) , atol=1e-4 ) print("Everything ok!" ) if pytorch_dump_folder_path: # Save model and processor logger.info(F'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase_ ).mkdir(exist_ok=UpperCamelCase_ ) model.save_pretrained(UpperCamelCase_ ) processor.save_pretrained(UpperCamelCase_ ) # Push to hub if push_to_hub: print("Pushing model and processor to hub..." ) model.push_to_hub(F'''jozhang97/{model_name}''' ) processor.push_to_hub(F'''jozhang97/{model_name}''' ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', type=str, default='deta-swin-large', choices=['deta-swin-large', 'deta-swin-large-o365'], help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) _UpperCAmelCase = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
360
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 _UpperCAmelCase = '▁' _UpperCAmelCase = {'vocab_file': 'spiece.model'} _UpperCAmelCase = { 'vocab_file': {'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'} } _UpperCAmelCase = { 'google/pegasus-xsum': 5_1_2, } _UpperCAmelCase = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = VOCAB_FILES_NAMES _UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[int] = ['''input_ids''', '''attention_mask'''] def __init__( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: str="<pad>" , _SCREAMING_SNAKE_CASE: Optional[Any]="</s>" , _SCREAMING_SNAKE_CASE: Any="<unk>" , _SCREAMING_SNAKE_CASE: int="<mask_2>" , _SCREAMING_SNAKE_CASE: List[Any]="<mask_1>" , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: Optional[int]=103 , _SCREAMING_SNAKE_CASE: Optional[Dict[str, Any]] = None , **_SCREAMING_SNAKE_CASE: Dict , ) -> None: """simple docstring""" UpperCamelCase_ = offset if additional_special_tokens is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError( f'''additional_special_tokens should be of type {type(_SCREAMING_SNAKE_CASE )}, but is''' f''' {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'''<unk_{i}>''' for i in range(len(_SCREAMING_SNAKE_CASE ) , self.offset - 1 ) ] if len(set(_SCREAMING_SNAKE_CASE ) ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError( "Please make sure that the provided additional_special_tokens do not contain an incorrectly" f''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) UpperCamelCase_ = additional_special_tokens_extended else: UpperCamelCase_ = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'''<unk_{i}>''' for i in range(2 , self.offset )] UpperCamelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token_sent=_SCREAMING_SNAKE_CASE , offset=_SCREAMING_SNAKE_CASE , additional_special_tokens=_SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = mask_token_sent UpperCamelCase_ = vocab_file UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_SCREAMING_SNAKE_CASE ) # add special tokens to encoder dict UpperCamelCase_ = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) UpperCamelCase_ = {v: k for k, v in self.encoder.items()} @property def lowercase ( self: Dict ) -> int: """simple docstring""" return len(self.sp_model ) + self.offset def lowercase ( self: int ) -> Dict[str, int]: """simple docstring""" UpperCamelCase_ = {self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self: Optional[int] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = self.__dict__.copy() UpperCamelCase_ = None return state def __setstate__( self: List[Any] , _SCREAMING_SNAKE_CASE: List[Any] ) -> Any: """simple docstring""" UpperCamelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCamelCase_ = {} UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_SCREAMING_SNAKE_CASE , out_type=_SCREAMING_SNAKE_CASE ) def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: str ) -> int: """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] UpperCamelCase_ = self.sp_model.piece_to_id(_SCREAMING_SNAKE_CASE ) return sp_id + self.offset def lowercase ( self: str , _SCREAMING_SNAKE_CASE: int ) -> str: """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: UpperCamelCase_ = self.sp_model.IdToPiece(index - self.offset ) return token def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = [] UpperCamelCase_ = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) + token UpperCamelCase_ = [] else: current_sub_tokens.append(_SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) return out_string.strip() def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Optional[int]=False ) -> Union[str, Any]: """simple docstring""" return 1 def lowercase ( self: int , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: List , _SCREAMING_SNAKE_CASE: Optional[List] = None , _SCREAMING_SNAKE_CASE: bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) elif token_ids_a is None: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any]=None ) -> List[int]: """simple docstring""" if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCamelCase_ = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(_SCREAMING_SNAKE_CASE , "wb" ) as fi: UpperCamelCase_ = self.sp_model.serialized_model_proto() fi.write(_SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
328
0
import doctest from collections import deque import numpy as np class _UpperCamelCase : def __init__( self: List[Any] ) -> None: """simple docstring""" UpperCamelCase_ = [2, 1, 2, -1] UpperCamelCase_ = [1, 2, 3, 4] def lowercase ( self: List[str] ) -> list[float]: """simple docstring""" UpperCamelCase_ = len(self.first_signal ) UpperCamelCase_ = len(self.second_signal ) UpperCamelCase_ = max(lowerCamelCase_ , lowerCamelCase_ ) # create a zero matrix of max_length x max_length UpperCamelCase_ = [[0] * max_length for i in range(lowerCamelCase_ )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(lowerCamelCase_ ): UpperCamelCase_ = deque(self.second_signal ) rotated_signal.rotate(lowerCamelCase_ ) for j, item in enumerate(lowerCamelCase_ ): matrix[i][j] += item # multiply the matrix with the first signal UpperCamelCase_ = np.matmul(np.transpose(lowerCamelCase_ ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(lowerCamelCase_ , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
361
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { 'configuration_tapas': ['TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TapasConfig'], 'tokenization_tapas': ['TapasTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TapasForMaskedLM', 'TapasForQuestionAnswering', 'TapasForSequenceClassification', 'TapasModel', 'TapasPreTrainedModel', 'load_tf_weights_in_tapas', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFTapasForMaskedLM', 'TFTapasForQuestionAnswering', 'TFTapasForSequenceClassification', 'TFTapasModel', 'TFTapasPreTrainedModel', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
328
0
"""simple docstring""" from functools import lru_cache @lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: if num < 0: raise ValueError("Number should not be negative." ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
362
import argparse import json from tqdm import tqdm def lowerCAmelCase_ ( ) -> Tuple: UpperCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--src_path" , type=UpperCamelCase_ , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , ) parser.add_argument( "--evaluation_set" , type=UpperCamelCase_ , help="where to store parsed evaluation_set file" , ) parser.add_argument( "--gold_data_path" , type=UpperCamelCase_ , help="where to store parsed gold_data_path file" , ) UpperCamelCase_ = parser.parse_args() with open(args.src_path , "r" ) as src_file, open(args.evaluation_set , "w" ) as eval_file, open( args.gold_data_path , "w" ) as gold_file: UpperCamelCase_ = json.load(UpperCamelCase_ ) for dpr_record in tqdm(UpperCamelCase_ ): UpperCamelCase_ = dpr_record["question"] UpperCamelCase_ = [context["title"] for context in dpr_record["positive_ctxs"]] eval_file.write(question + "\n" ) gold_file.write("\t".join(UpperCamelCase_ ) + "\n" ) if __name__ == "__main__": main()
328
0
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def lowerCAmelCase_ ( UpperCamelCase_ ) -> tuple: return (data["data"], data["target"]) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> XGBClassifier: UpperCamelCase_ = XGBClassifier() classifier.fit(_lowercase , _lowercase ) return classifier def lowerCAmelCase_ ( ) -> None: UpperCamelCase_ = load_iris() UpperCamelCase_ = data_handling(_lowercase ) UpperCamelCase_ = train_test_split( _lowercase , _lowercase , test_size=0.25 ) UpperCamelCase_ = iris["target_names"] # Create an XGBoost Classifier from the training data UpperCamelCase_ = xgboost(_lowercase , _lowercase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( _lowercase , _lowercase , _lowercase , display_labels=_lowercase , cmap="Blues" , normalize="true" , ) plt.title("Normalized Confusion Matrix - IRIS Dataset" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
363
import requests from bsa import BeautifulSoup def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = BeautifulSoup(requests.get(UpperCamelCase_ , params=UpperCamelCase_ ).content , "html.parser" ) UpperCamelCase_ = soup.find("div" , attrs={"class": "gs_ri"} ) UpperCamelCase_ = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": _UpperCAmelCase = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
328
0
import argparse import os import re _UpperCAmelCase = """src/transformers/models/auto""" # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict _UpperCAmelCase = re.compile(r'[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict') # re pattern that matches identifiers in mappings _UpperCAmelCase = re.compile(r'\s*\(\s*\"(\S[^\"]+)\"') def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = False ) -> int: with open(UpperCamelCase_ , "r" , encoding="utf-8" ) as f: UpperCamelCase_ = f.read() UpperCamelCase_ = content.split("\n" ) UpperCamelCase_ = [] UpperCamelCase_ = 0 while line_idx < len(UpperCamelCase_ ): if _re_intro_mapping.search(lines[line_idx] ) is not None: UpperCamelCase_ = len(re.search(r"^(\s*)\S" , lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(" " * indent + "(" ): new_lines.append(lines[line_idx] ) line_idx += 1 UpperCamelCase_ = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": UpperCamelCase_ = line_idx while not lines[line_idx].startswith(" " * indent + ")" ): line_idx += 1 blocks.append("\n".join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers UpperCamelCase_ = sorted(UpperCamelCase_ , key=lambda UpperCamelCase_ : _re_identifier.search(UpperCamelCase_ ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(UpperCamelCase_ , "w" , encoding="utf-8" ) as f: f.write("\n".join(UpperCamelCase_ ) ) elif "\n".join(UpperCamelCase_ ) != content: return True def lowerCAmelCase_ ( UpperCamelCase_ = False ) -> Dict: UpperCamelCase_ = [os.path.join(UpperCamelCase_ , UpperCamelCase_ ) for f in os.listdir(UpperCamelCase_ ) if f.endswith(".py" )] UpperCamelCase_ = [sort_auto_mapping(UpperCamelCase_ , overwrite=UpperCamelCase_ ) for fname in fnames] if not overwrite and any(UpperCamelCase_ ): UpperCamelCase_ = [f for f, d in zip(UpperCamelCase_ , UpperCamelCase_ ) if d] raise ValueError( F'''The following files have auto mappings that need sorting: {", ".join(UpperCamelCase_ )}. Run `make style` to fix''' " this." ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') _UpperCAmelCase = parser.parse_args() sort_all_auto_mappings(not args.check_only)
364
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: List[str] , *, _SCREAMING_SNAKE_CASE: int = 4 , _SCREAMING_SNAKE_CASE: int = 768 , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: str , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(_SCREAMING_SNAKE_CASE ) ) # parameters for additional clip time embeddings UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # parameters for encoder hidden states UpperCamelCase_ = clip_extra_context_tokens UpperCamelCase_ = nn.Linear( _SCREAMING_SNAKE_CASE , self.clip_extra_context_tokens * cross_attention_dim ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.LayerNorm(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , *, _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> str: """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings UpperCamelCase_ = image_embeddings.shape[0] UpperCamelCase_ = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) UpperCamelCase_ = classifier_free_guidance_embeddings.expand( _SCREAMING_SNAKE_CASE , -1 ) UpperCamelCase_ = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] UpperCamelCase_ = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... UpperCamelCase_ = self.embedding_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.clip_image_embeddings_project_to_time_embeddings(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" UpperCamelCase_ = self.clip_extra_context_tokens_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = clip_extra_context_tokens.reshape(_SCREAMING_SNAKE_CASE , -1 , self.clip_extra_context_tokens ) UpperCamelCase_ = clip_extra_context_tokens.permute(0 , 2 , 1 ) UpperCamelCase_ = self.encoder_hidden_states_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.text_encoder_hidden_states_norm(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
328
0
from __future__ import annotations def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> list[str]: if partitions <= 0: raise ValueError("partitions must be a positive number!" ) if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!" ) UpperCamelCase_ = number_of_bytes // partitions UpperCamelCase_ = [] for i in range(snake_case__ ): UpperCamelCase_ = i * bytes_per_partition + 1 UpperCamelCase_ = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(F'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
365
from functools import lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> set: UpperCamelCase_ = 2 UpperCamelCase_ = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(UpperCamelCase_ ) if n > 1: factors.add(UpperCamelCase_ ) return factors @lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: return len(unique_prime_factors(UpperCamelCase_ ) ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> bool: return len(set(UpperCamelCase_ ) ) in (0, 1) def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = 2 while True: # Increment each value of a generated range UpperCamelCase_ = [base + i for i in range(UpperCamelCase_ )] # Run elements through out unique_prime_factors function # Append our target number to the end. UpperCamelCase_ = [upf_len(UpperCamelCase_ ) for x in group] checker.append(UpperCamelCase_ ) # If all numbers in the list are equal, return the group variable. if equality(UpperCamelCase_ ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase_ ( UpperCamelCase_ = 4 ) -> int: UpperCamelCase_ = run(UpperCamelCase_ ) return results[0] if len(UpperCamelCase_ ) else None if __name__ == "__main__": print(solution())
328
0
import re def lowerCAmelCase_ ( UpperCamelCase_ ) -> Any: if len(re.findall("[ATCG]" , lowerCAmelCase__ ) ) != len(lowerCAmelCase__ ): raise ValueError("Invalid Strand" ) return dna.translate(dna.maketrans("ATCG" , "TAGC" ) ) if __name__ == "__main__": import doctest doctest.testmod()
366
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = len(UpperCamelCase_ ) UpperCamelCase_ = len(matrix[0] ) UpperCamelCase_ = min(UpperCamelCase_ , UpperCamelCase_ ) for row in range(UpperCamelCase_ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , UpperCamelCase_ ): UpperCamelCase_ = matrix[col][row] / matrix[row][row] for i in range(UpperCamelCase_ , UpperCamelCase_ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows UpperCamelCase_ = True for i in range(row + 1 , UpperCamelCase_ ): if matrix[i][row] != 0: UpperCamelCase_ , UpperCamelCase_ = matrix[i], matrix[row] UpperCamelCase_ = False break if reduce: rank -= 1 for i in range(UpperCamelCase_ ): UpperCamelCase_ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
328
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer _UpperCAmelCase = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast _UpperCAmelCase = TaTokenizerFast _UpperCAmelCase = {'configuration_mt5': ['MT5Config', 'MT5OnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'MT5EncoderModel', 'MT5ForConditionalGeneration', 'MT5ForQuestionAnswering', 'MT5Model', 'MT5PreTrainedModel', 'MT5Stack', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ['TFMT5EncoderModel', 'TFMT5ForConditionalGeneration', 'TFMT5Model'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ['FlaxMT5EncoderModel', 'FlaxMT5ForConditionalGeneration', 'FlaxMT5Model'] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys _UpperCAmelCase = _LazyModule( __name__, globals()['__file__'], _import_structure, extra_objects={'MT5Tokenizer': MTaTokenizer, 'MT5TokenizerFast': MTaTokenizerFast}, module_spec=__spec__, )
367
import math def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(UpperCamelCase_ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. _UpperCAmelCase = 'Enter the base and the power separated by a comma: ' _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) # We find the log of each number, using the function res(), which takes two # arguments. _UpperCAmelCase = res(xa, ya) _UpperCAmelCase = res(xa, ya) # We check for the largest number if resa > resa: print('Largest number is', xa, '^', ya) elif resa > resa: print('Largest number is', xa, '^', ya) else: print('Both are equal')
328
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _UpperCAmelCase = {"configuration_deit": ["DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeiTConfig", "DeiTOnnxConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ["DeiTFeatureExtractor"] _UpperCAmelCase = ["DeiTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ "DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "DeiTForImageClassification", "DeiTForImageClassificationWithTeacher", "DeiTForMaskedImageModeling", "DeiTModel", "DeiTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ "TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDeiTForImageClassification", "TFDeiTForImageClassificationWithTeacher", "TFDeiTForMaskedImageModeling", "TFDeiTModel", "TFDeiTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
368
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor _UpperCAmelCase = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> List[Any]: if isinstance(UpperCamelCase_ , torch.Tensor ): return image elif isinstance(UpperCamelCase_ , PIL.Image.Image ): UpperCamelCase_ = [image] UpperCamelCase_ = [trans(img.convert("RGB" ) ) for img in image] UpperCamelCase_ = torch.stack(UpperCamelCase_ ) return image class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase_ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[Any]: """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> int: """simple docstring""" UpperCamelCase_ = min(int(num_inference_steps * strength ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[int]=None ) -> List[Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = image.to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase_ = init_latents.shape UpperCamelCase_ = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) # get latents print("add noise to latents at timestep" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.scheduler.add_noise(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = init_latents return latents @torch.no_grad() def __call__( self: Dict , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, PIL.Image.Image] = None , _SCREAMING_SNAKE_CASE: float = 0.8 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: int = 50 , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" self.check_inputs(_SCREAMING_SNAKE_CASE ) # 2. Preprocess image UpperCamelCase_ = preprocess(_SCREAMING_SNAKE_CASE ) # 3. set timesteps self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=self.device ) UpperCamelCase_ , UpperCamelCase_ = self.get_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.device ) UpperCamelCase_ = timesteps[:1].repeat(_SCREAMING_SNAKE_CASE ) # 4. Prepare latent variables UpperCamelCase_ = self.prepare_latents(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.unet.dtype , self.device , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = latents # 5. Denoising loop for t in self.progress_bar(_SCREAMING_SNAKE_CASE ): # 1. predict noise model_output UpperCamelCase_ = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 UpperCamelCase_ = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , use_clipped_model_output=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample UpperCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
328
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _UpperCAmelCase = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure)
369
import re from filelock import FileLock try: import nltk _UpperCAmelCase = True except (ImportError, ModuleNotFoundError): _UpperCAmelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCAmelCase_ ( UpperCamelCase_ ) -> str: re.sub("<n>" , "" , UpperCamelCase_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase_ ) )
328
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) _UpperCAmelCase = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
370
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = DiTPipeline _UpperCamelCase : Any = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS _UpperCamelCase : Dict = PipelineTesterMixin.required_optional_params - { '''latents''', '''num_images_per_prompt''', '''callback''', '''callback_steps''', } _UpperCamelCase : Optional[int] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS _UpperCamelCase : Dict = False def lowercase ( self: str ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn="gelu-approximate" , num_embeds_ada_norm=1000 , norm_type="ada_norm_zero" , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = AutoencoderKL() UpperCamelCase_ = DDIMScheduler() UpperCamelCase_ = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler} return components def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: List[str]=0 ) -> Dict: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "class_labels": [1], "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def lowercase ( self: Any ) -> List[str]: """simple docstring""" UpperCamelCase_ = "cpu" UpperCamelCase_ = self.get_dummy_components() UpperCamelCase_ = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(**_SCREAMING_SNAKE_CASE ).images UpperCamelCase_ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) UpperCamelCase_ = np.array([0.29_46, 0.66_01, 0.43_29, 0.32_96, 0.41_44, 0.53_19, 0.72_73, 0.50_13, 0.44_57] ) UpperCamelCase_ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1e-3 ) def lowercase ( self: Optional[int] ) -> Any: """simple docstring""" self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Optional[Any] ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: Optional[int] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self: Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256" ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella", "white shark", "white wolf"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( f'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-2 def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512" ) UpperCamelCase_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" f'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-1
328
0
from typing import Any class _UpperCamelCase : def __init__( self: Any , _SCREAMING_SNAKE_CASE: int ) -> Tuple: """simple docstring""" UpperCamelCase_ = data UpperCamelCase_ = None class _UpperCamelCase : def __init__( self: List[Any] ) -> str: """simple docstring""" UpperCamelCase_ = None def lowercase ( self: Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = self.head while temp is not None: print(temp.data , end=" " ) UpperCamelCase_ = temp.next print() def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Any ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = Node(__lowerCAmelCase ) UpperCamelCase_ = self.head UpperCamelCase_ = new_node def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Optional[Any] ) -> List[Any]: """simple docstring""" if node_data_a == node_data_a: return else: UpperCamelCase_ = self.head while node_a is not None and node_a.data != node_data_a: UpperCamelCase_ = node_a.next UpperCamelCase_ = self.head while node_a is not None and node_a.data != node_data_a: UpperCamelCase_ = node_a.next if node_a is None or node_a is None: return UpperCamelCase_ , UpperCamelCase_ = node_a.data, node_a.data if __name__ == "__main__": _UpperCAmelCase = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
371
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _UpperCamelCase : def __init__( self: str ) -> Any: """simple docstring""" UpperCamelCase_ = "" UpperCamelCase_ = "" UpperCamelCase_ = [] UpperCamelCase_ = 0 UpperCamelCase_ = 256 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" UpperCamelCase_ = cva.imread(_SCREAMING_SNAKE_CASE , 0 ) UpperCamelCase_ = copy.deepcopy(self.img ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = plt.hist(self.img.ravel() , 256 , [0, 256] , label="x" ) UpperCamelCase_ = np.sum(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): UpperCamelCase_ = x[i] / self.k self.sk += prk UpperCamelCase_ = (self.L - 1) * self.sk if self.rem != 0: UpperCamelCase_ = int(last % last ) UpperCamelCase_ = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = int(np.ma.count(self.img ) / self.img[1].size ) UpperCamelCase_ = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): UpperCamelCase_ = self.img[j][i] if num != self.last_list[num]: UpperCamelCase_ = self.last_list[num] cva.imwrite("output_data/output.jpg" , self.img ) def lowercase ( self: Any ) -> Optional[Any]: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def lowercase ( self: Tuple ) -> Union[str, Any]: """simple docstring""" cva.imshow("Output-Image" , self.img ) cva.imshow("Input-Image" , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": _UpperCAmelCase = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') _UpperCAmelCase = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
328
0
def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Optional[int]: return x if y == 0 else greatest_common_divisor(__a , x % y ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: return (x * y) // greatest_common_divisor(__a , __a ) def lowerCAmelCase_ ( UpperCamelCase_ = 20 ) -> Optional[Any]: UpperCamelCase_ = 1 for i in range(1 , n + 1 ): UpperCamelCase_ = lcm(__a , __a ) return g if __name__ == "__main__": print(f'''{solution() = }''')
350
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _UpperCAmelCase = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' _UpperCAmelCase = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' _UpperCAmelCase = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: return float((preds == labels).mean() ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_="binary" ) -> Tuple: UpperCamelCase_ = simple_accuracy(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average=UpperCamelCase_ ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: UpperCamelCase_ = {} for id_pred, label in zip(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = F'''{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}''' UpperCamelCase_ = id_pred["prediction"] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase_ = [(pred, label)] UpperCamelCase_ , UpperCamelCase_ = [], [] for question, preds_labels in question_map.items(): UpperCamelCase_ , UpperCamelCase_ = zip(*UpperCamelCase_ ) UpperCamelCase_ = fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average="macro" ) fas.append(UpperCamelCase_ ) UpperCamelCase_ = int(sum(pred == label for pred, label in preds_labels ) == len(UpperCamelCase_ ) ) ems.append(UpperCamelCase_ ) UpperCamelCase_ = float(sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) ) UpperCamelCase_ = sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=[id_pred["prediction"] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCamelCase ( datasets.Metric ): def lowercase ( self: Optional[int] ) -> Optional[int]: """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="numpy" if not self.config_name == "record" and not self.config_name == "multirc" else None , ) def lowercase ( self: List[Any] ) -> int: """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "prediction_text": datasets.Value("string" ), }, "references": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "answers": datasets.Sequence(datasets.Value("string" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("int64" ), "paragraph": datasets.Value("int64" ), "question": datasets.Value("int64" ), }, "prediction": datasets.Value("int64" ), }, "references": datasets.Value("int64" ), } else: return { "predictions": datasets.Value("int64" ), "references": datasets.Value("int64" ), } def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> Dict: """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="macro" ) elif self.config_name == "record": UpperCamelCase_ = [ { "qas": [ {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]} for ref in references ] } ] UpperCamelCase_ = {pred["idx"]["query"]: pred["prediction_text"] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" )
328
0
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[int]: UpperCamelCase_ = np.array([[1, item, train_mtch[i]] for i, item in enumerate(A__ )] ) UpperCamelCase_ = np.array(A__ ) UpperCamelCase_ = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , A__ ) ) , x.transpose() ) , A__ ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: UpperCamelCase_ = (1, 2, 1) UpperCamelCase_ = (1, 1, 0, 7) UpperCamelCase_ = SARIMAX( A__ , exog=A__ , order=A__ , seasonal_order=A__ ) UpperCamelCase_ = model.fit(disp=A__ , maxiter=600 , method="nm" ) UpperCamelCase_ = model_fit.predict(1 , len(A__ ) , exog=[test_match] ) return result[0] def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: UpperCamelCase_ = SVR(kernel="rbf" , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(A__ , A__ ) UpperCamelCase_ = regressor.predict(A__ ) return y_pred[0] def lowerCAmelCase_ ( UpperCamelCase_ ) -> Optional[int]: train_user.sort() UpperCamelCase_ = np.percentile(A__ , 25 ) UpperCamelCase_ = np.percentile(A__ , 75 ) UpperCamelCase_ = qa - qa UpperCamelCase_ = qa - (iqr * 0.1) return low_lim def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: UpperCamelCase_ = 0 UpperCamelCase_ = 0 for i in list_vote: if i > actual_result: UpperCamelCase_ = not_safe + 1 else: if abs(abs(A__ ) - abs(A__ ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) _UpperCAmelCase = [[1_8_2_3_1, 0.0, 1], [2_2_6_2_1, 1.0, 2], [1_5_6_7_5, 0.0, 3], [2_3_5_8_3, 1.0, 4]] _UpperCAmelCase = pd.DataFrame( data_input, columns=['total_user', 'total_even', 'days'] ) _UpperCAmelCase = Normalizer().fit_transform(data_input_df.values) # split data _UpperCAmelCase = normalize_df[:, 2].tolist() _UpperCAmelCase = normalize_df[:, 0].tolist() _UpperCAmelCase = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) _UpperCAmelCase = normalize_df[:, [1, 2]].tolist() _UpperCAmelCase = x[: len(x) - 1] _UpperCAmelCase = x[len(x) - 1 :] # for linear regression & sarimax _UpperCAmelCase = total_date[: len(total_date) - 1] _UpperCAmelCase = total_user[: len(total_user) - 1] _UpperCAmelCase = total_match[: len(total_match) - 1] _UpperCAmelCase = total_date[len(total_date) - 1 :] _UpperCAmelCase = total_user[len(total_user) - 1 :] _UpperCAmelCase = total_match[len(total_match) - 1 :] # voting system with forecasting _UpperCAmelCase = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data _UpperCAmelCase = "" if data_safety_checker(res_vote, tst_user) else "not " print('Today\'s data is {not_str}safe.')
351
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = '''mgp-str''' def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[int]=[32, 128] , _SCREAMING_SNAKE_CASE: Tuple=4 , _SCREAMING_SNAKE_CASE: Optional[Any]=3 , _SCREAMING_SNAKE_CASE: Optional[int]=27 , _SCREAMING_SNAKE_CASE: Tuple=38 , _SCREAMING_SNAKE_CASE: Tuple=50257 , _SCREAMING_SNAKE_CASE: List[Any]=30522 , _SCREAMING_SNAKE_CASE: Optional[Any]=768 , _SCREAMING_SNAKE_CASE: Dict=12 , _SCREAMING_SNAKE_CASE: List[str]=12 , _SCREAMING_SNAKE_CASE: Dict=4.0 , _SCREAMING_SNAKE_CASE: int=True , _SCREAMING_SNAKE_CASE: Tuple=False , _SCREAMING_SNAKE_CASE: Tuple=1e-5 , _SCREAMING_SNAKE_CASE: Optional[Any]=0.0 , _SCREAMING_SNAKE_CASE: Tuple=0.0 , _SCREAMING_SNAKE_CASE: List[Any]=0.0 , _SCREAMING_SNAKE_CASE: List[str]=False , _SCREAMING_SNAKE_CASE: int=0.02 , **_SCREAMING_SNAKE_CASE: Any , ) -> str: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = image_size UpperCamelCase_ = patch_size UpperCamelCase_ = num_channels UpperCamelCase_ = max_token_length UpperCamelCase_ = num_character_labels UpperCamelCase_ = num_bpe_labels UpperCamelCase_ = num_wordpiece_labels UpperCamelCase_ = hidden_size UpperCamelCase_ = num_hidden_layers UpperCamelCase_ = num_attention_heads UpperCamelCase_ = mlp_ratio UpperCamelCase_ = distilled UpperCamelCase_ = layer_norm_eps UpperCamelCase_ = drop_rate UpperCamelCase_ = qkv_bias UpperCamelCase_ = attn_drop_rate UpperCamelCase_ = drop_path_rate UpperCamelCase_ = output_aa_attentions UpperCamelCase_ = initializer_range
328
0
"""simple docstring""" import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { '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', } _UpperCAmelCase = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: for attribute in key.split("." ): UpperCamelCase_ = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) if weight_type is not None: UpperCamelCase_ = getattr(lowerCAmelCase__ , lowerCAmelCase__ ).shape else: UpperCamelCase_ = 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": UpperCamelCase_ = value elif weight_type == "weight_g": UpperCamelCase_ = value elif weight_type == "weight_v": UpperCamelCase_ = value elif weight_type == "bias": UpperCamelCase_ = value else: UpperCamelCase_ = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: UpperCamelCase_ = [] UpperCamelCase_ = fairseq_model.state_dict() UpperCamelCase_ = hf_model.feature_extractor UpperCamelCase_ = hf_model.adapter for name, value in fairseq_dict.items(): UpperCamelCase_ = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , hf_model.config.feat_extract_norm == "group" , ) UpperCamelCase_ = True elif any(x in name for x in ["adaptor", "w2v_encoder.proj.", "w2v_proj_ln."] ): load_adapter(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) UpperCamelCase_ = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: UpperCamelCase_ = True if "*" in mapped_key: UpperCamelCase_ = name.split(lowerCAmelCase__ )[0].split("." )[-2] UpperCamelCase_ = mapped_key.replace("*" , lowerCAmelCase__ ) if "weight_g" in name: UpperCamelCase_ = '''weight_g''' elif "weight_v" in name: UpperCamelCase_ = '''weight_v''' elif "bias" in name: UpperCamelCase_ = '''bias''' elif "weight" in name: UpperCamelCase_ = '''weight''' else: UpperCamelCase_ = None set_recursively(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) continue if not is_used: unused_weights.append(lowerCAmelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: UpperCamelCase_ = full_name.split("conv_layers." )[-1] UpperCamelCase_ = name.split("." ) UpperCamelCase_ = int(items[0] ) UpperCamelCase_ = int(items[1] ) if type_id == 0: if "bias" in name: 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.''' ) UpperCamelCase_ = 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.''' ) UpperCamelCase_ = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: 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." ) UpperCamelCase_ = 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.''' ) UpperCamelCase_ = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowerCAmelCase__ ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: UpperCamelCase_ = full_name.split("adaptor." )[-1] UpperCamelCase_ = name.split("." ) if items[1].isdigit(): UpperCamelCase_ = int(items[1] ) else: UpperCamelCase_ = None if "adaptor" not in full_name: if "proj_ln" in full_name: # has to be layer norm if "bias" in name: assert ( value.shape == adapter.proj_layer_norm.bias.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.''' UpperCamelCase_ = value logger.info(F'''Adapter proj layer norm bias was initialized from {full_name}.''' ) if "weight" in name: assert ( value.shape == adapter.proj_layer_norm.weight.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.''' UpperCamelCase_ = value else: # has to be projection layer if "bias" in name: assert ( value.shape == adapter.proj.bias.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.''' UpperCamelCase_ = value logger.info(F'''Adapter proj layer bias was initialized from {full_name}.''' ) if "weight" in name: assert ( value.shape == adapter.proj.weight.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.''' UpperCamelCase_ = value logger.info(F'''Adapter proj layer weight was initialized from {full_name}.''' ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): if "bias" in name: assert ( value.shape == adapter.layers[layer_id].conv.bias.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.''' UpperCamelCase_ = value logger.info(F'''Adapter layer {layer_id} bias was initialized from {full_name}.''' ) elif "weight" in name: assert ( value.shape == adapter.layers[layer_id].conv.weight.data.shape ), F'''{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.''' UpperCamelCase_ = value logger.info(F'''Adapter layer {layer_id} bias was initialized from {full_name}.''' ) else: unused_weights.append(lowerCAmelCase__ ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> str: UpperCamelCase_ = emb.weight.shape UpperCamelCase_ = nn.Linear(lowerCAmelCase__ , lowerCAmelCase__ , bias=lowerCAmelCase__ ) UpperCamelCase_ = emb.weight.data return lin_layer @torch.no_grad() def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ) -> Dict: UpperCamelCase_ = WavaVecaConfig.from_pretrained( lowerCAmelCase__ , add_adapter=lowerCAmelCase__ , adapter_stride=lowerCAmelCase__ , adapter_kernel_size=lowerCAmelCase__ , use_auth_token=lowerCAmelCase__ , output_hidden_size=lowerCAmelCase__ , ) UpperCamelCase_ = MBartConfig.from_pretrained(lowerCAmelCase__ ) # load model UpperCamelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={ "config_yaml": config_yaml_path, "data": "/".join(dict_path.split("/" )[:-1] ), "w2v_path": checkpoint_path, "load_pretrained_decoder_from": None, } , ) UpperCamelCase_ = model[0].eval() # load feature extractor UpperCamelCase_ = WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase__ , use_auth_token=lowerCAmelCase__ ) # set weights for wav2vec2 encoder UpperCamelCase_ = WavaVecaModel(lowerCAmelCase__ ) recursively_load_weights_wavaveca(model.encoder , lowerCAmelCase__ ) # load decoder weights UpperCamelCase_ = MBartForCausalLM(lowerCAmelCase__ ) UpperCamelCase_ = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=lowerCAmelCase__ ) 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}''' ) UpperCamelCase_ = SpeechEncoderDecoderModel(encoder=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) UpperCamelCase_ = False UpperCamelCase_ = MBartaaTokenizer(lowerCAmelCase__ ) tokenizer.save_pretrained(lowerCAmelCase__ ) UpperCamelCase_ = hf_wavavec.config.to_dict() UpperCamelCase_ = tokenizer.pad_token_id UpperCamelCase_ = tokenizer.bos_token_id UpperCamelCase_ = tokenizer.eos_token_id UpperCamelCase_ = '''mbart50''' UpperCamelCase_ = '''wav2vec2''' UpperCamelCase_ = tokenizer.eos_token_id UpperCamelCase_ = 250004 UpperCamelCase_ = tokenizer.eos_token_id UpperCamelCase_ = SpeechEncoderDecoderConfig.from_dict(lowerCAmelCase__ ) hf_wavavec.save_pretrained(lowerCAmelCase__ ) feature_extractor.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_yaml_path', default=None, type=str, help='Path to yaml file of fine-tuned model') parser.add_argument( '--encoder_config_path', default='facebook/wav2vec2-xls-r-1b', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/mbart-large-50-one-to-many-mmt', type=str, help='Path to hf decoder checkpoint config', ) parser.add_argument('--add_adapter', default=True, type=bool, help='whethere to add model adapter layers') parser.add_argument('--adapter_stride', default=2, type=int, help='stride of adapter layers') parser.add_argument('--adapter_kernel_size', default=3, type=int, help='kernel size of adapter layers') parser.add_argument('--encoder_output_dim', default=1_0_2_4, type=int, help='encoder output dim') parser.add_argument('--start_token_id', default=2_5_0_0_0_4, type=int, help='`decoder_start_token_id` of model config') _UpperCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, args.config_yaml_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, add_adapter=args.add_adapter, adapter_kernel_size=args.adapter_kernel_size, adapter_stride=args.adapter_stride, decoder_start_token_id=args.start_token_id, encoder_output_dim=args.encoder_output_dim, )
352
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _UpperCAmelCase = logging.getLogger(__name__) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether tp freeze the encoder.'''} ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether to freeze the embeddings.'''} ) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''} ) _UpperCamelCase : Optional[str] = field( default='''summarization''' , metadata={'''help''': '''Task name, summarization (or summarization_{dataset} for pegasus) or translation'''} , ) _UpperCamelCase : Optional[int] = 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 : Optional[int] = field( default=1_2_8 , metadata={ '''help''': ( '''The maximum total sequence length for target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for validation target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded. ''' '''This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ''' '''during ``evaluate`` and ``predict``.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for test target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# training examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# validation examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# test examples. -1 means use all.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Source language id for translation.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Target language id for translation.'''} ) _UpperCamelCase : Optional[int] = field(default=lowerCAmelCase_ , metadata={'''help''': '''# num_beams to use for evaluation.'''} ) _UpperCamelCase : bool = field( default=lowerCAmelCase_ , metadata={'''help''': '''If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'''} , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[int]: logger.info(F'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(F''' {key} = {metrics[key]}''' ) save_json(UpperCamelCase_ , os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) ) def lowerCAmelCase_ ( ) -> Optional[int]: # 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. UpperCamelCase_ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_args_into_dataclasses() check_output_dir(UpperCamelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , UpperCamelCase_ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): assert hasattr(UpperCamelCase_ , UpperCamelCase_ ), F'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(UpperCamelCase_ , UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) UpperCamelCase_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=UpperCamelCase_ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(UpperCamelCase_ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: UpperCamelCase_ = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(UpperCamelCase_ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = tokenizer.lang_code_to_id[data_args.tgt_lang] else: UpperCamelCase_ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(UpperCamelCase_ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) UpperCamelCase_ = SeqaSeqDataset # Get datasets UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_train else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_predict else None ) # Initialize our Trainer UpperCamelCase_ = ( build_compute_metrics_fn(data_args.task , UpperCamelCase_ ) if training_args.predict_with_generate else None ) UpperCamelCase_ = SeqaSeqTrainer( model=UpperCamelCase_ , args=UpperCamelCase_ , data_args=UpperCamelCase_ , train_dataset=UpperCamelCase_ , eval_dataset=UpperCamelCase_ , data_collator=SeqaSeqDataCollator( UpperCamelCase_ , UpperCamelCase_ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=UpperCamelCase_ , tokenizer=UpperCamelCase_ , ) UpperCamelCase_ = {} # Training if training_args.do_train: logger.info("*** Train ***" ) UpperCamelCase_ = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) UpperCamelCase_ = train_result.metrics UpperCamelCase_ = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("train" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) UpperCamelCase_ = trainer.evaluate(metric_key_prefix="val" ) UpperCamelCase_ = data_args.n_val UpperCamelCase_ = round(metrics["val_loss"] , 4 ) if trainer.is_world_process_zero(): handle_metrics("val" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.do_predict: logger.info("*** Predict ***" ) UpperCamelCase_ = trainer.predict(test_dataset=UpperCamelCase_ , metric_key_prefix="test" ) UpperCamelCase_ = test_output.metrics UpperCamelCase_ = data_args.n_test if trainer.is_world_process_zero(): UpperCamelCase_ = round(metrics["test_loss"] , 4 ) handle_metrics("test" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.predict_with_generate: UpperCamelCase_ = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_ ) UpperCamelCase_ = lmap(str.strip , UpperCamelCase_ ) write_txt_file(UpperCamelCase_ , os.path.join(training_args.output_dir , "test_generations.txt" ) ) if trainer.is_world_process_zero(): save_json(UpperCamelCase_ , os.path.join(training_args.output_dir , "all_results.json" ) ) return all_metrics def lowerCAmelCase_ ( UpperCamelCase_ ) -> Optional[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
328
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCAmelCase_ ) class _UpperCamelCase ( lowerCAmelCase_ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization _UpperCamelCase : str = field(default='''text-classification''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) _UpperCamelCase : ClassVar[Features] = Features({'''text''': Value('''string''' )} ) _UpperCamelCase : ClassVar[Features] = Features({'''labels''': ClassLabel} ) _UpperCamelCase : str = "text" _UpperCamelCase : str = "labels" def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[int] ) -> Optional[int]: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , _SCREAMING_SNAKE_CASE ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) UpperCamelCase_ = copy.deepcopy(self ) UpperCamelCase_ = self.label_schema.copy() UpperCamelCase_ = features[self.label_column] UpperCamelCase_ = label_schema return task_template @property def lowercase ( self: str ) -> Dict[str, str]: """simple docstring""" return { self.text_column: "text", self.label_column: "labels", }
353
def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = int(UpperCamelCase_ ) if n_element < 1: UpperCamelCase_ = ValueError("a should be a positive number" ) raise my_error UpperCamelCase_ = [1] UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = (0, 0, 0) UpperCamelCase_ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _UpperCAmelCase = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') _UpperCAmelCase = hamming(int(n)) print('-----------------------------------------------------') print(f'''The list with nth numbers is: {hamming_numbers}''') print('-----------------------------------------------------')
328
0
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def lowerCAmelCase_ ( ) -> Optional[Any]: UpperCamelCase_ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=UpperCamelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=UpperCamelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=UpperCamelCase_ ) return parser.parse_args() def lowerCAmelCase_ ( ) -> Optional[Any]: UpperCamelCase_ = parse_args() # Import training_script as a module. UpperCamelCase_ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) UpperCamelCase_ = script_fpath.stem UpperCamelCase_ = importlib.import_module(UpperCamelCase_ ) # Patch sys.argv UpperCamelCase_ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
354
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : List[Any] = IFImgaImgSuperResolutionPipeline _UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} _UpperCamelCase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) _UpperCamelCase : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowercase ( self: List[str] ) -> Any: """simple docstring""" return self._get_superresolution_dummy_components() def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[int]=0 ) -> List[Any]: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Any ) -> Union[str, Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowercase ( self: int ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowercase ( self: Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowercase ( self: List[Any] ) -> Union[str, Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowercase ( self: Dict ) -> Any: """simple docstring""" self._test_save_load_local() def lowercase ( self: Any ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
328
0
"""simple docstring""" import torch from diffusers import StableDiffusionPipeline _UpperCAmelCase = 'path-to-your-trained-model' _UpperCAmelCase = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to('cuda') _UpperCAmelCase = 'A photo of sks dog in a bucket' _UpperCAmelCase = pipe(prompt, num_inference_steps=5_0, guidance_scale=7.5).images[0] image.save('dog-bucket.png')
355
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent _UpperCAmelCase = {'UserAgent': UserAgent().random} def lowerCAmelCase_ ( UpperCamelCase_ ) -> dict: UpperCamelCase_ = script.contents[0] UpperCamelCase_ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class _UpperCamelCase : def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = f'''https://www.instagram.com/{username}/''' UpperCamelCase_ = self.get_json() def lowercase ( self: Union[str, Any] ) -> dict: """simple docstring""" UpperCamelCase_ = requests.get(self.url , headers=_SCREAMING_SNAKE_CASE ).text UpperCamelCase_ = BeautifulSoup(_SCREAMING_SNAKE_CASE , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self: Tuple ) -> str: """simple docstring""" return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self: List[Any] ) -> str: """simple docstring""" return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["username"] @property def lowercase ( self: int ) -> str: """simple docstring""" return self.user_data["full_name"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["biography"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["business_email"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["external_url"] @property def lowercase ( self: List[Any] ) -> int: """simple docstring""" return self.user_data["edge_followed_by"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_follow"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["profile_pic_url_hd"] @property def lowercase ( self: Optional[int] ) -> bool: """simple docstring""" return self.user_data["is_verified"] @property def lowercase ( self: List[str] ) -> bool: """simple docstring""" return self.user_data["is_private"] def lowerCAmelCase_ ( UpperCamelCase_ = "github" ) -> None: import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase_ = InstagramUser(UpperCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , UpperCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = InstagramUser('github') print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
328
0
import flax.linen as nn import jax import jax.numpy as jnp class _UpperCamelCase ( nn.Module ): _UpperCamelCase : Optional[int] = 4_2 _UpperCamelCase : Union[str, Any] = jnp.floataa def lowercase ( self: Union[str, Any] ) -> List[str]: """simple docstring""" UpperCamelCase_ = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self: str , _SCREAMING_SNAKE_CASE: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = hidden_states.shape UpperCamelCase_ = jax.image.resize( __lowerCamelCase , shape=(batch, height * 2, width * 2, channels) , method="nearest" , ) UpperCamelCase_ = self.conv(__lowerCamelCase ) return hidden_states class _UpperCamelCase ( nn.Module ): _UpperCamelCase : Optional[int] = 4_2 _UpperCamelCase : Any = jnp.floataa def lowercase ( self: Any ) -> int: """simple docstring""" UpperCamelCase_ = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self: Dict , _SCREAMING_SNAKE_CASE: str ) -> Any: """simple docstring""" UpperCamelCase_ = self.conv(__lowerCamelCase ) return hidden_states class _UpperCamelCase ( nn.Module ): _UpperCamelCase : List[Any] = 4_2 _UpperCamelCase : List[str] = None _UpperCamelCase : Tuple = 0.0 _UpperCamelCase : Optional[Any] = None _UpperCamelCase : Optional[Any] = jnp.floataa def lowercase ( self: Union[str, Any] ) -> int: """simple docstring""" UpperCamelCase_ = self.in_channels if self.out_channels is None else self.out_channels UpperCamelCase_ = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCamelCase_ = nn.Conv( __lowerCamelCase , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCamelCase_ = nn.Dense(__lowerCamelCase , dtype=self.dtype ) UpperCamelCase_ = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) UpperCamelCase_ = nn.Dropout(self.dropout_prob ) UpperCamelCase_ = nn.Conv( __lowerCamelCase , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCamelCase_ = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut UpperCamelCase_ = None if use_nin_shortcut: UpperCamelCase_ = nn.Conv( __lowerCamelCase , kernel_size=(1, 1) , strides=(1, 1) , padding="VALID" , dtype=self.dtype , ) def __call__( self: List[str] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int=True ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = hidden_states UpperCamelCase_ = self.norma(__lowerCamelCase ) UpperCamelCase_ = nn.swish(__lowerCamelCase ) UpperCamelCase_ = self.conva(__lowerCamelCase ) UpperCamelCase_ = self.time_emb_proj(nn.swish(__lowerCamelCase ) ) UpperCamelCase_ = jnp.expand_dims(jnp.expand_dims(__lowerCamelCase , 1 ) , 1 ) UpperCamelCase_ = hidden_states + temb UpperCamelCase_ = self.norma(__lowerCamelCase ) UpperCamelCase_ = nn.swish(__lowerCamelCase ) UpperCamelCase_ = self.dropout(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase_ = self.conva(__lowerCamelCase ) if self.conv_shortcut is not None: UpperCamelCase_ = self.conv_shortcut(__lowerCamelCase ) return hidden_states + residual
356
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _UpperCAmelCase = False _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = 'ybelkada/fonts' def lowerCAmelCase_ ( ) -> Dict: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: requires_backends(UpperCamelCase_ , ["torch"] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase_ , UpperCamelCase_ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = 36 , UpperCamelCase_ = "black" , UpperCamelCase_ = "white" , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> Image.Image: requires_backends(UpperCamelCase_ , "vision" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase_ ) UpperCamelCase_ = "\n".join(UpperCamelCase_ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase_ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase_ , "Arial.TTF" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase_ , encoding="UTF-8" , size=UpperCamelCase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , UpperCamelCase_ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase_ , UpperCamelCase_ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("RGB" , (image_width, image_height) , UpperCamelCase_ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase_ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase_ , fill=UpperCamelCase_ , font=UpperCamelCase_ ) return image def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> Union[str, Any]: requires_backends(UpperCamelCase_ , "vision" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase_ ) UpperCamelCase_ = render_text(UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase_ ) if infer_channel_dimension_format(UpperCamelCase_ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase_ , ChannelDimension.LAST ) return new_image class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''flattened_patches'''] def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: Optional[Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: dict , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = patch_size["height"], patch_size["width"] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_SCREAMING_SNAKE_CASE ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_SCREAMING_SNAKE_CASE , antialias=_SCREAMING_SNAKE_CASE , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([rows, 1] ).repeat(1 , _SCREAMING_SNAKE_CASE ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([1, columns] ).repeat(_SCREAMING_SNAKE_CASE , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_SCREAMING_SNAKE_CASE , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) return result def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: List[str] ) -> np.ndarray: """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = np.std(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: Optional[Dict[str, int]] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> ImageInput: """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("data_format" , _SCREAMING_SNAKE_CASE ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) UpperCamelCase_ = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) UpperCamelCase_ = kwargs.pop("font_bytes" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("font_path" , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [header_text] * len(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [ render_header(_SCREAMING_SNAKE_CASE , header_text[i] , font_bytes=_SCREAMING_SNAKE_CASE , font_path=_SCREAMING_SNAKE_CASE ) for i, image in enumerate(_SCREAMING_SNAKE_CASE ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_SCREAMING_SNAKE_CASE , max_patches=_SCREAMING_SNAKE_CASE , patch_size=_SCREAMING_SNAKE_CASE ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_outputs
328
0
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: Optional[int] , _SCREAMING_SNAKE_CASE: pyspark.sql.DataFrame , _SCREAMING_SNAKE_CASE: Optional[NamedSplit] = None , _SCREAMING_SNAKE_CASE: Optional[Features] = None , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: str = None , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: str = None , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: str = "arrow" , **_SCREAMING_SNAKE_CASE: Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__( split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , **_A , ) UpperCamelCase_ = load_from_cache_file UpperCamelCase_ = file_format UpperCamelCase_ = Spark( df=_A , features=_A , cache_dir=_A , working_dir=_A , **_A , ) def lowercase ( self: Optional[Any] ) -> Union[str, Any]: """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) UpperCamelCase_ = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=_A , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
357
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: Any , _SCREAMING_SNAKE_CASE: int = 768 , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(1 , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(torch.ones(1 , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[Union[str, torch.device]] = None , _SCREAMING_SNAKE_CASE: Optional[torch.dtype] = None , ) -> List[Any]: """simple docstring""" UpperCamelCase_ = nn.Parameter(self.mean.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(self.std.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) return self def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = (embeds - self.mean) * 1.0 / self.std return embeds def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Dict: """simple docstring""" UpperCamelCase_ = (embeds * self.std) + self.mean return embeds
328
0
"""simple docstring""" import os def lowerCAmelCase_ ( ) -> Any: UpperCamelCase_ = os.path.dirname(os.path.realpath(_A ) ) UpperCamelCase_ = os.path.join(_A , "triangle.txt" ) with open(_A ) as f: UpperCamelCase_ = f.readlines() UpperCamelCase_ = [] for line in triangle: UpperCamelCase_ = [] for number in line.strip().split(" " ): numbers_from_line.append(int(_A ) ) a.append(_A ) for i in range(1 , len(_A ) ): for j in range(len(a[i] ) ): UpperCamelCase_ = a[i - 1][j] if j != len(a[i - 1] ) else 0 UpperCamelCase_ = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(_A , _A ) return max(a[-1] ) if __name__ == "__main__": print(solution())
358
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _UpperCAmelCase = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) _UpperCAmelCase = logging.getLogger() def lowerCAmelCase_ ( ) -> Optional[int]: UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCamelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_="eval" ) -> Any: UpperCamelCase_ = os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) if os.path.exists(UpperCamelCase_ ): with open(UpperCamelCase_ , "r" ) as f: return json.load(UpperCamelCase_ ) raise ValueError(F'''can\'t find {path}''' ) _UpperCAmelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _UpperCamelCase ( lowerCAmelCase_ ): def lowercase ( self: Optional[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_glue.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) @slow def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_clm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 100 ) @slow def lowercase ( self: Any ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_summarization_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE , split="test" ) self.assertGreaterEqual(result["test_rouge1"] , 10 ) self.assertGreaterEqual(result["test_rouge2"] , 2 ) self.assertGreaterEqual(result["test_rougeL"] , 7 ) self.assertGreaterEqual(result["test_rougeLsum"] , 7 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 42 ) @slow def lowercase ( self: Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_ta_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.42 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_ner.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertGreaterEqual(result["eval_f1"] , 0.3 ) @slow def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_qa.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_f1"] , 30 ) self.assertGreaterEqual(result["eval_exact"] , 30 )
328
0
import math from datetime import datetime, timedelta def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = year % 19 UpperCamelCase_ = year % 4 UpperCamelCase_ = year % 7 UpperCamelCase_ = math.floor(year / 100 ) UpperCamelCase_ = math.floor((13 + 8 * leap_day_inhibits) / 25 ) UpperCamelCase_ = leap_day_inhibits / 4 UpperCamelCase_ = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 UpperCamelCase_ = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 UpperCamelCase_ = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon UpperCamelCase_ = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(lowerCAmelCase__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(lowerCAmelCase__ , 4 , 18 ) else: return datetime(lowerCAmelCase__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): _UpperCAmelCase = "will be" if year > datetime.now().year else "was" print(f'''Easter in {year} {tense} {gauss_easter(year)}''')
359
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: for param in module.parameters(): UpperCamelCase_ = False def lowerCAmelCase_ ( ) -> Dict: UpperCamelCase_ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): UpperCamelCase_ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def lowerCAmelCase_ ( ) -> List[str]: UpperCamelCase_ = datetime.now() UpperCamelCase_ = current_time.strftime("%H:%M:%S" ) return timestamp
328
0
import functools from typing import Any def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> bool: # Validation if not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or len(UpperCamelCase_ ) == 0: raise ValueError("the string should be not empty string" ) if not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or not all( isinstance(UpperCamelCase_ , UpperCamelCase_ ) and len(UpperCamelCase_ ) > 0 for item in words ): raise ValueError("the words should be a list of non-empty strings" ) # Build trie UpperCamelCase_ = {} UpperCamelCase_ = "WORD_KEEPER" for word in words: UpperCamelCase_ = trie for c in word: if c not in trie_node: UpperCamelCase_ = {} UpperCamelCase_ = trie_node[c] UpperCamelCase_ = True UpperCamelCase_ = len(UpperCamelCase_ ) # Dynamic programming method @functools.cache def is_breakable(UpperCamelCase_ ) -> bool: if index == len_string: return True UpperCamelCase_ = trie for i in range(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = trie_node.get(string[i] , UpperCamelCase_ ) if trie_node is None: return False if trie_node.get(UpperCamelCase_ , UpperCamelCase_ ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
360
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 _UpperCAmelCase = '▁' _UpperCAmelCase = {'vocab_file': 'spiece.model'} _UpperCAmelCase = { 'vocab_file': {'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'} } _UpperCAmelCase = { 'google/pegasus-xsum': 5_1_2, } _UpperCAmelCase = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = VOCAB_FILES_NAMES _UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[int] = ['''input_ids''', '''attention_mask'''] def __init__( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: str="<pad>" , _SCREAMING_SNAKE_CASE: Optional[Any]="</s>" , _SCREAMING_SNAKE_CASE: Any="<unk>" , _SCREAMING_SNAKE_CASE: int="<mask_2>" , _SCREAMING_SNAKE_CASE: List[Any]="<mask_1>" , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: Optional[int]=103 , _SCREAMING_SNAKE_CASE: Optional[Dict[str, Any]] = None , **_SCREAMING_SNAKE_CASE: Dict , ) -> None: """simple docstring""" UpperCamelCase_ = offset if additional_special_tokens is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError( f'''additional_special_tokens should be of type {type(_SCREAMING_SNAKE_CASE )}, but is''' f''' {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'''<unk_{i}>''' for i in range(len(_SCREAMING_SNAKE_CASE ) , self.offset - 1 ) ] if len(set(_SCREAMING_SNAKE_CASE ) ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError( "Please make sure that the provided additional_special_tokens do not contain an incorrectly" f''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) UpperCamelCase_ = additional_special_tokens_extended else: UpperCamelCase_ = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'''<unk_{i}>''' for i in range(2 , self.offset )] UpperCamelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token_sent=_SCREAMING_SNAKE_CASE , offset=_SCREAMING_SNAKE_CASE , additional_special_tokens=_SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = mask_token_sent UpperCamelCase_ = vocab_file UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_SCREAMING_SNAKE_CASE ) # add special tokens to encoder dict UpperCamelCase_ = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) UpperCamelCase_ = {v: k for k, v in self.encoder.items()} @property def lowercase ( self: Dict ) -> int: """simple docstring""" return len(self.sp_model ) + self.offset def lowercase ( self: int ) -> Dict[str, int]: """simple docstring""" UpperCamelCase_ = {self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self: Optional[int] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = self.__dict__.copy() UpperCamelCase_ = None return state def __setstate__( self: List[Any] , _SCREAMING_SNAKE_CASE: List[Any] ) -> Any: """simple docstring""" UpperCamelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCamelCase_ = {} UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_SCREAMING_SNAKE_CASE , out_type=_SCREAMING_SNAKE_CASE ) def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: str ) -> int: """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] UpperCamelCase_ = self.sp_model.piece_to_id(_SCREAMING_SNAKE_CASE ) return sp_id + self.offset def lowercase ( self: str , _SCREAMING_SNAKE_CASE: int ) -> str: """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: UpperCamelCase_ = self.sp_model.IdToPiece(index - self.offset ) return token def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = [] UpperCamelCase_ = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) + token UpperCamelCase_ = [] else: current_sub_tokens.append(_SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) return out_string.strip() def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Optional[int]=False ) -> Union[str, Any]: """simple docstring""" return 1 def lowercase ( self: int , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: List , _SCREAMING_SNAKE_CASE: Optional[List] = None , _SCREAMING_SNAKE_CASE: bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) elif token_ids_a is None: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any]=None ) -> List[int]: """simple docstring""" if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCamelCase_ = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(_SCREAMING_SNAKE_CASE , "wb" ) as fi: UpperCamelCase_ = self.sp_model.serialized_model_proto() fi.write(_SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
328
0
import string def lowerCAmelCase_ ( UpperCamelCase_ ) -> None: for key in range(len(string.ascii_uppercase ) ): UpperCamelCase_ = '''''' for symbol in message: if symbol in string.ascii_uppercase: UpperCamelCase_ = string.ascii_uppercase.find(UpperCamelCase_ ) UpperCamelCase_ = num - key if num < 0: UpperCamelCase_ = num + len(string.ascii_uppercase ) UpperCamelCase_ = translated + string.ascii_uppercase[num] else: UpperCamelCase_ = translated + symbol print(F'''Decryption using Key #{key}: {translated}''' ) def lowerCAmelCase_ ( ) -> None: UpperCamelCase_ = input("Encrypted message: " ) UpperCamelCase_ = message.upper() decrypt(UpperCamelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
361
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { 'configuration_tapas': ['TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TapasConfig'], 'tokenization_tapas': ['TapasTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TapasForMaskedLM', 'TapasForQuestionAnswering', 'TapasForSequenceClassification', 'TapasModel', 'TapasPreTrainedModel', 'load_tf_weights_in_tapas', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFTapasForMaskedLM', 'TFTapasForQuestionAnswering', 'TFTapasForSequenceClassification', 'TFTapasModel', 'TFTapasPreTrainedModel', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
328
0
"""simple docstring""" import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(4_2) _UpperCAmelCase = 'bert-base-cased' _UpperCAmelCase = 'fp16' _UpperCAmelCase = 'bf16' _UpperCAmelCase = [FPaa, BFaa] @require_fsdp @require_cuda class _UpperCamelCase ( lowerCAmelCase_ ): def lowercase ( self: str ) -> Optional[Any]: """simple docstring""" super().setUp() UpperCamelCase_ = dict( ACCELERATE_USE_FSDP="true" , MASTER_ADDR="localhost" , MASTER_PORT="10999" , RANK="0" , LOCAL_RANK="0" , WORLD_SIZE="1" , ) def lowercase ( self: Union[str, Any] ) -> Optional[Any]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__a ): UpperCamelCase_ = self.dist_env.copy() UpperCamelCase_ = f'''{i + 1}''' UpperCamelCase_ = strategy with mockenv_context(**__a ): UpperCamelCase_ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def lowercase ( self: List[Any] ) -> Any: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__a ): UpperCamelCase_ = self.dist_env.copy() UpperCamelCase_ = prefetch_policy with mockenv_context(**__a ): UpperCamelCase_ = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def lowercase ( self: List[Any] ) -> Optional[Any]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__a ): UpperCamelCase_ = self.dist_env.copy() UpperCamelCase_ = state_dict_type with mockenv_context(**__a ): UpperCamelCase_ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def lowercase ( self: Union[str, Any] ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = AutoModel.from_pretrained(__a ) for policy in FSDP_AUTO_WRAP_POLICY: UpperCamelCase_ = self.dist_env.copy() UpperCamelCase_ = policy if policy == "TRANSFORMER_BASED_WRAP": UpperCamelCase_ = "BertLayer" elif policy == "SIZE_BASED_WRAP": UpperCamelCase_ = "2000" with mockenv_context(**__a ): UpperCamelCase_ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__a ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) UpperCamelCase_ = self.dist_env.copy() UpperCamelCase_ = "TRANSFORMER_BASED_WRAP" UpperCamelCase_ = "T5Layer" with mockenv_context(**__a ): UpperCamelCase_ = FullyShardedDataParallelPlugin() with self.assertRaises(__a ) as cm: fsdp_plugin.set_auto_wrap_policy(__a ) self.assertTrue("Could not find the transformer layer class to wrap in the model." in str(cm.exception ) ) UpperCamelCase_ = self.dist_env.copy() UpperCamelCase_ = "SIZE_BASED_WRAP" UpperCamelCase_ = "0" with mockenv_context(**__a ): UpperCamelCase_ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__a ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def lowercase ( self: List[Any] ) -> Any: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: UpperCamelCase_ = self.dist_env.copy() UpperCamelCase_ = mp_dtype with mockenv_context(**__a ): UpperCamelCase_ = Accelerator() if mp_dtype == "fp16": UpperCamelCase_ = torch.floataa elif mp_dtype == "bf16": UpperCamelCase_ = torch.bfloataa UpperCamelCase_ = MixedPrecision(param_dtype=__a , reduce_dtype=__a , buffer_dtype=__a ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , __a ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , __a ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__a ) def lowercase ( self: Tuple ) -> Tuple: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: UpperCamelCase_ = self.dist_env.copy() UpperCamelCase_ = str(__a ).lower() with mockenv_context(**__a ): UpperCamelCase_ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=__a ) ) @require_fsdp @require_multi_gpu @slow class _UpperCamelCase ( lowerCAmelCase_ ): def lowercase ( self: Optional[Any] ) -> Tuple: """simple docstring""" super().setUp() UpperCamelCase_ = 0.82 UpperCamelCase_ = [ "fsdp_shard_grad_op_transformer_based_wrap", "fsdp_full_shard_transformer_based_wrap", ] UpperCamelCase_ = { "multi_gpu_fp16": 3200, "fsdp_shard_grad_op_transformer_based_wrap_fp16": 2000, "fsdp_full_shard_transformer_based_wrap_fp16": 1900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } UpperCamelCase_ = 160 UpperCamelCase_ = 160 UpperCamelCase_ = inspect.getfile(accelerate.test_utils ) UpperCamelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "external_deps"] ) def lowercase ( self: Any ) -> Any: """simple docstring""" UpperCamelCase_ = os.path.join(self.test_scripts_folder , "test_performance.py" ) UpperCamelCase_ = ["accelerate", "launch", "--num_processes=2", "--num_machines=1", "--machine_rank=0", "--use_fsdp"] for config in self.performance_configs: UpperCamelCase_ = cmd.copy() for i, strategy in enumerate(__a ): if strategy.lower() in config: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "fp32" in config: cmd_config.append("--mixed_precision=no" ) else: cmd_config.append("--mixed_precision=fp16" ) if "cpu_offload" in config: cmd_config.append("--fsdp_offload_params=True" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("--fsdp_min_num_params=2000" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--performance_lower_bound={self.performance_lower_bound}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() ) def lowercase ( self: int ) -> Tuple: """simple docstring""" UpperCamelCase_ = os.path.join(self.test_scripts_folder , "test_checkpointing.py" ) UpperCamelCase_ = [ "accelerate", "launch", "--num_processes=2", "--num_machines=1", "--machine_rank=0", "--use_fsdp", "--mixed_precision=fp16", "--fsdp_transformer_layer_cls_to_wrap=BertLayer", ] for i, strategy in enumerate(__a ): UpperCamelCase_ = cmd.copy() cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) if strategy != "FULL_SHARD": continue UpperCamelCase_ = len(__a ) for state_dict_type in FSDP_STATE_DICT_TYPE: UpperCamelCase_ = cmd_config[:state_dict_config_index] cmd_config.append(f'''--fsdp_state_dict_type={state_dict_type}''' ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', "--partial_train_epoch=1", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() ) UpperCamelCase_ = cmd_config[:-1] UpperCamelCase_ = os.path.join(self.tmpdir , "epoch_0" ) cmd_config.extend( [ f'''--resume_from_checkpoint={resume_from_checkpoint}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() ) def lowercase ( self: Union[str, Any] ) -> List[Any]: """simple docstring""" UpperCamelCase_ = os.path.join(self.test_scripts_folder , "test_peak_memory_usage.py" ) UpperCamelCase_ = [ "accelerate", "launch", "--num_processes=2", "--num_machines=1", "--machine_rank=0", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): UpperCamelCase_ = cmd.copy() if "fp16" in spec: cmd_config.extend(["--mixed_precision=fp16"] ) else: cmd_config.extend(["--mixed_precision=no"] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["--use_fsdp"] ) for i, strategy in enumerate(__a ): if strategy.lower() in spec: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "cpu_offload" in spec: cmd_config.append("--fsdp_offload_params=True" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("--fsdp_min_num_params=2000" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--peak_memory_upper_bound={peak_mem_upper_bound}''', f'''--n_train={self.n_train}''', f'''--n_val={self.n_val}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() )
362
import argparse import json from tqdm import tqdm def lowerCAmelCase_ ( ) -> Tuple: UpperCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--src_path" , type=UpperCamelCase_ , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , ) parser.add_argument( "--evaluation_set" , type=UpperCamelCase_ , help="where to store parsed evaluation_set file" , ) parser.add_argument( "--gold_data_path" , type=UpperCamelCase_ , help="where to store parsed gold_data_path file" , ) UpperCamelCase_ = parser.parse_args() with open(args.src_path , "r" ) as src_file, open(args.evaluation_set , "w" ) as eval_file, open( args.gold_data_path , "w" ) as gold_file: UpperCamelCase_ = json.load(UpperCamelCase_ ) for dpr_record in tqdm(UpperCamelCase_ ): UpperCamelCase_ = dpr_record["question"] UpperCamelCase_ = [context["title"] for context in dpr_record["positive_ctxs"]] eval_file.write(question + "\n" ) gold_file.write("\t".join(UpperCamelCase_ ) + "\n" ) if __name__ == "__main__": main()
328
0
import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch _UpperCAmelCase = 'sshleifer/bart-tiny-random' _UpperCAmelCase = 'patrickvonplaten/t5-tiny-random' @require_torch class _UpperCamelCase ( unittest.TestCase ): @cached_property def lowercase ( self: str ) -> List[str]: """simple docstring""" return AutoConfig.from_pretrained(UpperCamelCase__ ) def lowercase ( self: Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ , *UpperCamelCase_ = create_student_by_copying_alternating_layers(UpperCamelCase__ , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.num_hidden_layers , 1 ) def lowercase ( self: List[str] ) -> Dict: """simple docstring""" UpperCamelCase_ , *UpperCamelCase_ = create_student_by_copying_alternating_layers(UpperCamelCase__ , tempfile.mkdtemp() , e=1 , d=UpperCamelCase__ ) def lowercase ( self: Optional[int] ) -> Dict: """simple docstring""" UpperCamelCase_ , *UpperCamelCase_ = create_student_by_copying_alternating_layers(UpperCamelCase__ , tempfile.mkdtemp() , e=1 , d=UpperCamelCase__ ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers ) def lowercase ( self: List[str] ) -> Dict: """simple docstring""" UpperCamelCase_ , *UpperCamelCase_ = create_student_by_copying_alternating_layers(UpperCamelCase__ , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , 1 ) def lowercase ( self: Dict ) -> List[str]: """simple docstring""" with self.assertRaises(UpperCamelCase__ ): create_student_by_copying_alternating_layers(UpperCamelCase__ , tempfile.mkdtemp() , e=UpperCamelCase__ , d=UpperCamelCase__ )
363
import requests from bsa import BeautifulSoup def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = BeautifulSoup(requests.get(UpperCamelCase_ , params=UpperCamelCase_ ).content , "html.parser" ) UpperCamelCase_ = soup.find("div" , attrs={"class": "gs_ri"} ) UpperCamelCase_ = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": _UpperCAmelCase = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
328
0
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: if len(SCREAMING_SNAKE_CASE_ ) <= 1: return [tuple(SCREAMING_SNAKE_CASE_ )] UpperCamelCase_ = [] def generate(UpperCamelCase_ , UpperCamelCase_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , SCREAMING_SNAKE_CASE_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even UpperCamelCase_ , UpperCamelCase_ = arr[k - 1], arr[i] else: # k is odd UpperCamelCase_ , UpperCamelCase_ = arr[k - 1], arr[0] generate(k - 1 , SCREAMING_SNAKE_CASE_ ) generate(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) return res if __name__ == "__main__": _UpperCAmelCase = input('Enter numbers separated by a comma:\n').strip() _UpperCAmelCase = [int(item) for item in user_input.split(',')] print(heaps(arr))
364
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: List[str] , *, _SCREAMING_SNAKE_CASE: int = 4 , _SCREAMING_SNAKE_CASE: int = 768 , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: str , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(_SCREAMING_SNAKE_CASE ) ) # parameters for additional clip time embeddings UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # parameters for encoder hidden states UpperCamelCase_ = clip_extra_context_tokens UpperCamelCase_ = nn.Linear( _SCREAMING_SNAKE_CASE , self.clip_extra_context_tokens * cross_attention_dim ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.LayerNorm(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , *, _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> str: """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings UpperCamelCase_ = image_embeddings.shape[0] UpperCamelCase_ = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) UpperCamelCase_ = classifier_free_guidance_embeddings.expand( _SCREAMING_SNAKE_CASE , -1 ) UpperCamelCase_ = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] UpperCamelCase_ = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... UpperCamelCase_ = self.embedding_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.clip_image_embeddings_project_to_time_embeddings(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" UpperCamelCase_ = self.clip_extra_context_tokens_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = clip_extra_context_tokens.reshape(_SCREAMING_SNAKE_CASE , -1 , self.clip_extra_context_tokens ) UpperCamelCase_ = clip_extra_context_tokens.permute(0 , 2 , 1 ) UpperCamelCase_ = self.encoder_hidden_states_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.text_encoder_hidden_states_norm(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
328
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase = {'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
365
from functools import lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> set: UpperCamelCase_ = 2 UpperCamelCase_ = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(UpperCamelCase_ ) if n > 1: factors.add(UpperCamelCase_ ) return factors @lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: return len(unique_prime_factors(UpperCamelCase_ ) ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> bool: return len(set(UpperCamelCase_ ) ) in (0, 1) def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = 2 while True: # Increment each value of a generated range UpperCamelCase_ = [base + i for i in range(UpperCamelCase_ )] # Run elements through out unique_prime_factors function # Append our target number to the end. UpperCamelCase_ = [upf_len(UpperCamelCase_ ) for x in group] checker.append(UpperCamelCase_ ) # If all numbers in the list are equal, return the group variable. if equality(UpperCamelCase_ ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase_ ( UpperCamelCase_ = 4 ) -> int: UpperCamelCase_ = run(UpperCamelCase_ ) return results[0] if len(UpperCamelCase_ ) else None if __name__ == "__main__": print(solution())
328
0
from timeit import timeit def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: if number < 0: raise ValueError("the value of input must not be negative" ) UpperCamelCase_ = 0 while number: number &= number - 1 result += 1 return result def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: if number < 0: raise ValueError("the value of input must not be negative" ) UpperCamelCase_ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCAmelCase_ ( ) -> None: def do_benchmark(UpperCamelCase_ ) -> None: UpperCamelCase_ = "import __main__ as z" print(F'''Benchmark when {number = }:''' ) print(F'''{get_set_bits_count_using_modulo_operator(lowerCAmelCase__ ) = }''' ) UpperCamelCase_ = timeit("z.get_set_bits_count_using_modulo_operator(25)" , setup=lowerCAmelCase__ ) print(F'''timeit() runs in {timing} seconds''' ) print(F'''{get_set_bits_count_using_brian_kernighans_algorithm(lowerCAmelCase__ ) = }''' ) UpperCamelCase_ = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)" , setup=lowerCAmelCase__ , ) print(F'''timeit() runs in {timing} seconds''' ) for number in (25, 37, 58, 0): do_benchmark(lowerCAmelCase__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
366
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = len(UpperCamelCase_ ) UpperCamelCase_ = len(matrix[0] ) UpperCamelCase_ = min(UpperCamelCase_ , UpperCamelCase_ ) for row in range(UpperCamelCase_ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , UpperCamelCase_ ): UpperCamelCase_ = matrix[col][row] / matrix[row][row] for i in range(UpperCamelCase_ , UpperCamelCase_ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows UpperCamelCase_ = True for i in range(row + 1 , UpperCamelCase_ ): if matrix[i][row] != 0: UpperCamelCase_ , UpperCamelCase_ = matrix[i], matrix[row] UpperCamelCase_ = False break if reduce: rank -= 1 for i in range(UpperCamelCase_ ): UpperCamelCase_ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
328
0
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: if "model" in orig_key: UpperCamelCase_ = orig_key.replace("model." , "" ) if "norm1" in orig_key: UpperCamelCase_ = orig_key.replace("norm1" , "attention.output.LayerNorm" ) if "norm2" in orig_key: UpperCamelCase_ = orig_key.replace("norm2" , "output.LayerNorm" ) if "norm" in orig_key: UpperCamelCase_ = orig_key.replace("norm" , "LayerNorm" ) if "transformer" in orig_key: UpperCamelCase_ = orig_key.split("." )[0].split("_" )[-1] UpperCamelCase_ = orig_key.replace(F'''transformer_{layer_num}''' , F'''encoder.layer.{layer_num}''' ) if "mha.attn" in orig_key: UpperCamelCase_ = orig_key.replace("mha.attn" , "attention.self" ) if "mha" in orig_key: UpperCamelCase_ = orig_key.replace("mha" , "attention" ) if "W_q" in orig_key: UpperCamelCase_ = orig_key.replace("W_q" , "self.query" ) if "W_k" in orig_key: UpperCamelCase_ = orig_key.replace("W_k" , "self.key" ) if "W_v" in orig_key: UpperCamelCase_ = orig_key.replace("W_v" , "self.value" ) if "ff1" in orig_key: UpperCamelCase_ = orig_key.replace("ff1" , "intermediate.dense" ) if "ff2" in orig_key: UpperCamelCase_ = orig_key.replace("ff2" , "output.dense" ) if "ff" in orig_key: UpperCamelCase_ = orig_key.replace("ff" , "output.dense" ) if "mlm_class" in orig_key: UpperCamelCase_ = orig_key.replace("mlm.mlm_class" , "cls.predictions.decoder" ) if "mlm" in orig_key: UpperCamelCase_ = orig_key.replace("mlm" , "cls.predictions.transform" ) if "cls" not in orig_key: UpperCamelCase_ = '''yoso.''' + orig_key return orig_key def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: for key in orig_state_dict.copy().keys(): UpperCamelCase_ = orig_state_dict.pop(UpperCamelCase_ ) if ("pooler" in key) or ("sen_class" in key): continue else: UpperCamelCase_ = val UpperCamelCase_ = orig_state_dict['''cls.predictions.decoder.bias'''] UpperCamelCase_ = torch.arange(UpperCamelCase_ ).expand((1, -1) ) + 2 return orig_state_dict def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: UpperCamelCase_ = torch.load(UpperCamelCase_ , map_location="cpu" )['''model_state_dict'''] UpperCamelCase_ = YosoConfig.from_json_file(UpperCamelCase_ ) UpperCamelCase_ = YosoForMaskedLM(UpperCamelCase_ ) UpperCamelCase_ = convert_checkpoint_helper(config.max_position_embeddings , UpperCamelCase_ ) print(model.load_state_dict(UpperCamelCase_ ) ) model.eval() model.save_pretrained(UpperCamelCase_ ) print(F'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to YOSO pytorch checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for YOSO model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _UpperCAmelCase = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
367
import math def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(UpperCamelCase_ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. _UpperCAmelCase = 'Enter the base and the power separated by a comma: ' _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) # We find the log of each number, using the function res(), which takes two # arguments. _UpperCAmelCase = res(xa, ya) _UpperCAmelCase = res(xa, ya) # We check for the largest number if resa > resa: print('Largest number is', xa, '^', ya) elif resa > resa: print('Largest number is', xa, '^', ya) else: print('Both are equal')
328
0
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class _UpperCamelCase ( unittest.TestCase , UpperCamelCase__ ): def lowercase ( self: Tuple ) -> Any: """simple docstring""" UpperCamelCase_ = load_tool("text-to-speech" ) self.tool.setup() def lowercase ( self: Union[str, Any] ) -> str: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = self.tool("hey" ) UpperCamelCase_ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85] ) , ) ) def lowercase ( self: List[str] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = self.tool("hey" ) UpperCamelCase_ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85] ) , ) )
368
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor _UpperCAmelCase = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> List[Any]: if isinstance(UpperCamelCase_ , torch.Tensor ): return image elif isinstance(UpperCamelCase_ , PIL.Image.Image ): UpperCamelCase_ = [image] UpperCamelCase_ = [trans(img.convert("RGB" ) ) for img in image] UpperCamelCase_ = torch.stack(UpperCamelCase_ ) return image class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase_ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[Any]: """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> int: """simple docstring""" UpperCamelCase_ = min(int(num_inference_steps * strength ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[int]=None ) -> List[Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = image.to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase_ = init_latents.shape UpperCamelCase_ = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) # get latents print("add noise to latents at timestep" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.scheduler.add_noise(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = init_latents return latents @torch.no_grad() def __call__( self: Dict , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, PIL.Image.Image] = None , _SCREAMING_SNAKE_CASE: float = 0.8 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: int = 50 , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" self.check_inputs(_SCREAMING_SNAKE_CASE ) # 2. Preprocess image UpperCamelCase_ = preprocess(_SCREAMING_SNAKE_CASE ) # 3. set timesteps self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=self.device ) UpperCamelCase_ , UpperCamelCase_ = self.get_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.device ) UpperCamelCase_ = timesteps[:1].repeat(_SCREAMING_SNAKE_CASE ) # 4. Prepare latent variables UpperCamelCase_ = self.prepare_latents(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.unet.dtype , self.device , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = latents # 5. Denoising loop for t in self.progress_bar(_SCREAMING_SNAKE_CASE ): # 1. predict noise model_output UpperCamelCase_ = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 UpperCamelCase_ = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , use_clipped_model_output=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample UpperCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
328
0
"""simple docstring""" import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings _UpperCAmelCase = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class _UpperCamelCase ( _UpperCamelCase ): _UpperCamelCase : bool = field(default=_UpperCamelCase , metadata={'''help''': '''Whether to use SortishSampler or not.'''} ) _UpperCamelCase : bool = field( default=_UpperCamelCase , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''} ) _UpperCamelCase : Optional[int] = field( default=_UpperCamelCase , metadata={ '''help''': ( '''The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default ''' '''to the `max_length` value of the model configuration.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=_UpperCamelCase , metadata={ '''help''': ( '''The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default ''' '''to the `num_beams` value of the model configuration.''' ) } , ) _UpperCamelCase : Optional[Union[str, Path, GenerationConfig]] = field( default=_UpperCamelCase , metadata={ '''help''': '''Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.''' } , ) def lowercase ( self: List[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase_ = super().to_dict() for k, v in d.items(): if isinstance(_UpperCAmelCase , _UpperCAmelCase ): UpperCamelCase_ = v.to_dict() return d
369
import re from filelock import FileLock try: import nltk _UpperCAmelCase = True except (ImportError, ModuleNotFoundError): _UpperCAmelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCAmelCase_ ( UpperCamelCase_ ) -> str: re.sub("<n>" , "" , UpperCamelCase_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase_ ) )
328
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( __snake_case ): _UpperCamelCase : int = """ClapFeatureExtractor""" _UpperCamelCase : List[str] = ("""RobertaTokenizer""", """RobertaTokenizerFast""") def __init__( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Tuple ) -> Optional[int]: """simple docstring""" super().__init__(UpperCamelCase__ , UpperCamelCase__ ) def __call__( self: int , _SCREAMING_SNAKE_CASE: Dict=None , _SCREAMING_SNAKE_CASE: Optional[int]=None , _SCREAMING_SNAKE_CASE: Dict=None , **_SCREAMING_SNAKE_CASE: List[str] ) -> Any: """simple docstring""" UpperCamelCase_ = kwargs.pop("sampling_rate" , UpperCamelCase__ ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: UpperCamelCase_ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if audios is not None: UpperCamelCase_ = self.feature_extractor( UpperCamelCase__ , sampling_rate=UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if text is not None and audios is not None: UpperCamelCase_ = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCamelCase__ ) , tensor_type=UpperCamelCase__ ) def lowercase ( self: Union[str, Any] , *_SCREAMING_SNAKE_CASE: Tuple , **_SCREAMING_SNAKE_CASE: Tuple ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*UpperCamelCase__ , **UpperCamelCase__ ) def lowercase ( self: str , *_SCREAMING_SNAKE_CASE: int , **_SCREAMING_SNAKE_CASE: Optional[int] ) -> List[str]: """simple docstring""" return self.tokenizer.decode(*UpperCamelCase__ , **UpperCamelCase__ ) @property def lowercase ( self: Any ) -> Any: """simple docstring""" UpperCamelCase_ = self.tokenizer.model_input_names UpperCamelCase_ = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
370
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = DiTPipeline _UpperCamelCase : Any = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS _UpperCamelCase : Dict = PipelineTesterMixin.required_optional_params - { '''latents''', '''num_images_per_prompt''', '''callback''', '''callback_steps''', } _UpperCamelCase : Optional[int] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS _UpperCamelCase : Dict = False def lowercase ( self: str ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn="gelu-approximate" , num_embeds_ada_norm=1000 , norm_type="ada_norm_zero" , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = AutoencoderKL() UpperCamelCase_ = DDIMScheduler() UpperCamelCase_ = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler} return components def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: List[str]=0 ) -> Dict: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "class_labels": [1], "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def lowercase ( self: Any ) -> List[str]: """simple docstring""" UpperCamelCase_ = "cpu" UpperCamelCase_ = self.get_dummy_components() UpperCamelCase_ = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(**_SCREAMING_SNAKE_CASE ).images UpperCamelCase_ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) UpperCamelCase_ = np.array([0.29_46, 0.66_01, 0.43_29, 0.32_96, 0.41_44, 0.53_19, 0.72_73, 0.50_13, 0.44_57] ) UpperCamelCase_ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1e-3 ) def lowercase ( self: Optional[int] ) -> Any: """simple docstring""" self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Optional[Any] ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: Optional[int] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self: Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256" ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella", "white shark", "white wolf"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( f'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-2 def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512" ) UpperCamelCase_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" f'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-1
328
0
import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { '''nvidia/segformer-b0-finetuned-ade-512-512''': ( '''https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json''' ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class _UpperCamelCase ( lowerCamelCase_ ): _UpperCamelCase : Dict = '''segformer''' def __init__( self: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[int]=3 , _SCREAMING_SNAKE_CASE: Dict=4 , _SCREAMING_SNAKE_CASE: Tuple=[2, 2, 2, 2] , _SCREAMING_SNAKE_CASE: List[str]=[8, 4, 2, 1] , _SCREAMING_SNAKE_CASE: Any=[32, 64, 160, 256] , _SCREAMING_SNAKE_CASE: Tuple=[7, 3, 3, 3] , _SCREAMING_SNAKE_CASE: List[Any]=[4, 2, 2, 2] , _SCREAMING_SNAKE_CASE: Any=[1, 2, 5, 8] , _SCREAMING_SNAKE_CASE: Optional[int]=[4, 4, 4, 4] , _SCREAMING_SNAKE_CASE: List[str]="gelu" , _SCREAMING_SNAKE_CASE: Optional[int]=0.0 , _SCREAMING_SNAKE_CASE: Dict=0.0 , _SCREAMING_SNAKE_CASE: Dict=0.1 , _SCREAMING_SNAKE_CASE: Any=0.02 , _SCREAMING_SNAKE_CASE: str=0.1 , _SCREAMING_SNAKE_CASE: Tuple=1e-6 , _SCREAMING_SNAKE_CASE: Dict=256 , _SCREAMING_SNAKE_CASE: List[str]=255 , **_SCREAMING_SNAKE_CASE: Any , ) -> Dict: """simple docstring""" super().__init__(**__snake_case ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( "Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be" " removed, as the behaviour will default to that of reshape_last_stage = True." , __snake_case , ) UpperCamelCase_ = num_channels UpperCamelCase_ = num_encoder_blocks UpperCamelCase_ = depths UpperCamelCase_ = sr_ratios UpperCamelCase_ = hidden_sizes UpperCamelCase_ = patch_sizes UpperCamelCase_ = strides UpperCamelCase_ = mlp_ratios UpperCamelCase_ = num_attention_heads UpperCamelCase_ = hidden_act UpperCamelCase_ = hidden_dropout_prob UpperCamelCase_ = attention_probs_dropout_prob UpperCamelCase_ = classifier_dropout_prob UpperCamelCase_ = initializer_range UpperCamelCase_ = drop_path_rate UpperCamelCase_ = layer_norm_eps UpperCamelCase_ = decoder_hidden_size UpperCamelCase_ = kwargs.get("reshape_last_stage" , __snake_case ) UpperCamelCase_ = semantic_loss_ignore_index class _UpperCamelCase ( lowerCamelCase_ ): _UpperCamelCase : Dict = version.parse('''1.11''' ) @property def lowercase ( self: Any ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def lowercase ( self: Optional[Any] ) -> float: """simple docstring""" return 1e-4 @property def lowercase ( self: Union[str, Any] ) -> int: """simple docstring""" return 12
371
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _UpperCamelCase : def __init__( self: str ) -> Any: """simple docstring""" UpperCamelCase_ = "" UpperCamelCase_ = "" UpperCamelCase_ = [] UpperCamelCase_ = 0 UpperCamelCase_ = 256 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" UpperCamelCase_ = cva.imread(_SCREAMING_SNAKE_CASE , 0 ) UpperCamelCase_ = copy.deepcopy(self.img ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = plt.hist(self.img.ravel() , 256 , [0, 256] , label="x" ) UpperCamelCase_ = np.sum(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): UpperCamelCase_ = x[i] / self.k self.sk += prk UpperCamelCase_ = (self.L - 1) * self.sk if self.rem != 0: UpperCamelCase_ = int(last % last ) UpperCamelCase_ = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = int(np.ma.count(self.img ) / self.img[1].size ) UpperCamelCase_ = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): UpperCamelCase_ = self.img[j][i] if num != self.last_list[num]: UpperCamelCase_ = self.last_list[num] cva.imwrite("output_data/output.jpg" , self.img ) def lowercase ( self: Any ) -> Optional[Any]: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def lowercase ( self: Tuple ) -> Union[str, Any]: """simple docstring""" cva.imshow("Output-Image" , self.img ) cva.imshow("Input-Image" , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": _UpperCAmelCase = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') _UpperCAmelCase = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
328
0
import torch from diffusers import StableDiffusionPipeline _UpperCAmelCase = 'path-to-your-trained-model' _UpperCAmelCase = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to('cuda') _UpperCAmelCase = 'A photo of sks dog in a bucket' _UpperCAmelCase = pipe(prompt, num_inference_steps=5_0, guidance_scale=7.5).images[0] image.save('dog-bucket.png')
350
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _UpperCAmelCase = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' _UpperCAmelCase = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' _UpperCAmelCase = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: return float((preds == labels).mean() ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_="binary" ) -> Tuple: UpperCamelCase_ = simple_accuracy(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average=UpperCamelCase_ ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: UpperCamelCase_ = {} for id_pred, label in zip(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = F'''{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}''' UpperCamelCase_ = id_pred["prediction"] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase_ = [(pred, label)] UpperCamelCase_ , UpperCamelCase_ = [], [] for question, preds_labels in question_map.items(): UpperCamelCase_ , UpperCamelCase_ = zip(*UpperCamelCase_ ) UpperCamelCase_ = fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average="macro" ) fas.append(UpperCamelCase_ ) UpperCamelCase_ = int(sum(pred == label for pred, label in preds_labels ) == len(UpperCamelCase_ ) ) ems.append(UpperCamelCase_ ) UpperCamelCase_ = float(sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) ) UpperCamelCase_ = sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=[id_pred["prediction"] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCamelCase ( datasets.Metric ): def lowercase ( self: Optional[int] ) -> Optional[int]: """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="numpy" if not self.config_name == "record" and not self.config_name == "multirc" else None , ) def lowercase ( self: List[Any] ) -> int: """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "prediction_text": datasets.Value("string" ), }, "references": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "answers": datasets.Sequence(datasets.Value("string" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("int64" ), "paragraph": datasets.Value("int64" ), "question": datasets.Value("int64" ), }, "prediction": datasets.Value("int64" ), }, "references": datasets.Value("int64" ), } else: return { "predictions": datasets.Value("int64" ), "references": datasets.Value("int64" ), } def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> Dict: """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="macro" ) elif self.config_name == "record": UpperCamelCase_ = [ { "qas": [ {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]} for ref in references ] } ] UpperCamelCase_ = {pred["idx"]["query"]: pred["prediction_text"] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" )
328
0
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_ ( UpperCamelCase_ ) -> Optional[Any]: UpperCamelCase_ = filter(lambda UpperCamelCase_ : p.requires_grad , model.parameters() ) UpperCamelCase_ = sum([np.prod(p.size() ) for p in model_parameters] ) return params _UpperCAmelCase = logging.getLogger(__name__) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: if metric == "rouge2": UpperCamelCase_ = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": UpperCamelCase_ = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": UpperCamelCase_ = "{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." ) UpperCamelCase_ = ModelCheckpoint( dirpath=UpperCamelCase_ , filename=UpperCamelCase_ , monitor=F'''val_{metric}''' , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: return EarlyStopping( monitor=F'''val_{metric}''' , mode="min" if "loss" in metric else "max" , patience=UpperCamelCase_ , verbose=UpperCamelCase_ , ) class _UpperCamelCase ( pl.Callback ): def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: List[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = {f'''lr_group_{i}''': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_SCREAMING_SNAKE_CASE ) @rank_zero_only def lowercase ( self: int , _SCREAMING_SNAKE_CASE: pl.Trainer , _SCREAMING_SNAKE_CASE: pl.LightningModule , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: str=True ) -> None: """simple docstring""" logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) UpperCamelCase_ = 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 UpperCamelCase_ = Path(pl_module.hparams.output_dir ) if type_path == "test": UpperCamelCase_ = od / "test_results.txt" UpperCamelCase_ = 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. UpperCamelCase_ = od / f'''{type_path}_results/{trainer.global_step:05d}.txt''' UpperCamelCase_ = od / f'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) generations_file.parent.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , "a+" ) as writer: for key in sorted(_SCREAMING_SNAKE_CASE ): if key in ["log", "progress_bar", "preds"]: continue UpperCamelCase_ = metrics[key] if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): UpperCamelCase_ = val.item() UpperCamelCase_ = f'''{key}: {val:.6f}\n''' writer.write(_SCREAMING_SNAKE_CASE ) if not save_generations: return if "preds" in metrics: UpperCamelCase_ = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_SCREAMING_SNAKE_CASE ) @rank_zero_only def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Any: """simple docstring""" try: UpperCamelCase_ = pl_module.model.model.num_parameters() except AttributeError: UpperCamelCase_ = pl_module.model.num_parameters() UpperCamelCase_ = count_trainable_parameters(_SCREAMING_SNAKE_CASE ) # 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 lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: pl.Trainer , _SCREAMING_SNAKE_CASE: pl.LightningModule ) -> Tuple: """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , "test" ) @rank_zero_only def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: pl.Trainer , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Union[str, Any]: """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
351
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = '''mgp-str''' def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[int]=[32, 128] , _SCREAMING_SNAKE_CASE: Tuple=4 , _SCREAMING_SNAKE_CASE: Optional[Any]=3 , _SCREAMING_SNAKE_CASE: Optional[int]=27 , _SCREAMING_SNAKE_CASE: Tuple=38 , _SCREAMING_SNAKE_CASE: Tuple=50257 , _SCREAMING_SNAKE_CASE: List[Any]=30522 , _SCREAMING_SNAKE_CASE: Optional[Any]=768 , _SCREAMING_SNAKE_CASE: Dict=12 , _SCREAMING_SNAKE_CASE: List[str]=12 , _SCREAMING_SNAKE_CASE: Dict=4.0 , _SCREAMING_SNAKE_CASE: int=True , _SCREAMING_SNAKE_CASE: Tuple=False , _SCREAMING_SNAKE_CASE: Tuple=1e-5 , _SCREAMING_SNAKE_CASE: Optional[Any]=0.0 , _SCREAMING_SNAKE_CASE: Tuple=0.0 , _SCREAMING_SNAKE_CASE: List[Any]=0.0 , _SCREAMING_SNAKE_CASE: List[str]=False , _SCREAMING_SNAKE_CASE: int=0.02 , **_SCREAMING_SNAKE_CASE: Any , ) -> str: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = image_size UpperCamelCase_ = patch_size UpperCamelCase_ = num_channels UpperCamelCase_ = max_token_length UpperCamelCase_ = num_character_labels UpperCamelCase_ = num_bpe_labels UpperCamelCase_ = num_wordpiece_labels UpperCamelCase_ = hidden_size UpperCamelCase_ = num_hidden_layers UpperCamelCase_ = num_attention_heads UpperCamelCase_ = mlp_ratio UpperCamelCase_ = distilled UpperCamelCase_ = layer_norm_eps UpperCamelCase_ = drop_rate UpperCamelCase_ = qkv_bias UpperCamelCase_ = attn_drop_rate UpperCamelCase_ = drop_path_rate UpperCamelCase_ = output_aa_attentions UpperCamelCase_ = initializer_range
328
0
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCAmelCase = {'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'MRA_PRETRAINED_MODEL_ARCHIVE_LIST', 'MraForMaskedLM', 'MraForMultipleChoice', 'MraForQuestionAnswering', 'MraForSequenceClassification', 'MraForTokenClassification', 'MraLayer', 'MraModel', 'MraPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure)
352
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _UpperCAmelCase = logging.getLogger(__name__) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether tp freeze the encoder.'''} ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether to freeze the embeddings.'''} ) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''} ) _UpperCamelCase : Optional[str] = field( default='''summarization''' , metadata={'''help''': '''Task name, summarization (or summarization_{dataset} for pegasus) or translation'''} , ) _UpperCamelCase : Optional[int] = 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 : Optional[int] = field( default=1_2_8 , metadata={ '''help''': ( '''The maximum total sequence length for target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for validation target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded. ''' '''This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ''' '''during ``evaluate`` and ``predict``.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for test target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# training examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# validation examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# test examples. -1 means use all.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Source language id for translation.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Target language id for translation.'''} ) _UpperCamelCase : Optional[int] = field(default=lowerCAmelCase_ , metadata={'''help''': '''# num_beams to use for evaluation.'''} ) _UpperCamelCase : bool = field( default=lowerCAmelCase_ , metadata={'''help''': '''If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'''} , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[int]: logger.info(F'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(F''' {key} = {metrics[key]}''' ) save_json(UpperCamelCase_ , os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) ) def lowerCAmelCase_ ( ) -> Optional[int]: # 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. UpperCamelCase_ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_args_into_dataclasses() check_output_dir(UpperCamelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , UpperCamelCase_ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): assert hasattr(UpperCamelCase_ , UpperCamelCase_ ), F'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(UpperCamelCase_ , UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) UpperCamelCase_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=UpperCamelCase_ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(UpperCamelCase_ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: UpperCamelCase_ = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(UpperCamelCase_ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = tokenizer.lang_code_to_id[data_args.tgt_lang] else: UpperCamelCase_ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(UpperCamelCase_ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) UpperCamelCase_ = SeqaSeqDataset # Get datasets UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_train else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_predict else None ) # Initialize our Trainer UpperCamelCase_ = ( build_compute_metrics_fn(data_args.task , UpperCamelCase_ ) if training_args.predict_with_generate else None ) UpperCamelCase_ = SeqaSeqTrainer( model=UpperCamelCase_ , args=UpperCamelCase_ , data_args=UpperCamelCase_ , train_dataset=UpperCamelCase_ , eval_dataset=UpperCamelCase_ , data_collator=SeqaSeqDataCollator( UpperCamelCase_ , UpperCamelCase_ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=UpperCamelCase_ , tokenizer=UpperCamelCase_ , ) UpperCamelCase_ = {} # Training if training_args.do_train: logger.info("*** Train ***" ) UpperCamelCase_ = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) UpperCamelCase_ = train_result.metrics UpperCamelCase_ = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("train" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) UpperCamelCase_ = trainer.evaluate(metric_key_prefix="val" ) UpperCamelCase_ = data_args.n_val UpperCamelCase_ = round(metrics["val_loss"] , 4 ) if trainer.is_world_process_zero(): handle_metrics("val" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.do_predict: logger.info("*** Predict ***" ) UpperCamelCase_ = trainer.predict(test_dataset=UpperCamelCase_ , metric_key_prefix="test" ) UpperCamelCase_ = test_output.metrics UpperCamelCase_ = data_args.n_test if trainer.is_world_process_zero(): UpperCamelCase_ = round(metrics["test_loss"] , 4 ) handle_metrics("test" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.predict_with_generate: UpperCamelCase_ = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_ ) UpperCamelCase_ = lmap(str.strip , UpperCamelCase_ ) write_txt_file(UpperCamelCase_ , os.path.join(training_args.output_dir , "test_generations.txt" ) ) if trainer.is_world_process_zero(): save_json(UpperCamelCase_ , os.path.join(training_args.output_dir , "all_results.json" ) ) return all_metrics def lowerCAmelCase_ ( UpperCamelCase_ ) -> Optional[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
328
0
from math import pi def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> float: return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
353
def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = int(UpperCamelCase_ ) if n_element < 1: UpperCamelCase_ = ValueError("a should be a positive number" ) raise my_error UpperCamelCase_ = [1] UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = (0, 0, 0) UpperCamelCase_ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _UpperCAmelCase = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') _UpperCAmelCase = hamming(int(n)) print('-----------------------------------------------------') print(f'''The list with nth numbers is: {hamming_numbers}''') print('-----------------------------------------------------')
328
0
import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: str , _SCREAMING_SNAKE_CASE: int ) -> Any: """simple docstring""" UpperCamelCase_ = 3 UpperCamelCase_ = 250 UpperCamelCase_ = ids_tensor((batch_size, length) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.ones((batch_size, length) , device=_SCREAMING_SNAKE_CASE , dtype=torch.float ) / length return input_ids, scores def lowercase ( self: List[str] ) -> Tuple: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(5 ) UpperCamelCase_ = StoppingCriteriaList( [ MaxLengthCriteria(max_length=10 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(9 ) self.assertFalse(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(10 ) self.assertTrue(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: int ) -> Any: """simple docstring""" UpperCamelCase_ = MaxLengthCriteria(max_length=10 ) UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(5 ) self.assertFalse(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(9 ) self.assertFalse(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(10 ) self.assertTrue(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: Optional[int] ) -> Tuple: """simple docstring""" UpperCamelCase_ = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(5 ) self.assertFalse(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(9 ) self.assertFalse(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(10 ) self.assertTrue(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 10 ) def lowercase ( self: List[Any] ) -> Any: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = self._get_tensors(5 ) UpperCamelCase_ = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: Dict ) -> List[str]: """simple docstring""" validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 ) with self.assertWarns(_SCREAMING_SNAKE_CASE ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 ) UpperCamelCase_ = validate_stopping_criteria(StoppingCriteriaList() , 11 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 1 )
354
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : List[Any] = IFImgaImgSuperResolutionPipeline _UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} _UpperCamelCase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) _UpperCamelCase : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowercase ( self: List[str] ) -> Any: """simple docstring""" return self._get_superresolution_dummy_components() def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[int]=0 ) -> List[Any]: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Any ) -> Union[str, Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowercase ( self: int ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowercase ( self: Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowercase ( self: List[Any] ) -> Union[str, Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowercase ( self: Dict ) -> Any: """simple docstring""" self._test_save_load_local() def lowercase ( self: Any ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
328
0
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: Union[str, Any] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowercase ( self: Dict ) -> int: """simple docstring""" UpperCamelCase_ = 1 UpperCamelCase_ = 3 UpperCamelCase_ = (32, 32) UpperCamelCase_ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) return image @property def lowercase ( self: List[Any] ) -> Any: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = 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 lowercase ( self: Tuple ) -> str: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = 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 lowercase ( self: Dict ) -> int: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = 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 , ) return CLIPTextModel(_SCREAMING_SNAKE_CASE ) @property def lowercase ( self: Union[str, Any] ) -> Union[str, Any]: """simple docstring""" def extract(*_SCREAMING_SNAKE_CASE: Optional[int] , **_SCREAMING_SNAKE_CASE: Optional[int] ): class _UpperCamelCase : def __init__( self: Optional[int] ) -> int: """simple docstring""" UpperCamelCase_ = torch.ones([0] ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Optional[Any] ) -> Optional[int]: """simple docstring""" self.pixel_values.to(_SCREAMING_SNAKE_CASE ) return self return Out() return extract def lowercase ( self: int ) -> List[Any]: """simple docstring""" UpperCamelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCamelCase_ = self.dummy_cond_unet UpperCamelCase_ = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=_SCREAMING_SNAKE_CASE , set_alpha_to_one=_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = self.dummy_vae UpperCamelCase_ = self.dummy_text_encoder UpperCamelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk UpperCamelCase_ = StableDiffusionPipeline( unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=self.dummy_extractor , ) UpperCamelCase_ = sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = "A painting of a squirrel eating a burger" UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase_ = sd_pipe([prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) UpperCamelCase_ = output.images UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase_ = sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=_SCREAMING_SNAKE_CASE , )[0] UpperCamelCase_ = image[0, -3:, -3:, -1] UpperCamelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase_ = np.array([0.57_56, 0.61_18, 0.50_05, 0.50_41, 0.54_71, 0.47_26, 0.49_76, 0.48_65, 0.48_64] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self: Optional[Any] ) -> Dict: """simple docstring""" UpperCamelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCamelCase_ = self.dummy_cond_unet UpperCamelCase_ = PNDMScheduler(skip_prk_steps=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.dummy_vae UpperCamelCase_ = self.dummy_text_encoder UpperCamelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk UpperCamelCase_ = StableDiffusionPipeline( unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=self.dummy_extractor , ) UpperCamelCase_ = sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = "A painting of a squirrel eating a burger" UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase_ = sd_pipe([prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) UpperCamelCase_ = output.images UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase_ = sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=_SCREAMING_SNAKE_CASE , )[0] UpperCamelCase_ = image[0, -3:, -3:, -1] UpperCamelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase_ = np.array([0.51_25, 0.57_16, 0.48_28, 0.50_60, 0.56_50, 0.47_68, 0.51_85, 0.48_95, 0.49_93] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self: str ) -> Dict: """simple docstring""" UpperCamelCase_ = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=_SCREAMING_SNAKE_CASE ) assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert isinstance(pipe.scheduler , _SCREAMING_SNAKE_CASE ) assert pipe.safety_checker is None UpperCamelCase_ = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) # sanity check that the pipeline still works assert pipe.safety_checker is None UpperCamelCase_ = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def lowercase ( self: List[str] ) -> List[str]: """simple docstring""" UpperCamelCase_ = self.dummy_cond_unet UpperCamelCase_ = PNDMScheduler(skip_prk_steps=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.dummy_vae UpperCamelCase_ = self.dummy_text_encoder UpperCamelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 UpperCamelCase_ = unet.half() UpperCamelCase_ = vae.half() UpperCamelCase_ = bert.half() # make sure here that pndm scheduler skips prk UpperCamelCase_ = StableDiffusionPipeline( unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=self.dummy_extractor , ) UpperCamelCase_ = sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = "A painting of a squirrel eating a burger" UpperCamelCase_ = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: Union[str, Any] ) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self: Optional[int] ) -> str: """simple docstring""" UpperCamelCase_ = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) UpperCamelCase_ = sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = ( "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle" " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with" " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and" " children from bahnhof zoo, detailed " ) UpperCamelCase_ = 4003660346 UpperCamelCase_ = 7 # without safety guidance (sld_guidance_scale = 0) UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) UpperCamelCase_ = output.images UpperCamelCase_ = image[0, -3:, -3:, -1] UpperCamelCase_ = [0.22_78, 0.22_31, 0.22_49, 0.23_33, 0.23_03, 0.18_85, 0.22_73, 0.21_44, 0.21_76] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_25 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) UpperCamelCase_ = output.images UpperCamelCase_ = image[0, -3:, -3:, -1] UpperCamelCase_ = [0.23_83, 0.22_76, 0.2_36, 0.21_92, 0.21_86, 0.20_53, 0.19_71, 0.19_01, 0.17_19] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self: List[Any] ) -> Any: """simple docstring""" UpperCamelCase_ = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) UpperCamelCase_ = sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = "padme amidala taking a bath artwork, safe for work, no nudity" UpperCamelCase_ = 2734971755 UpperCamelCase_ = 7 UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) UpperCamelCase_ = output.images UpperCamelCase_ = image[0, -3:, -3:, -1] UpperCamelCase_ = [0.35_02, 0.36_22, 0.33_96, 0.36_42, 0.34_78, 0.33_18, 0.35, 0.33_48, 0.32_97] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_25 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) UpperCamelCase_ = output.images UpperCamelCase_ = image[0, -3:, -3:, -1] UpperCamelCase_ = [0.55_31, 0.52_06, 0.48_95, 0.51_56, 0.51_82, 0.47_51, 0.48_02, 0.48_03, 0.44_43] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self: List[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) UpperCamelCase_ = sd_pipe.to(_SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = ( "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c." " leyendecker" ) UpperCamelCase_ = 1044355234 UpperCamelCase_ = 12 UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) UpperCamelCase_ = output.images UpperCamelCase_ = image[0, -3:, -3:, -1] UpperCamelCase_ = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = sd_pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_25 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) UpperCamelCase_ = output.images UpperCamelCase_ = image[0, -3:, -3:, -1] UpperCamelCase_ = np.array([0.58_18, 0.62_85, 0.68_35, 0.60_19, 0.6_25, 0.67_54, 0.60_96, 0.63_34, 0.65_61] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
355
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent _UpperCAmelCase = {'UserAgent': UserAgent().random} def lowerCAmelCase_ ( UpperCamelCase_ ) -> dict: UpperCamelCase_ = script.contents[0] UpperCamelCase_ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class _UpperCamelCase : def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = f'''https://www.instagram.com/{username}/''' UpperCamelCase_ = self.get_json() def lowercase ( self: Union[str, Any] ) -> dict: """simple docstring""" UpperCamelCase_ = requests.get(self.url , headers=_SCREAMING_SNAKE_CASE ).text UpperCamelCase_ = BeautifulSoup(_SCREAMING_SNAKE_CASE , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self: Tuple ) -> str: """simple docstring""" return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self: List[Any] ) -> str: """simple docstring""" return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["username"] @property def lowercase ( self: int ) -> str: """simple docstring""" return self.user_data["full_name"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["biography"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["business_email"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["external_url"] @property def lowercase ( self: List[Any] ) -> int: """simple docstring""" return self.user_data["edge_followed_by"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_follow"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["profile_pic_url_hd"] @property def lowercase ( self: Optional[int] ) -> bool: """simple docstring""" return self.user_data["is_verified"] @property def lowercase ( self: List[str] ) -> bool: """simple docstring""" return self.user_data["is_private"] def lowerCAmelCase_ ( UpperCamelCase_ = "github" ) -> None: import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase_ = InstagramUser(UpperCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , UpperCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = InstagramUser('github') print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
328
0
def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> int: return 1 if input_a == input_a else 0 def lowerCAmelCase_ ( ) -> None: assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
356
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _UpperCAmelCase = False _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = 'ybelkada/fonts' def lowerCAmelCase_ ( ) -> Dict: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: requires_backends(UpperCamelCase_ , ["torch"] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase_ , UpperCamelCase_ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = 36 , UpperCamelCase_ = "black" , UpperCamelCase_ = "white" , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> Image.Image: requires_backends(UpperCamelCase_ , "vision" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase_ ) UpperCamelCase_ = "\n".join(UpperCamelCase_ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase_ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase_ , "Arial.TTF" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase_ , encoding="UTF-8" , size=UpperCamelCase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , UpperCamelCase_ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase_ , UpperCamelCase_ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("RGB" , (image_width, image_height) , UpperCamelCase_ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase_ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase_ , fill=UpperCamelCase_ , font=UpperCamelCase_ ) return image def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> Union[str, Any]: requires_backends(UpperCamelCase_ , "vision" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase_ ) UpperCamelCase_ = render_text(UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase_ ) if infer_channel_dimension_format(UpperCamelCase_ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase_ , ChannelDimension.LAST ) return new_image class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''flattened_patches'''] def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: Optional[Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: dict , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = patch_size["height"], patch_size["width"] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_SCREAMING_SNAKE_CASE ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_SCREAMING_SNAKE_CASE , antialias=_SCREAMING_SNAKE_CASE , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([rows, 1] ).repeat(1 , _SCREAMING_SNAKE_CASE ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([1, columns] ).repeat(_SCREAMING_SNAKE_CASE , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_SCREAMING_SNAKE_CASE , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) return result def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: List[str] ) -> np.ndarray: """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = np.std(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: Optional[Dict[str, int]] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> ImageInput: """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("data_format" , _SCREAMING_SNAKE_CASE ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) UpperCamelCase_ = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) UpperCamelCase_ = kwargs.pop("font_bytes" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("font_path" , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [header_text] * len(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [ render_header(_SCREAMING_SNAKE_CASE , header_text[i] , font_bytes=_SCREAMING_SNAKE_CASE , font_path=_SCREAMING_SNAKE_CASE ) for i, image in enumerate(_SCREAMING_SNAKE_CASE ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_SCREAMING_SNAKE_CASE , max_patches=_SCREAMING_SNAKE_CASE , patch_size=_SCREAMING_SNAKE_CASE ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_outputs
328
0
import os from datetime import datetime as dt from github import Github _UpperCAmelCase = [ 'good first issue', 'feature request', 'wip', ] def lowerCAmelCase_ ( ) -> Union[str, Any]: UpperCamelCase_ = Github(os.environ["GITHUB_TOKEN"] ) UpperCamelCase_ = g.get_repo("huggingface/accelerate" ) UpperCamelCase_ = repo.get_issues(state="open" ) for issue in open_issues: UpperCamelCase_ = sorted([comment for comment in issue.get_comments()] , key=lambda UpperCamelCase_ : i.created_at , reverse=UpperCamelCase_ ) UpperCamelCase_ = comments[0] if len(UpperCamelCase_ ) > 0 else None UpperCamelCase_ = dt.utcnow() UpperCamelCase_ = (current_time - issue.updated_at).days UpperCamelCase_ = (current_time - issue.created_at).days if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and days_since_updated > 7 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Close issue since it has been 7 days of inactivity since bot mention. issue.edit(state="closed" ) elif ( days_since_updated > 23 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Add stale comment issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) " "are likely to be ignored." ) if __name__ == "__main__": main()
357
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: Any , _SCREAMING_SNAKE_CASE: int = 768 , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(1 , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(torch.ones(1 , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[Union[str, torch.device]] = None , _SCREAMING_SNAKE_CASE: Optional[torch.dtype] = None , ) -> List[Any]: """simple docstring""" UpperCamelCase_ = nn.Parameter(self.mean.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(self.std.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) return self def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = (embeds - self.mean) * 1.0 / self.std return embeds def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Dict: """simple docstring""" UpperCamelCase_ = (embeds * self.std) + self.mean return embeds
328
0
"""simple docstring""" from math import factorial def lowerCAmelCase_ ( UpperCamelCase_ = 20 ) -> int: UpperCamelCase_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... UpperCamelCase_ = n // 2 return int(factorial(UpperCamelCase_ ) / (factorial(UpperCamelCase_ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: _UpperCAmelCase = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
358
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _UpperCAmelCase = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) _UpperCAmelCase = logging.getLogger() def lowerCAmelCase_ ( ) -> Optional[int]: UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCamelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_="eval" ) -> Any: UpperCamelCase_ = os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) if os.path.exists(UpperCamelCase_ ): with open(UpperCamelCase_ , "r" ) as f: return json.load(UpperCamelCase_ ) raise ValueError(F'''can\'t find {path}''' ) _UpperCAmelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _UpperCamelCase ( lowerCAmelCase_ ): def lowercase ( self: Optional[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_glue.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) @slow def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_clm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 100 ) @slow def lowercase ( self: Any ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_summarization_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE , split="test" ) self.assertGreaterEqual(result["test_rouge1"] , 10 ) self.assertGreaterEqual(result["test_rouge2"] , 2 ) self.assertGreaterEqual(result["test_rougeL"] , 7 ) self.assertGreaterEqual(result["test_rougeLsum"] , 7 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 42 ) @slow def lowercase ( self: Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_ta_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.42 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_ner.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertGreaterEqual(result["eval_f1"] , 0.3 ) @slow def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_qa.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_f1"] , 30 ) self.assertGreaterEqual(result["eval_exact"] , 30 )
328
0
from __future__ import annotations import math def lowerCAmelCase_ ( UpperCamelCase_ ) -> 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(UpperCamelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True _UpperCAmelCase = [num for num in range(3, 1_0_0_0_0_1, 2) if not is_prime(num)] def lowerCAmelCase_ ( UpperCamelCase_ ) -> list[int]: if not isinstance(UpperCamelCase_ , UpperCamelCase_ ): raise ValueError("n must be an integer" ) if n <= 0: raise ValueError("n must be >= 0" ) UpperCamelCase_ = [] for num in range(len(UpperCamelCase_ ) ): UpperCamelCase_ = 0 while 2 * i * i <= odd_composites[num]: UpperCamelCase_ = odd_composites[num] - 2 * i * i if is_prime(UpperCamelCase_ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(UpperCamelCase_ ) == n: return list_nums return [] def lowerCAmelCase_ ( ) -> int: return compute_nums(1 )[0] if __name__ == "__main__": print(f'''{solution() = }''')
359
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: for param in module.parameters(): UpperCamelCase_ = False def lowerCAmelCase_ ( ) -> Dict: UpperCamelCase_ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): UpperCamelCase_ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def lowerCAmelCase_ ( ) -> List[str]: UpperCamelCase_ = datetime.now() UpperCamelCase_ = current_time.strftime("%H:%M:%S" ) return timestamp
328
0
import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = ['model.decoder.embed_positions.weights'] def lowerCAmelCase_ ( UpperCamelCase_ ) -> Any: if "emb" in name: UpperCamelCase_ = name.replace("emb" , "model.decoder.embed_tokens" ) if "transformer" in name: UpperCamelCase_ = name.replace("transformer" , "model.decoder" ) if "cross_attention" in name: UpperCamelCase_ = name.replace("cross_attention" , "encoder_attn" ) if "linear1" in name: UpperCamelCase_ = name.replace("linear1" , "fc1" ) if "linear2" in name: UpperCamelCase_ = name.replace("linear2" , "fc2" ) if "norm1" in name: UpperCamelCase_ = name.replace("norm1" , "self_attn_layer_norm" ) if "norm_cross" in name: UpperCamelCase_ = name.replace("norm_cross" , "encoder_attn_layer_norm" ) if "norm2" in name: UpperCamelCase_ = name.replace("norm2" , "final_layer_norm" ) if "out_norm" in name: UpperCamelCase_ = name.replace("out_norm" , "model.decoder.layer_norm" ) if "linears" in name: UpperCamelCase_ = name.replace("linears" , "lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: UpperCamelCase_ = name.replace("condition_provider.conditioners.description.output_proj" , "enc_to_dec_proj" ) return name def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Tuple[Dict, Dict]: UpperCamelCase_ = list(state_dict.keys() ) UpperCamelCase_ = {} for key in keys: UpperCamelCase_ = state_dict.pop(UpperCamelCase_ ) UpperCamelCase_ = rename_keys(UpperCamelCase_ ) if "in_proj_weight" in key: # split fused qkv proj UpperCamelCase_ = val[:hidden_size, :] UpperCamelCase_ = val[hidden_size : 2 * hidden_size, :] UpperCamelCase_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: UpperCamelCase_ = val else: UpperCamelCase_ = val return state_dict, enc_dec_proj_state_dict def lowerCAmelCase_ ( UpperCamelCase_ ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values UpperCamelCase_ = 1024 UpperCamelCase_ = 24 UpperCamelCase_ = 16 elif checkpoint == "medium": UpperCamelCase_ = 1536 UpperCamelCase_ = 48 UpperCamelCase_ = 24 elif checkpoint == "large": UpperCamelCase_ = 2048 UpperCamelCase_ = 48 UpperCamelCase_ = 32 else: raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) UpperCamelCase_ = MusicgenDecoderConfig( hidden_size=UpperCamelCase_ , ffn_dim=hidden_size * 4 , num_hidden_layers=UpperCamelCase_ , num_attention_heads=UpperCamelCase_ , ) return config @torch.no_grad() def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_="cpu" ) -> str: UpperCamelCase_ = MusicGen.get_pretrained(UpperCamelCase_ , device=UpperCamelCase_ ) UpperCamelCase_ = decoder_config_from_checkpoint(UpperCamelCase_ ) UpperCamelCase_ = fairseq_model.lm.state_dict() UpperCamelCase_ , UpperCamelCase_ = rename_state_dict( UpperCamelCase_ , hidden_size=decoder_config.hidden_size ) UpperCamelCase_ = TaEncoderModel.from_pretrained("t5-base" ) UpperCamelCase_ = EncodecModel.from_pretrained("facebook/encodec_32khz" ) UpperCamelCase_ = MusicgenForCausalLM(UpperCamelCase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection UpperCamelCase_ , UpperCamelCase_ = decoder.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(UpperCamelCase_ ) if len(UpperCamelCase_ ) > 0: raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' ) if len(UpperCamelCase_ ) > 0: raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model UpperCamelCase_ = MusicgenForConditionalGeneration(text_encoder=UpperCamelCase_ , audio_encoder=UpperCamelCase_ , decoder=UpperCamelCase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(UpperCamelCase_ ) # check we can do a forward pass UpperCamelCase_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) UpperCamelCase_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): UpperCamelCase_ = model(input_ids=UpperCamelCase_ , decoder_input_ids=UpperCamelCase_ ).logits if logits.shape != (8, 1, 2048): raise ValueError("Incorrect shape for logits" ) # now construct the processor UpperCamelCase_ = AutoTokenizer.from_pretrained("t5-base" ) UpperCamelCase_ = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" , padding_side="left" ) UpperCamelCase_ = MusicgenProcessor(feature_extractor=UpperCamelCase_ , tokenizer=UpperCamelCase_ ) # set the appropriate bos/pad token ids UpperCamelCase_ = 2048 UpperCamelCase_ = 2048 # set other default generation config params UpperCamelCase_ = int(30 * audio_encoder.config.frame_rate ) UpperCamelCase_ = True UpperCamelCase_ = 3.0 if pytorch_dump_folder is not None: Path(UpperCamelCase_ ).mkdir(exist_ok=UpperCamelCase_ ) logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(UpperCamelCase_ ) processor.save_pretrained(UpperCamelCase_ ) if repo_id: logger.info(F'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(UpperCamelCase_ ) processor.push_to_hub(UpperCamelCase_ ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) _UpperCAmelCase = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
360
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 _UpperCAmelCase = '▁' _UpperCAmelCase = {'vocab_file': 'spiece.model'} _UpperCAmelCase = { 'vocab_file': {'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'} } _UpperCAmelCase = { 'google/pegasus-xsum': 5_1_2, } _UpperCAmelCase = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = VOCAB_FILES_NAMES _UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[int] = ['''input_ids''', '''attention_mask'''] def __init__( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: str="<pad>" , _SCREAMING_SNAKE_CASE: Optional[Any]="</s>" , _SCREAMING_SNAKE_CASE: Any="<unk>" , _SCREAMING_SNAKE_CASE: int="<mask_2>" , _SCREAMING_SNAKE_CASE: List[Any]="<mask_1>" , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: Optional[int]=103 , _SCREAMING_SNAKE_CASE: Optional[Dict[str, Any]] = None , **_SCREAMING_SNAKE_CASE: Dict , ) -> None: """simple docstring""" UpperCamelCase_ = offset if additional_special_tokens is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError( f'''additional_special_tokens should be of type {type(_SCREAMING_SNAKE_CASE )}, but is''' f''' {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'''<unk_{i}>''' for i in range(len(_SCREAMING_SNAKE_CASE ) , self.offset - 1 ) ] if len(set(_SCREAMING_SNAKE_CASE ) ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError( "Please make sure that the provided additional_special_tokens do not contain an incorrectly" f''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) UpperCamelCase_ = additional_special_tokens_extended else: UpperCamelCase_ = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'''<unk_{i}>''' for i in range(2 , self.offset )] UpperCamelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token_sent=_SCREAMING_SNAKE_CASE , offset=_SCREAMING_SNAKE_CASE , additional_special_tokens=_SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = mask_token_sent UpperCamelCase_ = vocab_file UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_SCREAMING_SNAKE_CASE ) # add special tokens to encoder dict UpperCamelCase_ = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) UpperCamelCase_ = {v: k for k, v in self.encoder.items()} @property def lowercase ( self: Dict ) -> int: """simple docstring""" return len(self.sp_model ) + self.offset def lowercase ( self: int ) -> Dict[str, int]: """simple docstring""" UpperCamelCase_ = {self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self: Optional[int] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = self.__dict__.copy() UpperCamelCase_ = None return state def __setstate__( self: List[Any] , _SCREAMING_SNAKE_CASE: List[Any] ) -> Any: """simple docstring""" UpperCamelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCamelCase_ = {} UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_SCREAMING_SNAKE_CASE , out_type=_SCREAMING_SNAKE_CASE ) def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: str ) -> int: """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] UpperCamelCase_ = self.sp_model.piece_to_id(_SCREAMING_SNAKE_CASE ) return sp_id + self.offset def lowercase ( self: str , _SCREAMING_SNAKE_CASE: int ) -> str: """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: UpperCamelCase_ = self.sp_model.IdToPiece(index - self.offset ) return token def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = [] UpperCamelCase_ = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) + token UpperCamelCase_ = [] else: current_sub_tokens.append(_SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) return out_string.strip() def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Optional[int]=False ) -> Union[str, Any]: """simple docstring""" return 1 def lowercase ( self: int , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: List , _SCREAMING_SNAKE_CASE: Optional[List] = None , _SCREAMING_SNAKE_CASE: bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) elif token_ids_a is None: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any]=None ) -> List[int]: """simple docstring""" if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCamelCase_ = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(_SCREAMING_SNAKE_CASE , "wb" ) as fi: UpperCamelCase_ = self.sp_model.serialized_model_proto() fi.write(_SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
328
0
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _UpperCAmelCase = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' _UpperCAmelCase = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' _UpperCAmelCase = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: return float((preds == labels).mean() ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_="binary" ) -> Tuple: UpperCamelCase_ = simple_accuracy(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average=UpperCamelCase_ ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: UpperCamelCase_ = {} for id_pred, label in zip(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = F'''{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}''' UpperCamelCase_ = id_pred["prediction"] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase_ = [(pred, label)] UpperCamelCase_ , UpperCamelCase_ = [], [] for question, preds_labels in question_map.items(): UpperCamelCase_ , UpperCamelCase_ = zip(*UpperCamelCase_ ) UpperCamelCase_ = fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average="macro" ) fas.append(UpperCamelCase_ ) UpperCamelCase_ = int(sum(pred == label for pred, label in preds_labels ) == len(UpperCamelCase_ ) ) ems.append(UpperCamelCase_ ) UpperCamelCase_ = float(sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) ) UpperCamelCase_ = sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=[id_pred["prediction"] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCamelCase ( datasets.Metric ): def lowercase ( self: Optional[int] ) -> Optional[int]: """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="numpy" if not self.config_name == "record" and not self.config_name == "multirc" else None , ) def lowercase ( self: List[Any] ) -> int: """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "prediction_text": datasets.Value("string" ), }, "references": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "answers": datasets.Sequence(datasets.Value("string" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("int64" ), "paragraph": datasets.Value("int64" ), "question": datasets.Value("int64" ), }, "prediction": datasets.Value("int64" ), }, "references": datasets.Value("int64" ), } else: return { "predictions": datasets.Value("int64" ), "references": datasets.Value("int64" ), } def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> Dict: """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="macro" ) elif self.config_name == "record": UpperCamelCase_ = [ { "qas": [ {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]} for ref in references ] } ] UpperCamelCase_ = {pred["idx"]["query"]: pred["prediction_text"] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" )
361
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { 'configuration_tapas': ['TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TapasConfig'], 'tokenization_tapas': ['TapasTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TapasForMaskedLM', 'TapasForQuestionAnswering', 'TapasForSequenceClassification', 'TapasModel', 'TapasPreTrainedModel', 'load_tf_weights_in_tapas', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFTapasForMaskedLM', 'TFTapasForQuestionAnswering', 'TFTapasForSequenceClassification', 'TFTapasModel', 'TFTapasPreTrainedModel', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
328
0
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Union[str, Any] = ['''image_processor''', '''tokenizer'''] _UpperCamelCase : Optional[int] = '''AutoImageProcessor''' _UpperCamelCase : int = '''AutoTokenizer''' def __init__( self: int , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[int] ) -> Dict: """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.image_processor def __call__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: List[str]=None , **_SCREAMING_SNAKE_CASE: List[Any] ) -> Dict: """simple docstring""" if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: UpperCamelCase_ = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if images is not None: UpperCamelCase_ = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None and images is not None: UpperCamelCase_ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_SCREAMING_SNAKE_CASE ) , tensor_type=_SCREAMING_SNAKE_CASE ) def lowercase ( self: str , *_SCREAMING_SNAKE_CASE: List[str] , **_SCREAMING_SNAKE_CASE: int ) -> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[Any] , *_SCREAMING_SNAKE_CASE: str , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> List[Any]: """simple docstring""" return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
362
import argparse import json from tqdm import tqdm def lowerCAmelCase_ ( ) -> Tuple: UpperCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--src_path" , type=UpperCamelCase_ , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , ) parser.add_argument( "--evaluation_set" , type=UpperCamelCase_ , help="where to store parsed evaluation_set file" , ) parser.add_argument( "--gold_data_path" , type=UpperCamelCase_ , help="where to store parsed gold_data_path file" , ) UpperCamelCase_ = parser.parse_args() with open(args.src_path , "r" ) as src_file, open(args.evaluation_set , "w" ) as eval_file, open( args.gold_data_path , "w" ) as gold_file: UpperCamelCase_ = json.load(UpperCamelCase_ ) for dpr_record in tqdm(UpperCamelCase_ ): UpperCamelCase_ = dpr_record["question"] UpperCamelCase_ = [context["title"] for context in dpr_record["positive_ctxs"]] eval_file.write(question + "\n" ) gold_file.write("\t".join(UpperCamelCase_ ) + "\n" ) if __name__ == "__main__": main()
328
0
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = OrderedDict( [ ('audio-spectrogram-transformer', 'ASTFeatureExtractor'), ('beit', 'BeitFeatureExtractor'), ('chinese_clip', 'ChineseCLIPFeatureExtractor'), ('clap', 'ClapFeatureExtractor'), ('clip', 'CLIPFeatureExtractor'), ('clipseg', 'ViTFeatureExtractor'), ('conditional_detr', 'ConditionalDetrFeatureExtractor'), ('convnext', 'ConvNextFeatureExtractor'), ('cvt', 'ConvNextFeatureExtractor'), ('data2vec-audio', 'Wav2Vec2FeatureExtractor'), ('data2vec-vision', 'BeitFeatureExtractor'), ('deformable_detr', 'DeformableDetrFeatureExtractor'), ('deit', 'DeiTFeatureExtractor'), ('detr', 'DetrFeatureExtractor'), ('dinat', 'ViTFeatureExtractor'), ('donut-swin', 'DonutFeatureExtractor'), ('dpt', 'DPTFeatureExtractor'), ('encodec', 'EncodecFeatureExtractor'), ('flava', 'FlavaFeatureExtractor'), ('glpn', 'GLPNFeatureExtractor'), ('groupvit', 'CLIPFeatureExtractor'), ('hubert', 'Wav2Vec2FeatureExtractor'), ('imagegpt', 'ImageGPTFeatureExtractor'), ('layoutlmv2', 'LayoutLMv2FeatureExtractor'), ('layoutlmv3', 'LayoutLMv3FeatureExtractor'), ('levit', 'LevitFeatureExtractor'), ('maskformer', 'MaskFormerFeatureExtractor'), ('mctct', 'MCTCTFeatureExtractor'), ('mobilenet_v1', 'MobileNetV1FeatureExtractor'), ('mobilenet_v2', 'MobileNetV2FeatureExtractor'), ('mobilevit', 'MobileViTFeatureExtractor'), ('nat', 'ViTFeatureExtractor'), ('owlvit', 'OwlViTFeatureExtractor'), ('perceiver', 'PerceiverFeatureExtractor'), ('poolformer', 'PoolFormerFeatureExtractor'), ('regnet', 'ConvNextFeatureExtractor'), ('resnet', 'ConvNextFeatureExtractor'), ('segformer', 'SegformerFeatureExtractor'), ('sew', 'Wav2Vec2FeatureExtractor'), ('sew-d', 'Wav2Vec2FeatureExtractor'), ('speech_to_text', 'Speech2TextFeatureExtractor'), ('speecht5', 'SpeechT5FeatureExtractor'), ('swiftformer', 'ViTFeatureExtractor'), ('swin', 'ViTFeatureExtractor'), ('swinv2', 'ViTFeatureExtractor'), ('table-transformer', 'DetrFeatureExtractor'), ('timesformer', 'VideoMAEFeatureExtractor'), ('tvlt', 'TvltFeatureExtractor'), ('unispeech', 'Wav2Vec2FeatureExtractor'), ('unispeech-sat', 'Wav2Vec2FeatureExtractor'), ('van', 'ConvNextFeatureExtractor'), ('videomae', 'VideoMAEFeatureExtractor'), ('vilt', 'ViltFeatureExtractor'), ('vit', 'ViTFeatureExtractor'), ('vit_mae', 'ViTFeatureExtractor'), ('vit_msn', 'ViTFeatureExtractor'), ('wav2vec2', 'Wav2Vec2FeatureExtractor'), ('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'), ('wavlm', 'Wav2Vec2FeatureExtractor'), ('whisper', 'WhisperFeatureExtractor'), ('xclip', 'CLIPFeatureExtractor'), ('yolos', 'YolosFeatureExtractor'), ] ) _UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def lowerCAmelCase_ ( UpperCamelCase_ ) -> List[str]: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: UpperCamelCase_ = model_type_to_module_name(UpperCamelCase_ ) UpperCamelCase_ = importlib.import_module(F'''.{module_name}''' , "transformers.models" ) try: return getattr(UpperCamelCase_ , UpperCamelCase_ ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(UpperCamelCase_ , "__name__" , UpperCamelCase_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. UpperCamelCase_ = importlib.import_module("transformers" ) if hasattr(UpperCamelCase_ , UpperCamelCase_ ): return getattr(UpperCamelCase_ , UpperCamelCase_ ) return None def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = False , **UpperCamelCase_ , ) -> List[str]: UpperCamelCase_ = get_file_from_repo( UpperCamelCase_ , UpperCamelCase_ , cache_dir=UpperCamelCase_ , force_download=UpperCamelCase_ , resume_download=UpperCamelCase_ , proxies=UpperCamelCase_ , use_auth_token=UpperCamelCase_ , revision=UpperCamelCase_ , local_files_only=UpperCamelCase_ , ) if resolved_config_file is None: logger.info( "Could not locate the feature extractor configuration file, will try to use the model config instead." ) return {} with open(UpperCamelCase_ , encoding="utf-8" ) as reader: return json.load(UpperCamelCase_ ) class _UpperCamelCase : def __init__( self: Any ) -> Dict: """simple docstring""" raise EnvironmentError( "AutoFeatureExtractor is designed to be instantiated " "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(_SCREAMING_SNAKE_CASE ) def lowercase ( cls: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , **_SCREAMING_SNAKE_CASE: str ) -> Tuple: """simple docstring""" UpperCamelCase_ = kwargs.pop("config" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("trust_remote_code" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = True UpperCamelCase_ , UpperCamelCase_ = FeatureExtractionMixin.get_feature_extractor_dict(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = config_dict.get("feature_extractor_type" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = None if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): UpperCamelCase_ = config_dict["auto_map"]["AutoFeatureExtractor"] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) # It could be in `config.feature_extractor_type`` UpperCamelCase_ = getattr(_SCREAMING_SNAKE_CASE , "feature_extractor_type" , _SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , "auto_map" ) and "AutoFeatureExtractor" in config.auto_map: UpperCamelCase_ = config.auto_map["AutoFeatureExtractor"] if feature_extractor_class is not None: UpperCamelCase_ = feature_extractor_class_from_name(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = feature_extractor_auto_map is not None UpperCamelCase_ = feature_extractor_class is not None or type(_SCREAMING_SNAKE_CASE ) in FEATURE_EXTRACTOR_MAPPING UpperCamelCase_ = resolve_trust_remote_code( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if has_remote_code and trust_remote_code: UpperCamelCase_ = get_class_from_dynamic_module( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("code_revision" , _SCREAMING_SNAKE_CASE ) if os.path.isdir(_SCREAMING_SNAKE_CASE ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(_SCREAMING_SNAKE_CASE ) in FEATURE_EXTRACTOR_MAPPING: UpperCamelCase_ = FEATURE_EXTRACTOR_MAPPING[type(_SCREAMING_SNAKE_CASE )] return feature_extractor_class.from_dict(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) raise ValueError( f'''Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ''' f'''`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def lowercase ( _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> Union[str, Any]: """simple docstring""" FEATURE_EXTRACTOR_MAPPING.register(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
363
import requests from bsa import BeautifulSoup def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = BeautifulSoup(requests.get(UpperCamelCase_ , params=UpperCamelCase_ ).content , "html.parser" ) UpperCamelCase_ = soup.find("div" , attrs={"class": "gs_ri"} ) UpperCamelCase_ = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": _UpperCAmelCase = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
328
0
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap _UpperCAmelCase = 'Usage of script: script_name <size_of_canvas:int>' _UpperCAmelCase = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def lowerCAmelCase_ ( UpperCamelCase_ ) -> list[list[bool]]: UpperCamelCase_ = [[False for i in range(UpperCamelCase_ )] for j in range(UpperCamelCase_ )] return canvas def lowerCAmelCase_ ( UpperCamelCase_ ) -> None: for i, row in enumerate(UpperCamelCase_ ): for j, _ in enumerate(UpperCamelCase_ ): UpperCamelCase_ = bool(random.getrandbits(1 ) ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> list[list[bool]]: UpperCamelCase_ = np.array(UpperCamelCase_ ) UpperCamelCase_ = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(UpperCamelCase_ ): for c, pt in enumerate(UpperCamelCase_ ): UpperCamelCase_ = __judge_point( UpperCamelCase_ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) UpperCamelCase_ = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. UpperCamelCase_ = current_canvas.tolist() return return_canvas def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> bool: UpperCamelCase_ = 0 UpperCamelCase_ = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. UpperCamelCase_ = pt if pt: if alive < 2: UpperCamelCase_ = False elif alive == 2 or alive == 3: UpperCamelCase_ = True elif alive > 3: UpperCamelCase_ = False else: if alive == 3: UpperCamelCase_ = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) _UpperCAmelCase = int(sys.argv[1]) # main working structure of this module. _UpperCAmelCase = create_canvas(canvas_size) seed(c) _UpperCAmelCase , _UpperCAmelCase = plt.subplots() fig.show() _UpperCAmelCase = ListedColormap(['w', 'k']) try: while True: _UpperCAmelCase = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
364
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: List[str] , *, _SCREAMING_SNAKE_CASE: int = 4 , _SCREAMING_SNAKE_CASE: int = 768 , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: str , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(_SCREAMING_SNAKE_CASE ) ) # parameters for additional clip time embeddings UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # parameters for encoder hidden states UpperCamelCase_ = clip_extra_context_tokens UpperCamelCase_ = nn.Linear( _SCREAMING_SNAKE_CASE , self.clip_extra_context_tokens * cross_attention_dim ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.LayerNorm(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , *, _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> str: """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings UpperCamelCase_ = image_embeddings.shape[0] UpperCamelCase_ = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) UpperCamelCase_ = classifier_free_guidance_embeddings.expand( _SCREAMING_SNAKE_CASE , -1 ) UpperCamelCase_ = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] UpperCamelCase_ = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... UpperCamelCase_ = self.embedding_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.clip_image_embeddings_project_to_time_embeddings(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" UpperCamelCase_ = self.clip_extra_context_tokens_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = clip_extra_context_tokens.reshape(_SCREAMING_SNAKE_CASE , -1 , self.clip_extra_context_tokens ) UpperCamelCase_ = clip_extra_context_tokens.permute(0 , 2 , 1 ) UpperCamelCase_ = self.encoder_hidden_states_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.text_encoder_hidden_states_norm(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
328
0
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name _UpperCAmelCase = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to("cuda")\n\n >>> prompt = "A red cartoon frog, 4k"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16\n ... )\n >>> pipe.to("cuda")\n\n >>> init_image = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/frog.png"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save("red_frog.png")\n ```\n' def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=8 ) -> Optional[Any]: UpperCamelCase_ = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 UpperCamelCase_ = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_=512 , UpperCamelCase_=512 ) -> Any: UpperCamelCase_ = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) UpperCamelCase_ = np.array(pil_image.convert("RGB" ) ) UpperCamelCase_ = arr.astype(np.floataa ) / 127.5 - 1 UpperCamelCase_ = np.transpose(UpperCamelCase_ , [2, 0, 1] ) UpperCamelCase_ = torch.from_numpy(UpperCamelCase_ ).unsqueeze(0 ) return image class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: List[str] , _SCREAMING_SNAKE_CASE: UNetaDConditionModel , _SCREAMING_SNAKE_CASE: DDPMScheduler , _SCREAMING_SNAKE_CASE: VQModel , ) -> Tuple: """simple docstring""" super().__init__() self.register_modules( unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , movq=_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowercase ( self: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Optional[Any] ) -> List[Any]: """simple docstring""" UpperCamelCase_ = min(int(num_inference_steps * strength ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Union[str, Any]=None ) -> Tuple: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = image.to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = batch_size * num_images_per_prompt if image.shape[1] == 4: UpperCamelCase_ = image else: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_SCREAMING_SNAKE_CASE ) ] UpperCamelCase_ = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) else: UpperCamelCase_ = self.movq.encode(_SCREAMING_SNAKE_CASE ).latent_dist.sample(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.movq.config.scaling_factor * init_latents UpperCamelCase_ = torch.cat([init_latents] , dim=0 ) UpperCamelCase_ = init_latents.shape UpperCamelCase_ = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) # get latents UpperCamelCase_ = self.scheduler.add_noise(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = init_latents return latents def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Any=0 ) -> List[Any]: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCamelCase_ = torch.device(f'''cuda:{gpu_id}''' ) UpperCamelCase_ = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int]=0 ) -> List[Any]: """simple docstring""" if is_accelerate_available() and is_accelerate_version(">=" , "0.17.0.dev0" ): from accelerate import cpu_offload_with_hook else: raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." ) UpperCamelCase_ = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=_SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) UpperCamelCase_ = None for cpu_offloaded_model in [self.unet, self.movq]: UpperCamelCase_ , UpperCamelCase_ = cpu_offload_with_hook(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , prev_module_hook=_SCREAMING_SNAKE_CASE ) # We'll offload the last model manually. UpperCamelCase_ = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowercase ( self: Any ) -> Dict: """simple docstring""" if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(_SCREAMING_SNAKE_CASE , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_SCREAMING_SNAKE_CASE ) def __call__( self: Optional[int] , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, List[torch.FloatTensor]] , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, List[torch.FloatTensor]] , _SCREAMING_SNAKE_CASE: int = 512 , _SCREAMING_SNAKE_CASE: int = 512 , _SCREAMING_SNAKE_CASE: int = 100 , _SCREAMING_SNAKE_CASE: float = 4.0 , _SCREAMING_SNAKE_CASE: float = 0.3 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Tuple: """simple docstring""" UpperCamelCase_ = self._execution_device UpperCamelCase_ = guidance_scale > 1.0 if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) UpperCamelCase_ = image_embeds.shape[0] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: UpperCamelCase_ = image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) UpperCamelCase_ = negative_image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) UpperCamelCase_ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_SCREAMING_SNAKE_CASE ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [image] if not all(isinstance(_SCREAMING_SNAKE_CASE , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( f'''Input is in incorrect format: {[type(_SCREAMING_SNAKE_CASE ) for i in image]}. Currently, we only support PIL image and pytorch tensor''' ) UpperCamelCase_ = torch.cat([prepare_image(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for i in image] , dim=0 ) UpperCamelCase_ = image.to(dtype=image_embeds.dtype , device=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.movq.encode(_SCREAMING_SNAKE_CASE )["latents"] UpperCamelCase_ = latents.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = self.get_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = timesteps[:1].repeat(batch_size * num_images_per_prompt ) UpperCamelCase_ , UpperCamelCase_ = downscale_height_and_width(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.movq_scale_factor ) UpperCamelCase_ = self.prepare_latents( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , image_embeds.dtype , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for i, t in enumerate(self.progress_bar(_SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase_ = {"image_embeds": image_embeds} UpperCamelCase_ = self.unet( sample=_SCREAMING_SNAKE_CASE , timestep=_SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , added_cond_kwargs=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , )[0] if do_classifier_free_guidance: UpperCamelCase_ , UpperCamelCase_ = noise_pred.split(latents.shape[1] , dim=1 ) UpperCamelCase_ , UpperCamelCase_ = noise_pred.chunk(2 ) UpperCamelCase_ , UpperCamelCase_ = variance_pred.chunk(2 ) UpperCamelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) UpperCamelCase_ = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , "variance_type" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): UpperCamelCase_ , UpperCamelCase_ = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase_ = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , )[0] # post-processing UpperCamelCase_ = self.movq.decode(_SCREAMING_SNAKE_CASE , force_not_quantize=_SCREAMING_SNAKE_CASE )["sample"] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: UpperCamelCase_ = image * 0.5 + 0.5 UpperCamelCase_ = image.clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
365
from functools import lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> set: UpperCamelCase_ = 2 UpperCamelCase_ = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(UpperCamelCase_ ) if n > 1: factors.add(UpperCamelCase_ ) return factors @lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: return len(unique_prime_factors(UpperCamelCase_ ) ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> bool: return len(set(UpperCamelCase_ ) ) in (0, 1) def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = 2 while True: # Increment each value of a generated range UpperCamelCase_ = [base + i for i in range(UpperCamelCase_ )] # Run elements through out unique_prime_factors function # Append our target number to the end. UpperCamelCase_ = [upf_len(UpperCamelCase_ ) for x in group] checker.append(UpperCamelCase_ ) # If all numbers in the list are equal, return the group variable. if equality(UpperCamelCase_ ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase_ ( UpperCamelCase_ = 4 ) -> int: UpperCamelCase_ = run(UpperCamelCase_ ) return results[0] if len(UpperCamelCase_ ) else None if __name__ == "__main__": print(solution())
328
0
from __future__ import annotations import math def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> int: if depth < 0: raise ValueError("Depth cannot be less than 0" ) if len(UpperCamelCase_ ) == 0: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , minimax(depth + 1 , node_index * 2 + 1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , ) return min( minimax(depth + 1 , node_index * 2 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , minimax(depth + 1 , node_index * 2 + 1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , ) def lowerCAmelCase_ ( ) -> None: UpperCamelCase_ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase_ = math.log(len(UpperCamelCase_ ) , 2 ) print("Optimal value : " , end="" ) print(minimax(0 , 0 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
366
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = len(UpperCamelCase_ ) UpperCamelCase_ = len(matrix[0] ) UpperCamelCase_ = min(UpperCamelCase_ , UpperCamelCase_ ) for row in range(UpperCamelCase_ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , UpperCamelCase_ ): UpperCamelCase_ = matrix[col][row] / matrix[row][row] for i in range(UpperCamelCase_ , UpperCamelCase_ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows UpperCamelCase_ = True for i in range(row + 1 , UpperCamelCase_ ): if matrix[i][row] != 0: UpperCamelCase_ , UpperCamelCase_ = matrix[i], matrix[row] UpperCamelCase_ = False break if reduce: rank -= 1 for i in range(UpperCamelCase_ ): UpperCamelCase_ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
328
0
from functools import lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> set: UpperCamelCase_ = 2 UpperCamelCase_ = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(UpperCamelCase_ ) if n > 1: factors.add(UpperCamelCase_ ) return factors @lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: return len(unique_prime_factors(UpperCamelCase_ ) ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> bool: return len(set(UpperCamelCase_ ) ) in (0, 1) def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = 2 while True: # Increment each value of a generated range UpperCamelCase_ = [base + i for i in range(UpperCamelCase_ )] # Run elements through out unique_prime_factors function # Append our target number to the end. UpperCamelCase_ = [upf_len(UpperCamelCase_ ) for x in group] checker.append(UpperCamelCase_ ) # If all numbers in the list are equal, return the group variable. if equality(UpperCamelCase_ ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase_ ( UpperCamelCase_ = 4 ) -> int: UpperCamelCase_ = run(UpperCamelCase_ ) return results[0] if len(UpperCamelCase_ ) else None if __name__ == "__main__": print(solution())
367
import math def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(UpperCamelCase_ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. _UpperCAmelCase = 'Enter the base and the power separated by a comma: ' _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) # We find the log of each number, using the function res(), which takes two # arguments. _UpperCAmelCase = res(xa, ya) _UpperCAmelCase = res(xa, ya) # We check for the largest number if resa > resa: print('Largest number is', xa, '^', ya) elif resa > resa: print('Largest number is', xa, '^', ya) else: print('Both are equal')
328
0
def lowerCAmelCase_ ( UpperCamelCase_ = 1000 ) -> int: UpperCamelCase_ = 3 UpperCamelCase_ = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f'''{solution() = }''')
368
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor _UpperCAmelCase = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> List[Any]: if isinstance(UpperCamelCase_ , torch.Tensor ): return image elif isinstance(UpperCamelCase_ , PIL.Image.Image ): UpperCamelCase_ = [image] UpperCamelCase_ = [trans(img.convert("RGB" ) ) for img in image] UpperCamelCase_ = torch.stack(UpperCamelCase_ ) return image class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase_ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[Any]: """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> int: """simple docstring""" UpperCamelCase_ = min(int(num_inference_steps * strength ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[int]=None ) -> List[Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = image.to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase_ = init_latents.shape UpperCamelCase_ = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) # get latents print("add noise to latents at timestep" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.scheduler.add_noise(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = init_latents return latents @torch.no_grad() def __call__( self: Dict , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, PIL.Image.Image] = None , _SCREAMING_SNAKE_CASE: float = 0.8 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: int = 50 , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" self.check_inputs(_SCREAMING_SNAKE_CASE ) # 2. Preprocess image UpperCamelCase_ = preprocess(_SCREAMING_SNAKE_CASE ) # 3. set timesteps self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=self.device ) UpperCamelCase_ , UpperCamelCase_ = self.get_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.device ) UpperCamelCase_ = timesteps[:1].repeat(_SCREAMING_SNAKE_CASE ) # 4. Prepare latent variables UpperCamelCase_ = self.prepare_latents(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.unet.dtype , self.device , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = latents # 5. Denoising loop for t in self.progress_bar(_SCREAMING_SNAKE_CASE ): # 1. predict noise model_output UpperCamelCase_ = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 UpperCamelCase_ = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , use_clipped_model_output=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample UpperCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
328
0
"""simple docstring""" import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _UpperCAmelCase = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } _UpperCAmelCase = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Union[str, Any] = '''mask2former''' _UpperCamelCase : str = ['''swin'''] _UpperCamelCase : List[Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self: str , _SCREAMING_SNAKE_CASE: Optional[Dict] = None , _SCREAMING_SNAKE_CASE: int = 256 , _SCREAMING_SNAKE_CASE: int = 256 , _SCREAMING_SNAKE_CASE: int = 256 , _SCREAMING_SNAKE_CASE: int = 1024 , _SCREAMING_SNAKE_CASE: str = "relu" , _SCREAMING_SNAKE_CASE: int = 6 , _SCREAMING_SNAKE_CASE: int = 10 , _SCREAMING_SNAKE_CASE: int = 8 , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: int = 4 , _SCREAMING_SNAKE_CASE: int = 255 , _SCREAMING_SNAKE_CASE: int = 100 , _SCREAMING_SNAKE_CASE: float = 0.1 , _SCREAMING_SNAKE_CASE: float = 2.0 , _SCREAMING_SNAKE_CASE: float = 5.0 , _SCREAMING_SNAKE_CASE: float = 5.0 , _SCREAMING_SNAKE_CASE: int = 12544 , _SCREAMING_SNAKE_CASE: float = 3.0 , _SCREAMING_SNAKE_CASE: float = 0.75 , _SCREAMING_SNAKE_CASE: float = 0.02 , _SCREAMING_SNAKE_CASE: float = 1.0 , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: List[int] = [4, 8, 16, 32] , _SCREAMING_SNAKE_CASE: bool = None , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> Dict: """simple docstring""" if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `Swin` backbone." ) UpperCamelCase_ = CONFIG_MAPPING["swin"]( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_SCREAMING_SNAKE_CASE , out_features=["stage1", "stage2", "stage3", "stage4"] , ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = backbone_config.pop("model_type" ) UpperCamelCase_ = CONFIG_MAPPING[backbone_model_type] UpperCamelCase_ = config_class.from_dict(_SCREAMING_SNAKE_CASE ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ''' f'''Supported model types: {",".join(self.backbones_supported )}''' ) UpperCamelCase_ = backbone_config UpperCamelCase_ = feature_size UpperCamelCase_ = mask_feature_size UpperCamelCase_ = hidden_dim UpperCamelCase_ = encoder_feedforward_dim UpperCamelCase_ = activation_function UpperCamelCase_ = encoder_layers UpperCamelCase_ = decoder_layers UpperCamelCase_ = num_attention_heads UpperCamelCase_ = dropout UpperCamelCase_ = dim_feedforward UpperCamelCase_ = pre_norm UpperCamelCase_ = enforce_input_projection UpperCamelCase_ = common_stride UpperCamelCase_ = ignore_value UpperCamelCase_ = num_queries UpperCamelCase_ = no_object_weight UpperCamelCase_ = class_weight UpperCamelCase_ = mask_weight UpperCamelCase_ = dice_weight UpperCamelCase_ = train_num_points UpperCamelCase_ = oversample_ratio UpperCamelCase_ = importance_sample_ratio UpperCamelCase_ = init_std UpperCamelCase_ = init_xavier_std UpperCamelCase_ = use_auxiliary_loss UpperCamelCase_ = feature_strides UpperCamelCase_ = output_auxiliary_logits UpperCamelCase_ = decoder_layers super().__init__(**_SCREAMING_SNAKE_CASE ) @classmethod def lowercase ( cls: Union[str, Any] , _SCREAMING_SNAKE_CASE: PretrainedConfig , **_SCREAMING_SNAKE_CASE: Optional[Any] ) -> Optional[Any]: """simple docstring""" return cls( backbone_config=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) def lowercase ( self: List[Any] ) -> Dict[str, any]: """simple docstring""" UpperCamelCase_ = copy.deepcopy(self.__dict__ ) UpperCamelCase_ = self.backbone_config.to_dict() UpperCamelCase_ = self.__class__.model_type return output
369
import re from filelock import FileLock try: import nltk _UpperCAmelCase = True except (ImportError, ModuleNotFoundError): _UpperCAmelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCAmelCase_ ( UpperCamelCase_ ) -> str: re.sub("<n>" , "" , UpperCamelCase_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase_ ) )
328
0
def lowerCAmelCase_ ( UpperCamelCase_ = "The quick brown fox jumps over the lazy dog" , ): UpperCamelCase_ = set() # Replace all the whitespace in our sentence UpperCamelCase_ = input_str.replace(" " , "" ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(UpperCamelCase_ ) == 26 def lowerCAmelCase_ ( UpperCamelCase_ = "The quick brown fox jumps over the lazy dog" , ): UpperCamelCase_ = [False] * 26 for char in input_str: if char.islower(): UpperCamelCase_ = True elif char.isupper(): UpperCamelCase_ = True return all(UpperCamelCase_ ) def lowerCAmelCase_ ( UpperCamelCase_ = "The quick brown fox jumps over the lazy dog" , ): return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowerCAmelCase_ ( ): from timeit import timeit UpperCamelCase_ = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=UpperCamelCase_ ) ) print(timeit("is_pangram_faster()" , setup=UpperCamelCase_ ) ) print(timeit("is_pangram_fastest()" , setup=UpperCamelCase_ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
370
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = DiTPipeline _UpperCamelCase : Any = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS _UpperCamelCase : Dict = PipelineTesterMixin.required_optional_params - { '''latents''', '''num_images_per_prompt''', '''callback''', '''callback_steps''', } _UpperCamelCase : Optional[int] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS _UpperCamelCase : Dict = False def lowercase ( self: str ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn="gelu-approximate" , num_embeds_ada_norm=1000 , norm_type="ada_norm_zero" , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = AutoencoderKL() UpperCamelCase_ = DDIMScheduler() UpperCamelCase_ = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler} return components def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: List[str]=0 ) -> Dict: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "class_labels": [1], "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def lowercase ( self: Any ) -> List[str]: """simple docstring""" UpperCamelCase_ = "cpu" UpperCamelCase_ = self.get_dummy_components() UpperCamelCase_ = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(**_SCREAMING_SNAKE_CASE ).images UpperCamelCase_ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) UpperCamelCase_ = np.array([0.29_46, 0.66_01, 0.43_29, 0.32_96, 0.41_44, 0.53_19, 0.72_73, 0.50_13, 0.44_57] ) UpperCamelCase_ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1e-3 ) def lowercase ( self: Optional[int] ) -> Any: """simple docstring""" self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Optional[Any] ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: Optional[int] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self: Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256" ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella", "white shark", "white wolf"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( f'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-2 def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512" ) UpperCamelCase_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" f'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-1
328
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''image_processor''', '''tokenizer'''] _UpperCamelCase : List[str] = '''CLIPImageProcessor''' _UpperCamelCase : Union[str, Any] = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self: Optional[int] , _SCREAMING_SNAKE_CASE: Dict=None , _SCREAMING_SNAKE_CASE: Dict=None , **_SCREAMING_SNAKE_CASE: int ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , _SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = kwargs.pop("feature_extractor" ) UpperCamelCase_ = 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__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __call__( self: List[str] , _SCREAMING_SNAKE_CASE: Dict=None , _SCREAMING_SNAKE_CASE: Any=None , _SCREAMING_SNAKE_CASE: List[str]=None , **_SCREAMING_SNAKE_CASE: Tuple ) -> Union[str, Any]: """simple docstring""" if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: UpperCamelCase_ = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if images is not None: UpperCamelCase_ = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None and images is not None: UpperCamelCase_ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_SCREAMING_SNAKE_CASE ) , tensor_type=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[Any] , *_SCREAMING_SNAKE_CASE: Union[str, Any] , **_SCREAMING_SNAKE_CASE: Dict ) -> Any: """simple docstring""" return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] , *_SCREAMING_SNAKE_CASE: List[Any] , **_SCREAMING_SNAKE_CASE: Optional[Any] ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def lowercase ( self: Tuple ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = self.tokenizer.model_input_names UpperCamelCase_ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowercase ( self: int ) -> Optional[int]: """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def lowercase ( self: Any ) -> Tuple: """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , _SCREAMING_SNAKE_CASE , ) return self.image_processor
371
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _UpperCamelCase : def __init__( self: str ) -> Any: """simple docstring""" UpperCamelCase_ = "" UpperCamelCase_ = "" UpperCamelCase_ = [] UpperCamelCase_ = 0 UpperCamelCase_ = 256 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" UpperCamelCase_ = cva.imread(_SCREAMING_SNAKE_CASE , 0 ) UpperCamelCase_ = copy.deepcopy(self.img ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = plt.hist(self.img.ravel() , 256 , [0, 256] , label="x" ) UpperCamelCase_ = np.sum(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): UpperCamelCase_ = x[i] / self.k self.sk += prk UpperCamelCase_ = (self.L - 1) * self.sk if self.rem != 0: UpperCamelCase_ = int(last % last ) UpperCamelCase_ = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = int(np.ma.count(self.img ) / self.img[1].size ) UpperCamelCase_ = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): UpperCamelCase_ = self.img[j][i] if num != self.last_list[num]: UpperCamelCase_ = self.last_list[num] cva.imwrite("output_data/output.jpg" , self.img ) def lowercase ( self: Any ) -> Optional[Any]: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def lowercase ( self: Tuple ) -> Union[str, Any]: """simple docstring""" cva.imshow("Output-Image" , self.img ) cva.imshow("Input-Image" , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": _UpperCAmelCase = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') _UpperCAmelCase = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
328
0
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json', # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = '''blenderbot-small''' _UpperCamelCase : Union[str, Any] = ['''past_key_values'''] _UpperCamelCase : Dict = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self: int , _SCREAMING_SNAKE_CASE: Any=50265 , _SCREAMING_SNAKE_CASE: int=512 , _SCREAMING_SNAKE_CASE: Optional[int]=8 , _SCREAMING_SNAKE_CASE: Tuple=2048 , _SCREAMING_SNAKE_CASE: Any=16 , _SCREAMING_SNAKE_CASE: Any=8 , _SCREAMING_SNAKE_CASE: List[Any]=2048 , _SCREAMING_SNAKE_CASE: str=16 , _SCREAMING_SNAKE_CASE: Any=0.0 , _SCREAMING_SNAKE_CASE: Any=0.0 , _SCREAMING_SNAKE_CASE: List[str]=True , _SCREAMING_SNAKE_CASE: int=True , _SCREAMING_SNAKE_CASE: int="gelu" , _SCREAMING_SNAKE_CASE: Tuple=512 , _SCREAMING_SNAKE_CASE: int=0.1 , _SCREAMING_SNAKE_CASE: Dict=0.0 , _SCREAMING_SNAKE_CASE: Dict=0.0 , _SCREAMING_SNAKE_CASE: Dict=0.02 , _SCREAMING_SNAKE_CASE: str=1 , _SCREAMING_SNAKE_CASE: Any=False , _SCREAMING_SNAKE_CASE: Optional[int]=0 , _SCREAMING_SNAKE_CASE: int=1 , _SCREAMING_SNAKE_CASE: Any=2 , _SCREAMING_SNAKE_CASE: Optional[Any]=2 , **_SCREAMING_SNAKE_CASE: Union[str, Any] , ) -> int: """simple docstring""" UpperCamelCase_ = vocab_size UpperCamelCase_ = max_position_embeddings UpperCamelCase_ = d_model UpperCamelCase_ = encoder_ffn_dim UpperCamelCase_ = encoder_layers UpperCamelCase_ = encoder_attention_heads UpperCamelCase_ = decoder_ffn_dim UpperCamelCase_ = decoder_layers UpperCamelCase_ = decoder_attention_heads UpperCamelCase_ = dropout UpperCamelCase_ = attention_dropout UpperCamelCase_ = activation_dropout UpperCamelCase_ = activation_function UpperCamelCase_ = init_std UpperCamelCase_ = encoder_layerdrop UpperCamelCase_ = decoder_layerdrop UpperCamelCase_ = use_cache UpperCamelCase_ = encoder_layers UpperCamelCase_ = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , is_encoder_decoder=_SCREAMING_SNAKE_CASE , decoder_start_token_id=_SCREAMING_SNAKE_CASE , forced_eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) class _UpperCamelCase ( lowerCAmelCase_ ): @property def lowercase ( self: Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase_ = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase_ = {0: "batch"} UpperCamelCase_ = {0: "batch", 1: "past_decoder_sequence + sequence"} else: UpperCamelCase_ = {0: "batch", 1: "decoder_sequence"} UpperCamelCase_ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(_SCREAMING_SNAKE_CASE , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCamelCase_ = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase_ , UpperCamelCase_ = self.num_layers for i in range(_SCREAMING_SNAKE_CASE ): UpperCamelCase_ = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase_ = {0: "batch", 2: "past_sequence + sequence"} else: UpperCamelCase_ = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def lowercase ( self: str ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase_ = super().outputs else: UpperCamelCase_ = super(_SCREAMING_SNAKE_CASE , self ).outputs if self.use_past: UpperCamelCase_ , UpperCamelCase_ = self.num_layers for i in range(_SCREAMING_SNAKE_CASE ): UpperCamelCase_ = {0: "batch", 2: "past_sequence + sequence"} UpperCamelCase_ = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: PreTrainedTokenizer , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: Optional[TensorType] = None , ) -> Mapping[str, Any]: """simple docstring""" UpperCamelCase_ = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Generate decoder inputs UpperCamelCase_ = seq_length if not self.use_past else 1 UpperCamelCase_ = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = {f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()} UpperCamelCase_ = dict(**_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase_ , UpperCamelCase_ = common_inputs["input_ids"].shape UpperCamelCase_ = common_inputs["decoder_input_ids"].shape[1] UpperCamelCase_ , UpperCamelCase_ = self.num_attention_heads UpperCamelCase_ = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase_ = decoder_seq_length + 3 UpperCamelCase_ = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCamelCase_ = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )] , dim=1 ) UpperCamelCase_ = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCamelCase_ , UpperCamelCase_ = self.num_layers UpperCamelCase_ = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) - min_num_layers UpperCamelCase_ = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(_SCREAMING_SNAKE_CASE ): common_inputs["past_key_values"].append( ( torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), ) ) # TODO: test this. UpperCamelCase_ = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): common_inputs["past_key_values"].append((torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE )) ) return common_inputs def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: PreTrainedTokenizer , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: Optional[TensorType] = None , ) -> Mapping[str, Any]: """simple docstring""" UpperCamelCase_ = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCamelCase_ , UpperCamelCase_ = common_inputs["input_ids"].shape # Not using the same length for past_key_values UpperCamelCase_ = seqlen + 2 UpperCamelCase_ , UpperCamelCase_ = self.num_layers UpperCamelCase_ , UpperCamelCase_ = self.num_attention_heads UpperCamelCase_ = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase_ = common_inputs["attention_mask"].dtype UpperCamelCase_ = torch.cat( [common_inputs["attention_mask"], torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE )] , dim=1 ) UpperCamelCase_ = [ (torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE )) for _ in range(_SCREAMING_SNAKE_CASE ) ] return common_inputs def lowercase ( self: int , _SCREAMING_SNAKE_CASE: PreTrainedTokenizer , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: Optional[TensorType] = None , ) -> Mapping[str, Any]: """simple docstring""" UpperCamelCase_ = compute_effective_axis_dimension( _SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase_ = tokenizer.num_special_tokens_to_add(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = compute_effective_axis_dimension( _SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_SCREAMING_SNAKE_CASE ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase_ = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCamelCase_ = dict(tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) ) return common_inputs def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: PreTrainedTokenizer , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: Optional[TensorType] = None , ) -> Mapping[str, Any]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase_ = self._generate_dummy_inputs_for_default_and_seqaseq_lm( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) elif self.task == "causal-lm": UpperCamelCase_ = self._generate_dummy_inputs_for_causal_lm( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) return common_inputs def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: int ) -> Any: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase_ = super()._flatten_past_key_values_(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = super(_SCREAMING_SNAKE_CASE , self )._flatten_past_key_values_( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
350
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _UpperCAmelCase = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' _UpperCAmelCase = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' _UpperCAmelCase = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: return float((preds == labels).mean() ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_="binary" ) -> Tuple: UpperCamelCase_ = simple_accuracy(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average=UpperCamelCase_ ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: UpperCamelCase_ = {} for id_pred, label in zip(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = F'''{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}''' UpperCamelCase_ = id_pred["prediction"] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase_ = [(pred, label)] UpperCamelCase_ , UpperCamelCase_ = [], [] for question, preds_labels in question_map.items(): UpperCamelCase_ , UpperCamelCase_ = zip(*UpperCamelCase_ ) UpperCamelCase_ = fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average="macro" ) fas.append(UpperCamelCase_ ) UpperCamelCase_ = int(sum(pred == label for pred, label in preds_labels ) == len(UpperCamelCase_ ) ) ems.append(UpperCamelCase_ ) UpperCamelCase_ = float(sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) ) UpperCamelCase_ = sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=[id_pred["prediction"] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCamelCase ( datasets.Metric ): def lowercase ( self: Optional[int] ) -> Optional[int]: """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="numpy" if not self.config_name == "record" and not self.config_name == "multirc" else None , ) def lowercase ( self: List[Any] ) -> int: """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "prediction_text": datasets.Value("string" ), }, "references": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "answers": datasets.Sequence(datasets.Value("string" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("int64" ), "paragraph": datasets.Value("int64" ), "question": datasets.Value("int64" ), }, "prediction": datasets.Value("int64" ), }, "references": datasets.Value("int64" ), } else: return { "predictions": datasets.Value("int64" ), "references": datasets.Value("int64" ), } def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> Dict: """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="macro" ) elif self.config_name == "record": UpperCamelCase_ = [ { "qas": [ {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]} for ref in references ] } ] UpperCamelCase_ = {pred["idx"]["query"]: pred["prediction_text"] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" )
328
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : torch.FloatTensor class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: int , _SCREAMING_SNAKE_CASE: int = 65536 , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: int = 2 , _SCREAMING_SNAKE_CASE: int = 2 , _SCREAMING_SNAKE_CASE: int = 0 , _SCREAMING_SNAKE_CASE: str = "fourier" , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , _SCREAMING_SNAKE_CASE: Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , _SCREAMING_SNAKE_CASE: Tuple[str] = "UNetMidBlock1D" , _SCREAMING_SNAKE_CASE: str = None , _SCREAMING_SNAKE_CASE: Tuple[int] = (32, 32, 64) , _SCREAMING_SNAKE_CASE: str = None , _SCREAMING_SNAKE_CASE: int = 8 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: bool = False , ) -> Optional[int]: """simple docstring""" super().__init__() UpperCamelCase_ = sample_size # time if time_embedding_type == "fourier": UpperCamelCase_ = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=_SCREAMING_SNAKE_CASE , log=_SCREAMING_SNAKE_CASE , flip_sin_to_cos=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = 2 * block_out_channels[0] elif time_embedding_type == "positional": UpperCamelCase_ = Timesteps( block_out_channels[0] , flip_sin_to_cos=_SCREAMING_SNAKE_CASE , downscale_freq_shift=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = block_out_channels[0] if use_timestep_embedding: UpperCamelCase_ = block_out_channels[0] * 4 UpperCamelCase_ = TimestepEmbedding( in_channels=_SCREAMING_SNAKE_CASE , time_embed_dim=_SCREAMING_SNAKE_CASE , act_fn=_SCREAMING_SNAKE_CASE , out_dim=block_out_channels[0] , ) UpperCamelCase_ = nn.ModuleList([] ) UpperCamelCase_ = None UpperCamelCase_ = nn.ModuleList([] ) UpperCamelCase_ = None # down UpperCamelCase_ = in_channels for i, down_block_type in enumerate(_SCREAMING_SNAKE_CASE ): UpperCamelCase_ = output_channel UpperCamelCase_ = block_out_channels[i] if i == 0: input_channel += extra_in_channels UpperCamelCase_ = i == len(_SCREAMING_SNAKE_CASE ) - 1 UpperCamelCase_ = get_down_block( _SCREAMING_SNAKE_CASE , num_layers=_SCREAMING_SNAKE_CASE , in_channels=_SCREAMING_SNAKE_CASE , out_channels=_SCREAMING_SNAKE_CASE , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(_SCREAMING_SNAKE_CASE ) # mid UpperCamelCase_ = get_mid_block( _SCREAMING_SNAKE_CASE , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=_SCREAMING_SNAKE_CASE , add_downsample=_SCREAMING_SNAKE_CASE , ) # up UpperCamelCase_ = list(reversed(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = reversed_block_out_channels[0] if out_block_type is None: UpperCamelCase_ = out_channels else: UpperCamelCase_ = block_out_channels[0] for i, up_block_type in enumerate(_SCREAMING_SNAKE_CASE ): UpperCamelCase_ = output_channel UpperCamelCase_ = ( reversed_block_out_channels[i + 1] if i < len(_SCREAMING_SNAKE_CASE ) - 1 else final_upsample_channels ) UpperCamelCase_ = i == len(_SCREAMING_SNAKE_CASE ) - 1 UpperCamelCase_ = get_up_block( _SCREAMING_SNAKE_CASE , num_layers=_SCREAMING_SNAKE_CASE , in_channels=_SCREAMING_SNAKE_CASE , out_channels=_SCREAMING_SNAKE_CASE , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = output_channel # out UpperCamelCase_ = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) UpperCamelCase_ = get_out_block( out_block_type=_SCREAMING_SNAKE_CASE , num_groups_out=_SCREAMING_SNAKE_CASE , embed_dim=block_out_channels[0] , out_channels=_SCREAMING_SNAKE_CASE , act_fn=_SCREAMING_SNAKE_CASE , fc_dim=block_out_channels[-1] // 4 , ) def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: torch.FloatTensor , _SCREAMING_SNAKE_CASE: Union[torch.Tensor, float, int] , _SCREAMING_SNAKE_CASE: bool = True , ) -> Union[UNetaDOutput, Tuple]: """simple docstring""" UpperCamelCase_ = timestep if not torch.is_tensor(_SCREAMING_SNAKE_CASE ): UpperCamelCase_ = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(_SCREAMING_SNAKE_CASE ) and len(timesteps.shape ) == 0: UpperCamelCase_ = timesteps[None].to(sample.device ) UpperCamelCase_ = self.time_proj(_SCREAMING_SNAKE_CASE ) if self.config.use_timestep_embedding: UpperCamelCase_ = self.time_mlp(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = timestep_embed[..., None] UpperCamelCase_ = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) UpperCamelCase_ = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down UpperCamelCase_ = () for downsample_block in self.down_blocks: UpperCamelCase_ , UpperCamelCase_ = downsample_block(hidden_states=_SCREAMING_SNAKE_CASE , temb=_SCREAMING_SNAKE_CASE ) down_block_res_samples += res_samples # 3. mid if self.mid_block: UpperCamelCase_ = self.mid_block(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): UpperCamelCase_ = down_block_res_samples[-1:] UpperCamelCase_ = down_block_res_samples[:-1] UpperCamelCase_ = upsample_block(_SCREAMING_SNAKE_CASE , res_hidden_states_tuple=_SCREAMING_SNAKE_CASE , temb=_SCREAMING_SNAKE_CASE ) # 5. post-process if self.out_block: UpperCamelCase_ = self.out_block(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not return_dict: return (sample,) return UNetaDOutput(sample=_SCREAMING_SNAKE_CASE )
351
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = '''mgp-str''' def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[int]=[32, 128] , _SCREAMING_SNAKE_CASE: Tuple=4 , _SCREAMING_SNAKE_CASE: Optional[Any]=3 , _SCREAMING_SNAKE_CASE: Optional[int]=27 , _SCREAMING_SNAKE_CASE: Tuple=38 , _SCREAMING_SNAKE_CASE: Tuple=50257 , _SCREAMING_SNAKE_CASE: List[Any]=30522 , _SCREAMING_SNAKE_CASE: Optional[Any]=768 , _SCREAMING_SNAKE_CASE: Dict=12 , _SCREAMING_SNAKE_CASE: List[str]=12 , _SCREAMING_SNAKE_CASE: Dict=4.0 , _SCREAMING_SNAKE_CASE: int=True , _SCREAMING_SNAKE_CASE: Tuple=False , _SCREAMING_SNAKE_CASE: Tuple=1e-5 , _SCREAMING_SNAKE_CASE: Optional[Any]=0.0 , _SCREAMING_SNAKE_CASE: Tuple=0.0 , _SCREAMING_SNAKE_CASE: List[Any]=0.0 , _SCREAMING_SNAKE_CASE: List[str]=False , _SCREAMING_SNAKE_CASE: int=0.02 , **_SCREAMING_SNAKE_CASE: Any , ) -> str: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = image_size UpperCamelCase_ = patch_size UpperCamelCase_ = num_channels UpperCamelCase_ = max_token_length UpperCamelCase_ = num_character_labels UpperCamelCase_ = num_bpe_labels UpperCamelCase_ = num_wordpiece_labels UpperCamelCase_ = hidden_size UpperCamelCase_ = num_hidden_layers UpperCamelCase_ = num_attention_heads UpperCamelCase_ = mlp_ratio UpperCamelCase_ = distilled UpperCamelCase_ = layer_norm_eps UpperCamelCase_ = drop_rate UpperCamelCase_ = qkv_bias UpperCamelCase_ = attn_drop_rate UpperCamelCase_ = drop_path_rate UpperCamelCase_ = output_aa_attentions UpperCamelCase_ = initializer_range
328
0
"""simple docstring""" from __future__ import annotations _UpperCAmelCase = '#' class _UpperCamelCase : def __init__( self: Dict ) -> None: """simple docstring""" UpperCamelCase_ = {} def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: str ) -> None: """simple docstring""" UpperCamelCase_ = self._trie for char in text: if char not in trie: UpperCamelCase_ = {} UpperCamelCase_ = trie[char] UpperCamelCase_ = True def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: str ) -> tuple | list: """simple docstring""" UpperCamelCase_ = self._trie for char in prefix: if char in trie: UpperCamelCase_ = trie[char] else: return [] return self._elements(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: dict ) -> tuple: """simple docstring""" UpperCamelCase_ = [] for c, v in d.items(): UpperCamelCase_ = [" "] if c == END else [(c + s) for s in self._elements(_SCREAMING_SNAKE_CASE )] result.extend(_SCREAMING_SNAKE_CASE ) return tuple(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = Trie() _UpperCAmelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def lowerCAmelCase_ ( UpperCamelCase_ ) -> tuple: UpperCamelCase_ = trie.find_word(UpperCamelCase_ ) return tuple(string + word for word in suffixes ) def lowerCAmelCase_ ( ) -> None: print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
352
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _UpperCAmelCase = logging.getLogger(__name__) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether tp freeze the encoder.'''} ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether to freeze the embeddings.'''} ) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''} ) _UpperCamelCase : Optional[str] = field( default='''summarization''' , metadata={'''help''': '''Task name, summarization (or summarization_{dataset} for pegasus) or translation'''} , ) _UpperCamelCase : Optional[int] = 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 : Optional[int] = field( default=1_2_8 , metadata={ '''help''': ( '''The maximum total sequence length for target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for validation target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded. ''' '''This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ''' '''during ``evaluate`` and ``predict``.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for test target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# training examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# validation examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# test examples. -1 means use all.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Source language id for translation.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Target language id for translation.'''} ) _UpperCamelCase : Optional[int] = field(default=lowerCAmelCase_ , metadata={'''help''': '''# num_beams to use for evaluation.'''} ) _UpperCamelCase : bool = field( default=lowerCAmelCase_ , metadata={'''help''': '''If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'''} , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[int]: logger.info(F'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(F''' {key} = {metrics[key]}''' ) save_json(UpperCamelCase_ , os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) ) def lowerCAmelCase_ ( ) -> Optional[int]: # 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. UpperCamelCase_ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_args_into_dataclasses() check_output_dir(UpperCamelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , UpperCamelCase_ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): assert hasattr(UpperCamelCase_ , UpperCamelCase_ ), F'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(UpperCamelCase_ , UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) UpperCamelCase_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=UpperCamelCase_ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(UpperCamelCase_ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: UpperCamelCase_ = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(UpperCamelCase_ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = tokenizer.lang_code_to_id[data_args.tgt_lang] else: UpperCamelCase_ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(UpperCamelCase_ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) UpperCamelCase_ = SeqaSeqDataset # Get datasets UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_train else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_predict else None ) # Initialize our Trainer UpperCamelCase_ = ( build_compute_metrics_fn(data_args.task , UpperCamelCase_ ) if training_args.predict_with_generate else None ) UpperCamelCase_ = SeqaSeqTrainer( model=UpperCamelCase_ , args=UpperCamelCase_ , data_args=UpperCamelCase_ , train_dataset=UpperCamelCase_ , eval_dataset=UpperCamelCase_ , data_collator=SeqaSeqDataCollator( UpperCamelCase_ , UpperCamelCase_ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=UpperCamelCase_ , tokenizer=UpperCamelCase_ , ) UpperCamelCase_ = {} # Training if training_args.do_train: logger.info("*** Train ***" ) UpperCamelCase_ = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) UpperCamelCase_ = train_result.metrics UpperCamelCase_ = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("train" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) UpperCamelCase_ = trainer.evaluate(metric_key_prefix="val" ) UpperCamelCase_ = data_args.n_val UpperCamelCase_ = round(metrics["val_loss"] , 4 ) if trainer.is_world_process_zero(): handle_metrics("val" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.do_predict: logger.info("*** Predict ***" ) UpperCamelCase_ = trainer.predict(test_dataset=UpperCamelCase_ , metric_key_prefix="test" ) UpperCamelCase_ = test_output.metrics UpperCamelCase_ = data_args.n_test if trainer.is_world_process_zero(): UpperCamelCase_ = round(metrics["test_loss"] , 4 ) handle_metrics("test" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.predict_with_generate: UpperCamelCase_ = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_ ) UpperCamelCase_ = lmap(str.strip , UpperCamelCase_ ) write_txt_file(UpperCamelCase_ , os.path.join(training_args.output_dir , "test_generations.txt" ) ) if trainer.is_world_process_zero(): save_json(UpperCamelCase_ , os.path.join(training_args.output_dir , "all_results.json" ) ) return all_metrics def lowerCAmelCase_ ( UpperCamelCase_ ) -> Optional[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
328
0
from math import pi, sqrt def lowerCAmelCase_ ( UpperCamelCase_ ) -> float: if num <= 0: raise ValueError("math domain error" ) if num > 171.5: raise OverflowError("math range error" ) elif num - int(UpperCamelCase_ ) not in (0, 0.5): raise NotImplementedError("num must be an integer or a half-integer" ) elif num == 0.5: return sqrt(UpperCamelCase_ ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def lowerCAmelCase_ ( ) -> None: assert gamma(0.5 ) == sqrt(UpperCamelCase_ ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _UpperCAmelCase = 1.0 while num: _UpperCAmelCase = float(input('Gamma of: ')) print(f'''gamma({num}) = {gamma(num)}''') print('\nEnter 0 to exit...')
353
def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = int(UpperCamelCase_ ) if n_element < 1: UpperCamelCase_ = ValueError("a should be a positive number" ) raise my_error UpperCamelCase_ = [1] UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = (0, 0, 0) UpperCamelCase_ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _UpperCAmelCase = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') _UpperCAmelCase = hamming(int(n)) print('-----------------------------------------------------') print(f'''The list with nth numbers is: {hamming_numbers}''') print('-----------------------------------------------------')
328
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : List[Any] = ['''image_processor''', '''tokenizer'''] _UpperCamelCase : Optional[int] = '''CLIPImageProcessor''' _UpperCamelCase : List[str] = ('''XLMRobertaTokenizer''', '''XLMRobertaTokenizerFast''') def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Any=None , _SCREAMING_SNAKE_CASE: List[Any]=None , **_SCREAMING_SNAKE_CASE: List[str] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , _SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = kwargs.pop("feature_extractor" ) UpperCamelCase_ = 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__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __call__( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[Any]=None , _SCREAMING_SNAKE_CASE: Optional[int]=None , _SCREAMING_SNAKE_CASE: str=None , **_SCREAMING_SNAKE_CASE: Tuple ) -> str: """simple docstring""" if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: UpperCamelCase_ = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if images is not None: UpperCamelCase_ = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None and images is not None: UpperCamelCase_ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_SCREAMING_SNAKE_CASE ) , tensor_type=_SCREAMING_SNAKE_CASE ) def lowercase ( self: int , *_SCREAMING_SNAKE_CASE: List[str] , **_SCREAMING_SNAKE_CASE: int ) -> str: """simple docstring""" return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: str , *_SCREAMING_SNAKE_CASE: List[str] , **_SCREAMING_SNAKE_CASE: Dict ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def lowercase ( self: Union[str, Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.tokenizer.model_input_names UpperCamelCase_ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
354
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : List[Any] = IFImgaImgSuperResolutionPipeline _UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} _UpperCamelCase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) _UpperCamelCase : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowercase ( self: List[str] ) -> Any: """simple docstring""" return self._get_superresolution_dummy_components() def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[int]=0 ) -> List[Any]: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Any ) -> Union[str, Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowercase ( self: int ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowercase ( self: Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowercase ( self: List[Any] ) -> Union[str, Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowercase ( self: Dict ) -> Any: """simple docstring""" self._test_save_load_local() def lowercase ( self: Any ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
328
0
"""simple docstring""" import re from filelock import FileLock try: import nltk _UpperCAmelCase = True except (ImportError, ModuleNotFoundError): _UpperCAmelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCAmelCase_ ( UpperCamelCase_ ) -> str: re.sub("<n>" , "" , UpperCamelCase_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase_ ) )
355
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent _UpperCAmelCase = {'UserAgent': UserAgent().random} def lowerCAmelCase_ ( UpperCamelCase_ ) -> dict: UpperCamelCase_ = script.contents[0] UpperCamelCase_ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class _UpperCamelCase : def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = f'''https://www.instagram.com/{username}/''' UpperCamelCase_ = self.get_json() def lowercase ( self: Union[str, Any] ) -> dict: """simple docstring""" UpperCamelCase_ = requests.get(self.url , headers=_SCREAMING_SNAKE_CASE ).text UpperCamelCase_ = BeautifulSoup(_SCREAMING_SNAKE_CASE , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self: Tuple ) -> str: """simple docstring""" return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self: List[Any] ) -> str: """simple docstring""" return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["username"] @property def lowercase ( self: int ) -> str: """simple docstring""" return self.user_data["full_name"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["biography"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["business_email"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["external_url"] @property def lowercase ( self: List[Any] ) -> int: """simple docstring""" return self.user_data["edge_followed_by"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_follow"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["profile_pic_url_hd"] @property def lowercase ( self: Optional[int] ) -> bool: """simple docstring""" return self.user_data["is_verified"] @property def lowercase ( self: List[str] ) -> bool: """simple docstring""" return self.user_data["is_private"] def lowerCAmelCase_ ( UpperCamelCase_ = "github" ) -> None: import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase_ = InstagramUser(UpperCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , UpperCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = InstagramUser('github') print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
328
0
import pytest _UpperCAmelCase = '__dummy_dataset1__' _UpperCAmelCase = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def lowerCAmelCase_ ( ) -> Union[str, Any]: return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def lowerCAmelCase_ ( ) -> Dict: return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: UpperCamelCase_ = dataset_loading_script_name UpperCamelCase_ = tmp_path / "datasets" / script_name script_dir.mkdir(parents=UpperCamelCase_ ) UpperCamelCase_ = script_dir / F'''{script_name}.py''' with open(UpperCamelCase_ , "w" ) as f: f.write(UpperCamelCase_ ) return str(UpperCamelCase_ )
356
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _UpperCAmelCase = False _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = 'ybelkada/fonts' def lowerCAmelCase_ ( ) -> Dict: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: requires_backends(UpperCamelCase_ , ["torch"] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase_ , UpperCamelCase_ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = 36 , UpperCamelCase_ = "black" , UpperCamelCase_ = "white" , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> Image.Image: requires_backends(UpperCamelCase_ , "vision" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase_ ) UpperCamelCase_ = "\n".join(UpperCamelCase_ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase_ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase_ , "Arial.TTF" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase_ , encoding="UTF-8" , size=UpperCamelCase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , UpperCamelCase_ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase_ , UpperCamelCase_ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("RGB" , (image_width, image_height) , UpperCamelCase_ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase_ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase_ , fill=UpperCamelCase_ , font=UpperCamelCase_ ) return image def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> Union[str, Any]: requires_backends(UpperCamelCase_ , "vision" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase_ ) UpperCamelCase_ = render_text(UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase_ ) if infer_channel_dimension_format(UpperCamelCase_ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase_ , ChannelDimension.LAST ) return new_image class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''flattened_patches'''] def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: Optional[Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: dict , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = patch_size["height"], patch_size["width"] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_SCREAMING_SNAKE_CASE ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_SCREAMING_SNAKE_CASE , antialias=_SCREAMING_SNAKE_CASE , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([rows, 1] ).repeat(1 , _SCREAMING_SNAKE_CASE ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([1, columns] ).repeat(_SCREAMING_SNAKE_CASE , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_SCREAMING_SNAKE_CASE , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) return result def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: List[str] ) -> np.ndarray: """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = np.std(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: Optional[Dict[str, int]] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> ImageInput: """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("data_format" , _SCREAMING_SNAKE_CASE ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) UpperCamelCase_ = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) UpperCamelCase_ = kwargs.pop("font_bytes" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("font_path" , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [header_text] * len(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [ render_header(_SCREAMING_SNAKE_CASE , header_text[i] , font_bytes=_SCREAMING_SNAKE_CASE , font_path=_SCREAMING_SNAKE_CASE ) for i, image in enumerate(_SCREAMING_SNAKE_CASE ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_SCREAMING_SNAKE_CASE , max_patches=_SCREAMING_SNAKE_CASE , patch_size=_SCREAMING_SNAKE_CASE ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_outputs
328
0
_UpperCAmelCase = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _UpperCAmelCase = [None] * 1_0_0_0_0_0_0_0 _UpperCAmelCase = True _UpperCAmelCase = False def lowerCAmelCase_ ( UpperCamelCase_ ) -> bool: if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase_ = chain(next_number(UpperCamelCase_ ) ) UpperCamelCase_ = number_chain while number < 10000000: UpperCamelCase_ = number_chain number *= 10 return number_chain def lowerCAmelCase_ ( UpperCamelCase_ = 10000000 ) -> int: for i in range(1 , UpperCamelCase_ ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(UpperCamelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() print(f'''{solution() = }''')
357
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: Any , _SCREAMING_SNAKE_CASE: int = 768 , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(1 , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(torch.ones(1 , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[Union[str, torch.device]] = None , _SCREAMING_SNAKE_CASE: Optional[torch.dtype] = None , ) -> List[Any]: """simple docstring""" UpperCamelCase_ = nn.Parameter(self.mean.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(self.std.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) return self def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = (embeds - self.mean) * 1.0 / self.std return embeds def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Dict: """simple docstring""" UpperCamelCase_ = (embeds * self.std) + self.mean return embeds
328
0
"""simple docstring""" from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent _UpperCAmelCase = {'UserAgent': UserAgent().random} def lowerCAmelCase_ ( UpperCamelCase_ ) -> dict: UpperCamelCase_ = script.contents[0] UpperCamelCase_ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class _UpperCamelCase : def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = f'''https://www.instagram.com/{username}/''' UpperCamelCase_ = self.get_json() def lowercase ( self: Union[str, Any] ) -> dict: """simple docstring""" UpperCamelCase_ = requests.get(self.url , headers=_SCREAMING_SNAKE_CASE ).text UpperCamelCase_ = BeautifulSoup(_SCREAMING_SNAKE_CASE , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self: Tuple ) -> str: """simple docstring""" return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self: List[Any] ) -> str: """simple docstring""" return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["username"] @property def lowercase ( self: int ) -> str: """simple docstring""" return self.user_data["full_name"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["biography"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["business_email"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["external_url"] @property def lowercase ( self: List[Any] ) -> int: """simple docstring""" return self.user_data["edge_followed_by"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_follow"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["profile_pic_url_hd"] @property def lowercase ( self: Optional[int] ) -> bool: """simple docstring""" return self.user_data["is_verified"] @property def lowercase ( self: List[str] ) -> bool: """simple docstring""" return self.user_data["is_private"] def lowerCAmelCase_ ( UpperCamelCase_ = "github" ) -> None: import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase_ = InstagramUser(UpperCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , UpperCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = InstagramUser('github') print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
358
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _UpperCAmelCase = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) _UpperCAmelCase = logging.getLogger() def lowerCAmelCase_ ( ) -> Optional[int]: UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCamelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_="eval" ) -> Any: UpperCamelCase_ = os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) if os.path.exists(UpperCamelCase_ ): with open(UpperCamelCase_ , "r" ) as f: return json.load(UpperCamelCase_ ) raise ValueError(F'''can\'t find {path}''' ) _UpperCAmelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _UpperCamelCase ( lowerCAmelCase_ ): def lowercase ( self: Optional[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_glue.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) @slow def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_clm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 100 ) @slow def lowercase ( self: Any ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_summarization_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE , split="test" ) self.assertGreaterEqual(result["test_rouge1"] , 10 ) self.assertGreaterEqual(result["test_rouge2"] , 2 ) self.assertGreaterEqual(result["test_rougeL"] , 7 ) self.assertGreaterEqual(result["test_rougeLsum"] , 7 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 42 ) @slow def lowercase ( self: Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_ta_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.42 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_ner.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertGreaterEqual(result["eval_f1"] , 0.3 ) @slow def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_qa.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_f1"] , 30 ) self.assertGreaterEqual(result["eval_exact"] , 30 )
328
0
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params _UpperCAmelCase = getLogger(__name__) _UpperCAmelCase = 'cuda' if torch.cuda.is_available() else 'cpu' def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = 8 , UpperCamelCase_ = DEFAULT_DEVICE , UpperCamelCase_=False , UpperCamelCase_="summarization" , UpperCamelCase_=None , **UpperCamelCase_ , ) -> Dict: UpperCamelCase_ = Path(UpperCamelCase_ ).open("w" , encoding="utf-8" ) UpperCamelCase_ = str(UpperCamelCase_ ) UpperCamelCase_ = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase_ ).to(UpperCamelCase_ ) if fpaa: UpperCamelCase_ = model.half() UpperCamelCase_ = AutoTokenizer.from_pretrained(UpperCamelCase_ ) logger.info(F'''Inferred tokenizer type: {tokenizer.__class__}''' ) # if this is wrong, check config.model_type. UpperCamelCase_ = time.time() # update config with task specific params use_task_specific_params(UpperCamelCase_ , UpperCamelCase_ ) if prefix is None: UpperCamelCase_ = prefix or getattr(model.config , "prefix" , "" ) or "" for examples_chunk in tqdm(list(chunks(UpperCamelCase_ , UpperCamelCase_ ) ) ): UpperCamelCase_ = [prefix + text for text in examples_chunk] UpperCamelCase_ = tokenizer(UpperCamelCase_ , return_tensors="pt" , truncation=UpperCamelCase_ , padding="longest" ).to(UpperCamelCase_ ) UpperCamelCase_ = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **UpperCamelCase_ , ) UpperCamelCase_ = tokenizer.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_ ) for hypothesis in dec: fout.write(hypothesis + "\n" ) fout.flush() fout.close() UpperCamelCase_ = int(time.time() - start_time ) # seconds UpperCamelCase_ = len(UpperCamelCase_ ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowerCAmelCase_ ( ) -> List[Any]: return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" ) def lowerCAmelCase_ ( UpperCamelCase_=True ) -> Optional[int]: UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("model_name" , type=UpperCamelCase_ , help="like facebook/bart-large-cnn,t5-base, etc." ) parser.add_argument("input_path" , type=UpperCamelCase_ , help="like cnn_dm/test.source" ) parser.add_argument("save_path" , type=UpperCamelCase_ , help="where to save summaries" ) parser.add_argument("--reference_path" , type=UpperCamelCase_ , required=UpperCamelCase_ , help="like cnn_dm/test.target" ) parser.add_argument("--score_path" , type=UpperCamelCase_ , required=UpperCamelCase_ , default="metrics.json" , help="where to save metrics" ) parser.add_argument("--device" , type=UpperCamelCase_ , required=UpperCamelCase_ , default=UpperCamelCase_ , help="cuda, cuda:1, cpu etc." ) parser.add_argument( "--prefix" , type=UpperCamelCase_ , required=UpperCamelCase_ , default=UpperCamelCase_ , help="will be added to the begininng of src examples" ) parser.add_argument("--task" , type=UpperCamelCase_ , default="summarization" , help="used for task_specific_params + metrics" ) parser.add_argument("--bs" , type=UpperCamelCase_ , default=8 , required=UpperCamelCase_ , help="batch size" ) parser.add_argument( "--n_obs" , type=UpperCamelCase_ , default=-1 , required=UpperCamelCase_ , help="How many observations. Defaults to all." ) parser.add_argument("--fp16" , action="store_true" ) parser.add_argument("--dump-args" , action="store_true" , help="print the custom hparams with the results" ) parser.add_argument( "--info" , nargs="?" , type=UpperCamelCase_ , const=datetime_now() , help=( "use in conjunction w/ --dump-args to print with the results whatever other info you'd like, e.g." " lang=en-ru. If no value is passed, the current datetime string will be used." ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate UpperCamelCase_ , UpperCamelCase_ = parser.parse_known_args() UpperCamelCase_ = parse_numeric_n_bool_cl_kwargs(UpperCamelCase_ ) if parsed_args and verbose: print(F'''parsed the following generate kwargs: {parsed_args}''' ) UpperCamelCase_ = [" " + x.rstrip() if "t5" in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: UpperCamelCase_ = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=UpperCamelCase_ ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(F'''score_path {args.score_path} will be overwritten unless you type ctrl-c.''' ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError("Can't mix --fp16 and --device cpu" ) UpperCamelCase_ = generate_summaries_or_translations( UpperCamelCase_ , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **UpperCamelCase_ , ) if args.reference_path is None: return {} # Compute scores UpperCamelCase_ = calculate_bleu if "translation" in args.task else calculate_rouge UpperCamelCase_ = [x.rstrip() for x in open(args.save_path ).readlines()] UpperCamelCase_ = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(UpperCamelCase_ )] UpperCamelCase_ = score_fn(UpperCamelCase_ , UpperCamelCase_ ) scores.update(UpperCamelCase_ ) if args.dump_args: scores.update(UpperCamelCase_ ) if args.info: UpperCamelCase_ = args.info if verbose: print(UpperCamelCase_ ) if args.score_path is not None: json.dump(UpperCamelCase_ , open(args.score_path , "w" ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
359
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: for param in module.parameters(): UpperCamelCase_ = False def lowerCAmelCase_ ( ) -> Dict: UpperCamelCase_ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): UpperCamelCase_ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def lowerCAmelCase_ ( ) -> List[str]: UpperCamelCase_ = datetime.now() UpperCamelCase_ = current_time.strftime("%H:%M:%S" ) return timestamp
328
0
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class _UpperCamelCase : def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int]=2 , _SCREAMING_SNAKE_CASE: List[str]=True , _SCREAMING_SNAKE_CASE: Dict=False , _SCREAMING_SNAKE_CASE: Optional[int]=10 , _SCREAMING_SNAKE_CASE: List[str]=3 , _SCREAMING_SNAKE_CASE: Tuple=32 * 4 , _SCREAMING_SNAKE_CASE: Optional[Any]=32 * 6 , _SCREAMING_SNAKE_CASE: List[Any]=4 , _SCREAMING_SNAKE_CASE: Optional[Any]=32 , ) -> str: """simple docstring""" UpperCamelCase_ = parent UpperCamelCase_ = batch_size UpperCamelCase_ = is_training UpperCamelCase_ = use_auxiliary_loss UpperCamelCase_ = num_queries UpperCamelCase_ = num_channels UpperCamelCase_ = min_size UpperCamelCase_ = max_size UpperCamelCase_ = num_labels UpperCamelCase_ = mask_feature_size def lowercase ( self: Union[str, Any] ) -> List[str]: """simple docstring""" UpperCamelCase_ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_SCREAMING_SNAKE_CASE ) > 0.5 ).float() UpperCamelCase_ = (torch.rand((self.batch_size, self.num_labels) , device=_SCREAMING_SNAKE_CASE ) > 0.5).long() UpperCamelCase_ = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowercase ( self: int ) -> Optional[Any]: """simple docstring""" return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def lowercase ( self: Union[str, Any] ) -> str: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = self.prepare_config_and_inputs() UpperCamelCase_ = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] ) -> Any: """simple docstring""" UpperCamelCase_ = output.encoder_hidden_states UpperCamelCase_ = output.pixel_decoder_hidden_states UpperCamelCase_ = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE ) , config.decoder_config.decoder_layers ) def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Any=False ) -> Tuple: """simple docstring""" with torch.no_grad(): UpperCamelCase_ = MaskFormerModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase_ = model(pixel_values=_SCREAMING_SNAKE_CASE , pixel_mask=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = model(_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: List[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = MaskFormerForInstanceSegmentation(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() def comm_check_on_output(_SCREAMING_SNAKE_CASE: Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): UpperCamelCase_ = model(pixel_values=_SCREAMING_SNAKE_CASE , pixel_mask=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = model(_SCREAMING_SNAKE_CASE ) comm_check_on_output(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = model( pixel_values=_SCREAMING_SNAKE_CASE , pixel_mask=_SCREAMING_SNAKE_CASE , mask_labels=_SCREAMING_SNAKE_CASE , class_labels=_SCREAMING_SNAKE_CASE ) comm_check_on_output(_SCREAMING_SNAKE_CASE ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () _UpperCamelCase : List[Any] = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) _UpperCamelCase : List[Any] = False _UpperCamelCase : Tuple = False _UpperCamelCase : Dict = False _UpperCamelCase : Optional[int] = False def lowercase ( self: Optional[int] ) -> List[str]: """simple docstring""" UpperCamelCase_ = MaskFormerModelTester(self ) UpperCamelCase_ = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def lowercase ( self: Tuple ) -> List[Any]: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="MaskFormer does not use inputs_embeds" ) def lowercase ( self: Any ) -> Tuple: """simple docstring""" pass @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" ) def lowercase ( self: List[Any] ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormer is not a generative model" ) def lowercase ( self: Dict ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="MaskFormer does not use token embeddings" ) def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip( reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def lowercase ( self: Dict ) -> str: """simple docstring""" pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def lowercase ( self: Tuple ) -> str: """simple docstring""" pass def lowercase ( self: Union[str, Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase_ = model_class(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase_ = [*signature.parameters.keys()] UpperCamelCase_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) @slow def lowercase ( self: List[Any] ) -> Union[str, Any]: """simple docstring""" for model_name in ["facebook/maskformer-swin-small-coco"]: UpperCamelCase_ = MaskFormerModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[Any] ) -> Any: """simple docstring""" UpperCamelCase_ = (self.model_tester.min_size,) * 2 UpperCamelCase_ = { "pixel_values": torch.randn((2, 3, *size) , device=_SCREAMING_SNAKE_CASE ), "mask_labels": torch.randn((2, 10, *size) , device=_SCREAMING_SNAKE_CASE ), "class_labels": torch.zeros(2 , 10 , device=_SCREAMING_SNAKE_CASE ).long(), } UpperCamelCase_ = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = model(**_SCREAMING_SNAKE_CASE ) self.assertTrue(outputs.loss is not None ) def lowercase ( self: str ) -> Dict: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase_ = model_class(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = model(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertTrue(outputs.attentions is not None ) def lowercase ( self: Tuple ) -> List[Any]: """simple docstring""" if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss UpperCamelCase_ = self.all_model_classes[1] UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs() UpperCamelCase_ = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.train() UpperCamelCase_ = model(_SCREAMING_SNAKE_CASE , mask_labels=_SCREAMING_SNAKE_CASE , class_labels=_SCREAMING_SNAKE_CASE ).loss loss.backward() def lowercase ( self: str ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = self.all_model_classes[1] UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs() UpperCamelCase_ = True UpperCamelCase_ = True UpperCamelCase_ = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.train() UpperCamelCase_ = model(_SCREAMING_SNAKE_CASE , mask_labels=_SCREAMING_SNAKE_CASE , class_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCamelCase_ = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't UpperCamelCase_ = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCamelCase_ = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _UpperCAmelCase = 1e-4 def lowerCAmelCase_ ( ) -> Any: UpperCamelCase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class _UpperCamelCase ( unittest.TestCase ): @cached_property def lowercase ( self: Dict ) -> Tuple: """simple docstring""" return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" ) if is_vision_available() else None ) def lowercase ( self: Dict ) -> str: """simple docstring""" UpperCamelCase_ = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.default_image_processor UpperCamelCase_ = prepare_img() UpperCamelCase_ = image_processor(_SCREAMING_SNAKE_CASE , return_tensors="pt" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_SCREAMING_SNAKE_CASE , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCamelCase_ = model(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.tensor( [[-0.04_82, 0.92_28, 0.49_51], [-0.25_47, 0.80_17, 0.85_27], [-0.00_69, 0.33_85, -0.00_89]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = torch.tensor( [[-0.84_22, -0.84_34, -0.97_18], [-1.01_44, -0.55_65, -0.41_95], [-1.00_38, -0.44_84, -0.19_61]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = torch.tensor( [[0.28_52, -0.01_59, 0.97_35], [0.62_54, 0.18_58, 0.85_29], [-0.06_80, -0.41_16, 1.84_13]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) def lowercase ( self: Optional[int] ) -> Any: """simple docstring""" UpperCamelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(_SCREAMING_SNAKE_CASE ) .eval() ) UpperCamelCase_ = self.default_image_processor UpperCamelCase_ = prepare_img() UpperCamelCase_ = image_processor(_SCREAMING_SNAKE_CASE , return_tensors="pt" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_SCREAMING_SNAKE_CASE , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCamelCase_ = model(**_SCREAMING_SNAKE_CASE ) # masks_queries_logits UpperCamelCase_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) UpperCamelCase_ = [ [-1.3_73_71_24, -1.7_72_49_37, -1.9_36_42_33], [-1.5_97_72_81, -1.9_86_79_39, -2.1_52_36_95], [-1.5_79_53_98, -1.9_26_98_32, -2.09_39_42], ] UpperCamelCase_ = torch.tensor(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) # class_queries_logits UpperCamelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) UpperCamelCase_ = torch.tensor( [ [1.6512e00, -5.2572e00, -3.3519e00], [3.6169e-02, -5.9025e00, -2.9313e00], [1.0766e-04, -7.7630e00, -5.1263e00], ] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) def lowercase ( self: List[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" ) .to(_SCREAMING_SNAKE_CASE ) .eval() ) UpperCamelCase_ = self.default_image_processor UpperCamelCase_ = prepare_img() UpperCamelCase_ = image_processor(_SCREAMING_SNAKE_CASE , return_tensors="pt" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_SCREAMING_SNAKE_CASE , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCamelCase_ = model(**_SCREAMING_SNAKE_CASE ) # masks_queries_logits UpperCamelCase_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) UpperCamelCase_ = [[-0.90_46, -2.63_66, -4.60_62], [-3.41_79, -5.78_90, -8.80_57], [-4.91_79, -7.65_60, -10.77_11]] UpperCamelCase_ = torch.tensor(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) # class_queries_logits UpperCamelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) UpperCamelCase_ = torch.tensor( [[4.71_88, -3.25_85, -2.88_57], [6.68_71, -2.91_81, -1.24_87], [7.24_49, -2.27_64, -2.18_74]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=_SCREAMING_SNAKE_CASE ) ) def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" UpperCamelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(_SCREAMING_SNAKE_CASE ) .eval() ) UpperCamelCase_ = self.default_image_processor UpperCamelCase_ = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) UpperCamelCase_ = inputs["pixel_values"].to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [el.to(_SCREAMING_SNAKE_CASE ) for el in inputs["mask_labels"]] UpperCamelCase_ = [el.to(_SCREAMING_SNAKE_CASE ) for el in inputs["class_labels"]] with torch.no_grad(): UpperCamelCase_ = model(**_SCREAMING_SNAKE_CASE ) self.assertTrue(outputs.loss is not None )
360
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 _UpperCAmelCase = '▁' _UpperCAmelCase = {'vocab_file': 'spiece.model'} _UpperCAmelCase = { 'vocab_file': {'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'} } _UpperCAmelCase = { 'google/pegasus-xsum': 5_1_2, } _UpperCAmelCase = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = VOCAB_FILES_NAMES _UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[int] = ['''input_ids''', '''attention_mask'''] def __init__( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: str="<pad>" , _SCREAMING_SNAKE_CASE: Optional[Any]="</s>" , _SCREAMING_SNAKE_CASE: Any="<unk>" , _SCREAMING_SNAKE_CASE: int="<mask_2>" , _SCREAMING_SNAKE_CASE: List[Any]="<mask_1>" , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: Optional[int]=103 , _SCREAMING_SNAKE_CASE: Optional[Dict[str, Any]] = None , **_SCREAMING_SNAKE_CASE: Dict , ) -> None: """simple docstring""" UpperCamelCase_ = offset if additional_special_tokens is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError( f'''additional_special_tokens should be of type {type(_SCREAMING_SNAKE_CASE )}, but is''' f''' {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'''<unk_{i}>''' for i in range(len(_SCREAMING_SNAKE_CASE ) , self.offset - 1 ) ] if len(set(_SCREAMING_SNAKE_CASE ) ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError( "Please make sure that the provided additional_special_tokens do not contain an incorrectly" f''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) UpperCamelCase_ = additional_special_tokens_extended else: UpperCamelCase_ = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'''<unk_{i}>''' for i in range(2 , self.offset )] UpperCamelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token_sent=_SCREAMING_SNAKE_CASE , offset=_SCREAMING_SNAKE_CASE , additional_special_tokens=_SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = mask_token_sent UpperCamelCase_ = vocab_file UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_SCREAMING_SNAKE_CASE ) # add special tokens to encoder dict UpperCamelCase_ = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) UpperCamelCase_ = {v: k for k, v in self.encoder.items()} @property def lowercase ( self: Dict ) -> int: """simple docstring""" return len(self.sp_model ) + self.offset def lowercase ( self: int ) -> Dict[str, int]: """simple docstring""" UpperCamelCase_ = {self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self: Optional[int] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = self.__dict__.copy() UpperCamelCase_ = None return state def __setstate__( self: List[Any] , _SCREAMING_SNAKE_CASE: List[Any] ) -> Any: """simple docstring""" UpperCamelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCamelCase_ = {} UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_SCREAMING_SNAKE_CASE , out_type=_SCREAMING_SNAKE_CASE ) def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: str ) -> int: """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] UpperCamelCase_ = self.sp_model.piece_to_id(_SCREAMING_SNAKE_CASE ) return sp_id + self.offset def lowercase ( self: str , _SCREAMING_SNAKE_CASE: int ) -> str: """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: UpperCamelCase_ = self.sp_model.IdToPiece(index - self.offset ) return token def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = [] UpperCamelCase_ = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) + token UpperCamelCase_ = [] else: current_sub_tokens.append(_SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) return out_string.strip() def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Optional[int]=False ) -> Union[str, Any]: """simple docstring""" return 1 def lowercase ( self: int , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: List , _SCREAMING_SNAKE_CASE: Optional[List] = None , _SCREAMING_SNAKE_CASE: bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) elif token_ids_a is None: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any]=None ) -> List[int]: """simple docstring""" if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCamelCase_ = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(_SCREAMING_SNAKE_CASE , "wb" ) as fi: UpperCamelCase_ = self.sp_model.serialized_model_proto() fi.write(_SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
328
0
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = len(UpperCamelCase_ ) UpperCamelCase_ = len(matrix[0] ) UpperCamelCase_ = min(UpperCamelCase_ , UpperCamelCase_ ) for row in range(UpperCamelCase_ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , UpperCamelCase_ ): UpperCamelCase_ = matrix[col][row] / matrix[row][row] for i in range(UpperCamelCase_ , UpperCamelCase_ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows UpperCamelCase_ = True for i in range(row + 1 , UpperCamelCase_ ): if matrix[i][row] != 0: UpperCamelCase_ , UpperCamelCase_ = matrix[i], matrix[row] UpperCamelCase_ = False break if reduce: rank -= 1 for i in range(UpperCamelCase_ ): UpperCamelCase_ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
361
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { 'configuration_tapas': ['TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TapasConfig'], 'tokenization_tapas': ['TapasTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TapasForMaskedLM', 'TapasForQuestionAnswering', 'TapasForSequenceClassification', 'TapasModel', 'TapasPreTrainedModel', 'load_tf_weights_in_tapas', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFTapasForMaskedLM', 'TFTapasForQuestionAnswering', 'TFTapasForSequenceClassification', 'TFTapasModel', 'TFTapasPreTrainedModel', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
328
0
"""simple docstring""" import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput _UpperCAmelCase = 'scheduler_config.json' class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Union[str, Any] = 1 _UpperCamelCase : List[Any] = 2 _UpperCamelCase : Any = 3 _UpperCamelCase : str = 4 _UpperCamelCase : Dict = 5 @dataclass class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : jnp.ndarray class _UpperCamelCase : _UpperCamelCase : str = SCHEDULER_CONFIG_NAME _UpperCamelCase : Dict = ['''dtype'''] _UpperCamelCase : int = [] _UpperCamelCase : Optional[int] = True @classmethod def lowercase ( cls: Optional[Any] , _SCREAMING_SNAKE_CASE: Dict[str, Any] = None , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: List[str]=False , **_SCREAMING_SNAKE_CASE: Any , ) -> Optional[int]: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = cls.load_config( pretrained_model_name_or_path=_SCREAMING_SNAKE_CASE , subfolder=_SCREAMING_SNAKE_CASE , return_unused_kwargs=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ , UpperCamelCase_ = cls.from_config(_SCREAMING_SNAKE_CASE , return_unused_kwargs=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , "create_state" ) and getattr(_SCREAMING_SNAKE_CASE , "has_state" , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Union[str, os.PathLike] , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: str ) -> List[Any]: """simple docstring""" self.save_config(save_directory=_SCREAMING_SNAKE_CASE , push_to_hub=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def lowercase ( self: Dict ) -> List[str]: """simple docstring""" return self._get_compatibles() @classmethod def lowercase ( cls: Optional[Any] ) -> str: """simple docstring""" UpperCamelCase_ = list(set([cls.__name__] + cls._compatibles ) ) UpperCamelCase_ = importlib.import_module(__name__.split("." )[0] ) UpperCamelCase_ = [ getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for c in compatible_classes_str if hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ] return compatible_classes def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> jnp.ndarray: assert len(UpperCamelCase_ ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(UpperCamelCase_ ) - x.ndim) ) , UpperCamelCase_ ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_=0.9_99 , UpperCamelCase_=jnp.floataa ) -> jnp.ndarray: def alpha_bar(UpperCamelCase_ ): return math.cos((time_step + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 UpperCamelCase_ = [] for i in range(UpperCamelCase_ ): UpperCamelCase_ = i / num_diffusion_timesteps UpperCamelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(UpperCamelCase_ ) / alpha_bar(UpperCamelCase_ ) , UpperCamelCase_ ) ) return jnp.array(UpperCamelCase_ , dtype=UpperCamelCase_ ) @flax.struct.dataclass class _UpperCamelCase : _UpperCamelCase : jnp.ndarray _UpperCamelCase : jnp.ndarray _UpperCamelCase : jnp.ndarray @classmethod def lowercase ( cls: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = scheduler.config if config.trained_betas is not None: UpperCamelCase_ = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": UpperCamelCase_ = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCamelCase_ = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCamelCase_ = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( f'''beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}''' ) UpperCamelCase_ = 1.0 - betas UpperCamelCase_ = jnp.cumprod(_SCREAMING_SNAKE_CASE , axis=0 ) return cls( alphas=_SCREAMING_SNAKE_CASE , betas=_SCREAMING_SNAKE_CASE , alphas_cumprod=_SCREAMING_SNAKE_CASE , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> int: UpperCamelCase_ = state.alphas_cumprod UpperCamelCase_ = alphas_cumprod[timesteps] ** 0.5 UpperCamelCase_ = sqrt_alpha_prod.flatten() UpperCamelCase_ = broadcast_to_shape_from_left(UpperCamelCase_ , original_samples.shape ) UpperCamelCase_ = (1 - alphas_cumprod[timesteps]) ** 0.5 UpperCamelCase_ = sqrt_one_minus_alpha_prod.flatten() UpperCamelCase_ = broadcast_to_shape_from_left(UpperCamelCase_ , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ , UpperCamelCase_ = get_sqrt_alpha_prod(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ , UpperCamelCase_ = get_sqrt_alpha_prod(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
362
import argparse import json from tqdm import tqdm def lowerCAmelCase_ ( ) -> Tuple: UpperCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--src_path" , type=UpperCamelCase_ , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , ) parser.add_argument( "--evaluation_set" , type=UpperCamelCase_ , help="where to store parsed evaluation_set file" , ) parser.add_argument( "--gold_data_path" , type=UpperCamelCase_ , help="where to store parsed gold_data_path file" , ) UpperCamelCase_ = parser.parse_args() with open(args.src_path , "r" ) as src_file, open(args.evaluation_set , "w" ) as eval_file, open( args.gold_data_path , "w" ) as gold_file: UpperCamelCase_ = json.load(UpperCamelCase_ ) for dpr_record in tqdm(UpperCamelCase_ ): UpperCamelCase_ = dpr_record["question"] UpperCamelCase_ = [context["title"] for context in dpr_record["positive_ctxs"]] eval_file.write(question + "\n" ) gold_file.write("\t".join(UpperCamelCase_ ) + "\n" ) if __name__ == "__main__": main()
328
0
from ..utils import DummyObject, requires_backends class _UpperCamelCase ( metaclass=lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = ['''flax''', '''transformers'''] def __init__( self: int , *_SCREAMING_SNAKE_CASE: Tuple , **_SCREAMING_SNAKE_CASE: Optional[Any] ) -> Any: """simple docstring""" requires_backends(self , ["flax", "transformers"] ) @classmethod def lowercase ( cls: Any , *_SCREAMING_SNAKE_CASE: Union[str, Any] , **_SCREAMING_SNAKE_CASE: int ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ["flax", "transformers"] ) @classmethod def lowercase ( cls: int , *_SCREAMING_SNAKE_CASE: List[Any] , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> str: """simple docstring""" requires_backends(cls , ["flax", "transformers"] ) class _UpperCamelCase ( metaclass=lowerCAmelCase_ ): _UpperCamelCase : Union[str, Any] = ['''flax''', '''transformers'''] def __init__( self: Dict , *_SCREAMING_SNAKE_CASE: Dict , **_SCREAMING_SNAKE_CASE: List[Any] ) -> Any: """simple docstring""" requires_backends(self , ["flax", "transformers"] ) @classmethod def lowercase ( cls: Optional[int] , *_SCREAMING_SNAKE_CASE: Any , **_SCREAMING_SNAKE_CASE: List[Any] ) -> str: """simple docstring""" requires_backends(cls , ["flax", "transformers"] ) @classmethod def lowercase ( cls: Any , *_SCREAMING_SNAKE_CASE: Optional[Any] , **_SCREAMING_SNAKE_CASE: Dict ) -> List[str]: """simple docstring""" requires_backends(cls , ["flax", "transformers"] ) class _UpperCamelCase ( metaclass=lowerCAmelCase_ ): _UpperCamelCase : List[str] = ['''flax''', '''transformers'''] def __init__( self: Optional[int] , *_SCREAMING_SNAKE_CASE: Optional[int] , **_SCREAMING_SNAKE_CASE: Optional[Any] ) -> Optional[int]: """simple docstring""" requires_backends(self , ["flax", "transformers"] ) @classmethod def lowercase ( cls: Union[str, Any] , *_SCREAMING_SNAKE_CASE: Dict , **_SCREAMING_SNAKE_CASE: Dict ) -> Dict: """simple docstring""" requires_backends(cls , ["flax", "transformers"] ) @classmethod def lowercase ( cls: List[Any] , *_SCREAMING_SNAKE_CASE: int , **_SCREAMING_SNAKE_CASE: str ) -> Optional[int]: """simple docstring""" requires_backends(cls , ["flax", "transformers"] ) class _UpperCamelCase ( metaclass=lowerCAmelCase_ ): _UpperCamelCase : Optional[int] = ['''flax''', '''transformers'''] def __init__( self: List[str] , *_SCREAMING_SNAKE_CASE: int , **_SCREAMING_SNAKE_CASE: Optional[Any] ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["flax", "transformers"] ) @classmethod def lowercase ( cls: Tuple , *_SCREAMING_SNAKE_CASE: List[str] , **_SCREAMING_SNAKE_CASE: Tuple ) -> str: """simple docstring""" requires_backends(cls , ["flax", "transformers"] ) @classmethod def lowercase ( cls: List[str] , *_SCREAMING_SNAKE_CASE: Optional[int] , **_SCREAMING_SNAKE_CASE: List[Any] ) -> List[str]: """simple docstring""" requires_backends(cls , ["flax", "transformers"] )
363
import requests from bsa import BeautifulSoup def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = BeautifulSoup(requests.get(UpperCamelCase_ , params=UpperCamelCase_ ).content , "html.parser" ) UpperCamelCase_ = soup.find("div" , attrs={"class": "gs_ri"} ) UpperCamelCase_ = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": _UpperCAmelCase = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
328
0
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _UpperCAmelCase = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class _UpperCamelCase ( unittest.TestCase ): _UpperCamelCase : List[str] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _UpperCamelCase : Optional[int] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _UpperCamelCase : Any = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _UpperCamelCase : Tuple = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> int: """simple docstring""" UpperCamelCase_ = ZeroShotClassificationPipeline( model=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , candidate_labels=["polics", "health"] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Dict ) -> Tuple: """simple docstring""" UpperCamelCase_ = classifier("Who are you voting for in 2020?" , candidate_labels="politics" ) self.assertEqual(_SCREAMING_SNAKE_CASE , {"sequence": ANY(_SCREAMING_SNAKE_CASE ), "labels": [ANY(_SCREAMING_SNAKE_CASE )], "scores": [ANY(_SCREAMING_SNAKE_CASE )]} ) # No kwarg UpperCamelCase_ = classifier("Who are you voting for in 2020?" , ["politics"] ) self.assertEqual(_SCREAMING_SNAKE_CASE , {"sequence": ANY(_SCREAMING_SNAKE_CASE ), "labels": [ANY(_SCREAMING_SNAKE_CASE )], "scores": [ANY(_SCREAMING_SNAKE_CASE )]} ) UpperCamelCase_ = classifier("Who are you voting for in 2020?" , candidate_labels=["politics"] ) self.assertEqual(_SCREAMING_SNAKE_CASE , {"sequence": ANY(_SCREAMING_SNAKE_CASE ), "labels": [ANY(_SCREAMING_SNAKE_CASE )], "scores": [ANY(_SCREAMING_SNAKE_CASE )]} ) UpperCamelCase_ = classifier("Who are you voting for in 2020?" , candidate_labels="politics, public health" ) self.assertEqual( _SCREAMING_SNAKE_CASE , {"sequence": ANY(_SCREAMING_SNAKE_CASE ), "labels": [ANY(_SCREAMING_SNAKE_CASE ), ANY(_SCREAMING_SNAKE_CASE )], "scores": [ANY(_SCREAMING_SNAKE_CASE ), ANY(_SCREAMING_SNAKE_CASE )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["scores"] ) ) , 1.0 ) UpperCamelCase_ = classifier("Who are you voting for in 2020?" , candidate_labels=["politics", "public health"] ) self.assertEqual( _SCREAMING_SNAKE_CASE , {"sequence": ANY(_SCREAMING_SNAKE_CASE ), "labels": [ANY(_SCREAMING_SNAKE_CASE ), ANY(_SCREAMING_SNAKE_CASE )], "scores": [ANY(_SCREAMING_SNAKE_CASE ), ANY(_SCREAMING_SNAKE_CASE )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["scores"] ) ) , 1.0 ) UpperCamelCase_ = classifier( "Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template="This text is about {}" ) self.assertEqual(_SCREAMING_SNAKE_CASE , {"sequence": ANY(_SCREAMING_SNAKE_CASE ), "labels": [ANY(_SCREAMING_SNAKE_CASE )], "scores": [ANY(_SCREAMING_SNAKE_CASE )]} ) # https://github.com/huggingface/transformers/issues/13846 UpperCamelCase_ = classifier(["I am happy"] , ["positive", "negative"] ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ {"sequence": ANY(_SCREAMING_SNAKE_CASE ), "labels": [ANY(_SCREAMING_SNAKE_CASE ), ANY(_SCREAMING_SNAKE_CASE )], "scores": [ANY(_SCREAMING_SNAKE_CASE ), ANY(_SCREAMING_SNAKE_CASE )]} for i in range(1 ) ] , ) UpperCamelCase_ = classifier(["I am happy", "I am sad"] , ["positive", "negative"] ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ {"sequence": ANY(_SCREAMING_SNAKE_CASE ), "labels": [ANY(_SCREAMING_SNAKE_CASE ), ANY(_SCREAMING_SNAKE_CASE )], "scores": [ANY(_SCREAMING_SNAKE_CASE ), ANY(_SCREAMING_SNAKE_CASE )]} for i in range(2 ) ] , ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): classifier("" , candidate_labels="politics" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): classifier(_SCREAMING_SNAKE_CASE , candidate_labels="politics" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): classifier("Who are you voting for in 2020?" , candidate_labels="" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): classifier("Who are you voting for in 2020?" , candidate_labels=_SCREAMING_SNAKE_CASE ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): classifier( "Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template="Not formatting template" , ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): classifier( "Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template=_SCREAMING_SNAKE_CASE , ) self.run_entailment_id(_SCREAMING_SNAKE_CASE ) def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Pipeline ) -> Dict: """simple docstring""" UpperCamelCase_ = zero_shot_classifier.model.config UpperCamelCase_ = config.labelaid UpperCamelCase_ = zero_shot_classifier.entailment_id UpperCamelCase_ = {"LABEL_0": 0, "LABEL_1": 1, "LABEL_2": 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) UpperCamelCase_ = {"entailment": 0, "neutral": 1, "contradiction": 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) UpperCamelCase_ = {"ENTAIL": 0, "NON-ENTAIL": 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) UpperCamelCase_ = {"ENTAIL": 2, "NEUTRAL": 1, "CONTR": 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) UpperCamelCase_ = original_labelaid self.assertEqual(_SCREAMING_SNAKE_CASE , zero_shot_classifier.entailment_id ) @require_torch def lowercase ( self: Tuple ) -> List[str]: """simple docstring""" UpperCamelCase_ = pipeline( "zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="pt" , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( "Who are you voting for in 2020?" * 100 , candidate_labels=["politics", "public health", "science"] ) @require_torch def lowercase ( self: str ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = pipeline( "zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="pt" , ) UpperCamelCase_ = zero_shot_classifier( "Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE ) , { "sequence": "Who are you voting for in 2020?", "labels": ["science", "public health", "politics"], "scores": [0.3_33, 0.3_33, 0.3_33], } , ) @require_tf def lowercase ( self: Dict ) -> str: """simple docstring""" UpperCamelCase_ = pipeline( "zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="tf" , ) UpperCamelCase_ = zero_shot_classifier( "Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE ) , { "sequence": "Who are you voting for in 2020?", "labels": ["science", "public health", "politics"], "scores": [0.3_33, 0.3_33, 0.3_33], } , ) @slow @require_torch def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" UpperCamelCase_ = pipeline("zero-shot-classification" , model="roberta-large-mnli" , framework="pt" ) UpperCamelCase_ = zero_shot_classifier( "Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE ) , { "sequence": "Who are you voting for in 2020?", "labels": ["politics", "public health", "science"], "scores": [0.9_76, 0.0_15, 0.0_09], } , ) UpperCamelCase_ = zero_shot_classifier( "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks" " in an encoder-decoder configuration. The best performing models also connect the encoder and decoder" " through an attention mechanism. We propose a new simple network architecture, the Transformer, based" " solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two" " machine translation tasks show these models to be superior in quality while being more parallelizable" " and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014" " English-to-German translation task, improving over the existing best results, including ensembles by" " over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new" " single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small" " fraction of the training costs of the best models from the literature. We show that the Transformer" " generalizes well to other tasks by applying it successfully to English constituency parsing both with" " large and limited training data." , candidate_labels=["machine learning", "statistics", "translation", "vision"] , multi_label=_SCREAMING_SNAKE_CASE , ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE ) , { "sequence": ( "The dominant sequence transduction models are based on complex recurrent or convolutional neural" " networks in an encoder-decoder configuration. The best performing models also connect the" " encoder and decoder through an attention mechanism. We propose a new simple network" " architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence" " and convolutions entirely. Experiments on two machine translation tasks show these models to be" " superior in quality while being more parallelizable and requiring significantly less time to" " train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task," " improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014" " English-to-French translation task, our model establishes a new single-model state-of-the-art" " BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training" " costs of the best models from the literature. We show that the Transformer generalizes well to" " other tasks by applying it successfully to English constituency parsing both with large and" " limited training data." ), "labels": ["translation", "machine learning", "vision", "statistics"], "scores": [0.8_17, 0.7_13, 0.0_18, 0.0_18], } , ) @slow @require_tf def lowercase ( self: Union[str, Any] ) -> str: """simple docstring""" UpperCamelCase_ = pipeline("zero-shot-classification" , model="roberta-large-mnli" , framework="tf" ) UpperCamelCase_ = zero_shot_classifier( "Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE ) , { "sequence": "Who are you voting for in 2020?", "labels": ["politics", "public health", "science"], "scores": [0.9_76, 0.0_15, 0.0_09], } , ) UpperCamelCase_ = zero_shot_classifier( "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks" " in an encoder-decoder configuration. The best performing models also connect the encoder and decoder" " through an attention mechanism. We propose a new simple network architecture, the Transformer, based" " solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two" " machine translation tasks show these models to be superior in quality while being more parallelizable" " and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014" " English-to-German translation task, improving over the existing best results, including ensembles by" " over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new" " single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small" " fraction of the training costs of the best models from the literature. We show that the Transformer" " generalizes well to other tasks by applying it successfully to English constituency parsing both with" " large and limited training data." , candidate_labels=["machine learning", "statistics", "translation", "vision"] , multi_label=_SCREAMING_SNAKE_CASE , ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE ) , { "sequence": ( "The dominant sequence transduction models are based on complex recurrent or convolutional neural" " networks in an encoder-decoder configuration. The best performing models also connect the" " encoder and decoder through an attention mechanism. We propose a new simple network" " architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence" " and convolutions entirely. Experiments on two machine translation tasks show these models to be" " superior in quality while being more parallelizable and requiring significantly less time to" " train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task," " improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014" " English-to-French translation task, our model establishes a new single-model state-of-the-art" " BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training" " costs of the best models from the literature. We show that the Transformer generalizes well to" " other tasks by applying it successfully to English constituency parsing both with large and" " limited training data." ), "labels": ["translation", "machine learning", "vision", "statistics"], "scores": [0.8_17, 0.7_13, 0.0_18, 0.0_18], } , )
364
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: List[str] , *, _SCREAMING_SNAKE_CASE: int = 4 , _SCREAMING_SNAKE_CASE: int = 768 , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: str , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(_SCREAMING_SNAKE_CASE ) ) # parameters for additional clip time embeddings UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # parameters for encoder hidden states UpperCamelCase_ = clip_extra_context_tokens UpperCamelCase_ = nn.Linear( _SCREAMING_SNAKE_CASE , self.clip_extra_context_tokens * cross_attention_dim ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.LayerNorm(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , *, _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> str: """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings UpperCamelCase_ = image_embeddings.shape[0] UpperCamelCase_ = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) UpperCamelCase_ = classifier_free_guidance_embeddings.expand( _SCREAMING_SNAKE_CASE , -1 ) UpperCamelCase_ = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] UpperCamelCase_ = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... UpperCamelCase_ = self.embedding_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.clip_image_embeddings_project_to_time_embeddings(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" UpperCamelCase_ = self.clip_extra_context_tokens_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = clip_extra_context_tokens.reshape(_SCREAMING_SNAKE_CASE , -1 , self.clip_extra_context_tokens ) UpperCamelCase_ = clip_extra_context_tokens.permute(0 , 2 , 1 ) UpperCamelCase_ = self.encoder_hidden_states_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.text_encoder_hidden_states_norm(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
328
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=lowerCAmelCase_ ) class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = field(default='''audio-classification''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) _UpperCamelCase : ClassVar[Features] = Features({'''audio''': Audio()} ) _UpperCamelCase : ClassVar[Features] = Features({'''labels''': ClassLabel} ) _UpperCamelCase : str = "audio" _UpperCamelCase : str = "labels" def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Dict ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , _SCREAMING_SNAKE_CASE ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) UpperCamelCase_ = copy.deepcopy(self ) UpperCamelCase_ = self.label_schema.copy() UpperCamelCase_ = features[self.label_column] UpperCamelCase_ = label_schema return task_template @property def lowercase ( self: Tuple ) -> Dict[str, str]: """simple docstring""" return { self.audio_column: "audio", self.label_column: "labels", }
365
from functools import lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> set: UpperCamelCase_ = 2 UpperCamelCase_ = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(UpperCamelCase_ ) if n > 1: factors.add(UpperCamelCase_ ) return factors @lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: return len(unique_prime_factors(UpperCamelCase_ ) ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> bool: return len(set(UpperCamelCase_ ) ) in (0, 1) def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = 2 while True: # Increment each value of a generated range UpperCamelCase_ = [base + i for i in range(UpperCamelCase_ )] # Run elements through out unique_prime_factors function # Append our target number to the end. UpperCamelCase_ = [upf_len(UpperCamelCase_ ) for x in group] checker.append(UpperCamelCase_ ) # If all numbers in the list are equal, return the group variable. if equality(UpperCamelCase_ ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase_ ( UpperCamelCase_ = 4 ) -> int: UpperCamelCase_ = run(UpperCamelCase_ ) return results[0] if len(UpperCamelCase_ ) else None if __name__ == "__main__": print(solution())
328
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import importlib.metadata import json import os from dataclasses import dataclass from typing import Any, Dict, Union from packaging import version from ..utils import is_torch_available, logging if is_torch_available(): import torch _UpperCAmelCase = logging.get_logger(__name__) @dataclass class _UpperCamelCase : def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: Dict=False , _SCREAMING_SNAKE_CASE: Any=False , _SCREAMING_SNAKE_CASE: Optional[Any]=6.0 , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: Any=False , _SCREAMING_SNAKE_CASE: str=False , _SCREAMING_SNAKE_CASE: str=None , _SCREAMING_SNAKE_CASE: List[str]="fp4" , _SCREAMING_SNAKE_CASE: Union[str, Any]=False , **_SCREAMING_SNAKE_CASE: Dict , ) -> str: """simple docstring""" UpperCamelCase_ = load_in_abit UpperCamelCase_ = load_in_abit UpperCamelCase_ = llm_inta_threshold UpperCamelCase_ = llm_inta_skip_modules UpperCamelCase_ = llm_inta_enable_fpaa_cpu_offload UpperCamelCase_ = llm_inta_has_fpaa_weight UpperCamelCase_ = bnb_abit_quant_type UpperCamelCase_ = bnb_abit_use_double_quant if bnb_abit_compute_dtype is None: UpperCamelCase_ = torch.floataa elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , torch.dtype ): UpperCamelCase_ = bnb_abit_compute_dtype else: raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype" ) self.post_init() def lowercase ( self: int ) -> List[Any]: """simple docstring""" if not isinstance(self.llm_inta_threshold , _SCREAMING_SNAKE_CASE ): raise ValueError("llm_int8_threshold must be a float" ) if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules , _SCREAMING_SNAKE_CASE ): raise ValueError("llm_int8_skip_modules must be a list of strings" ) if not isinstance(self.llm_inta_enable_fpaa_cpu_offload , _SCREAMING_SNAKE_CASE ): raise ValueError("llm_int8_enable_fp32_cpu_offload must be a boolean" ) if not isinstance(self.llm_inta_has_fpaa_weight , _SCREAMING_SNAKE_CASE ): raise ValueError("llm_int8_has_fp16_weight must be a boolean" ) if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype , torch.dtype ): raise ValueError("bnb_4bit_compute_dtype must be torch.dtype" ) if not isinstance(self.bnb_abit_quant_type , _SCREAMING_SNAKE_CASE ): raise ValueError("bnb_4bit_quant_type must be a string" ) if not isinstance(self.bnb_abit_use_double_quant , _SCREAMING_SNAKE_CASE ): raise ValueError("bnb_4bit_use_double_quant must be a boolean" ) if self.load_in_abit and not version.parse(importlib.metadata.version("bitsandbytes" ) ) >= version.parse( "0.39.0" ): raise ValueError( "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version" ) def lowercase ( self: int ) -> List[Any]: """simple docstring""" return self.load_in_abit or self.load_in_abit def lowercase ( self: str ) -> Optional[int]: """simple docstring""" if self.load_in_abit: return "llm_int8" elif self.load_in_abit and self.bnb_abit_quant_type == "fp4": return "fp4" elif self.load_in_abit and self.bnb_abit_quant_type == "nf4": return "nf4" else: return None @classmethod def lowercase ( cls: Tuple , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Dict , **_SCREAMING_SNAKE_CASE: Tuple ) -> List[Any]: """simple docstring""" UpperCamelCase_ = cls(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [] for key, value in kwargs.items(): if hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) to_remove.append(_SCREAMING_SNAKE_CASE ) for key in to_remove: kwargs.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if return_unused_kwargs: return config, kwargs else: return config def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Union[str, os.PathLike] ) -> Dict: """simple docstring""" with open(_SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as writer: UpperCamelCase_ = self.to_dict() UpperCamelCase_ = json.dumps(_SCREAMING_SNAKE_CASE , indent=2 , sort_keys=_SCREAMING_SNAKE_CASE ) + "\n" writer.write(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Any ) -> Dict[str, Any]: """simple docstring""" UpperCamelCase_ = copy.deepcopy(self.__dict__ ) UpperCamelCase_ = str(output["bnb_4bit_compute_dtype"] ).split("." )[1] return output def __repr__( self: Tuple ) -> List[str]: """simple docstring""" return f'''{self.__class__.__name__} {self.to_json_string()}''' def lowercase ( self: str , _SCREAMING_SNAKE_CASE: bool = True ) -> str: """simple docstring""" if use_diff is True: UpperCamelCase_ = self.to_diff_dict() else: UpperCamelCase_ = self.to_dict() return json.dumps(_SCREAMING_SNAKE_CASE , indent=2 , sort_keys=_SCREAMING_SNAKE_CASE ) + "\n" def lowercase ( self: Optional[int] ) -> Dict[str, Any]: """simple docstring""" UpperCamelCase_ = self.to_dict() # get the default config dict UpperCamelCase_ = BitsAndBytesConfig().to_dict() UpperCamelCase_ = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: UpperCamelCase_ = value return serializable_config_dict
366
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = len(UpperCamelCase_ ) UpperCamelCase_ = len(matrix[0] ) UpperCamelCase_ = min(UpperCamelCase_ , UpperCamelCase_ ) for row in range(UpperCamelCase_ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , UpperCamelCase_ ): UpperCamelCase_ = matrix[col][row] / matrix[row][row] for i in range(UpperCamelCase_ , UpperCamelCase_ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows UpperCamelCase_ = True for i in range(row + 1 , UpperCamelCase_ ): if matrix[i][row] != 0: UpperCamelCase_ , UpperCamelCase_ = matrix[i], matrix[row] UpperCamelCase_ = False break if reduce: rank -= 1 for i in range(UpperCamelCase_ ): UpperCamelCase_ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
328
0
# using dfs for finding eulerian path traversal def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None ) -> List[Any]: UpperCamelCase_ = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: UpperCamelCase_ , UpperCamelCase_ = True, True UpperCamelCase_ = dfs(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) return path def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: UpperCamelCase_ = 0 UpperCamelCase_ = -1 for i in range(UpperCamelCase_ ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 UpperCamelCase_ = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] UpperCamelCase_ , UpperCamelCase_ = check_circuit_or_path(UpperCamelCase_ , UpperCamelCase_ ) if check == 3: print("graph is not Eulerian" ) print("no path" ) return UpperCamelCase_ = 1 if check == 2: UpperCamelCase_ = odd_node print("graph has a Euler path" ) if check == 1: print("graph has a Euler cycle" ) UpperCamelCase_ = dfs(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) print(UpperCamelCase_ ) def lowerCAmelCase_ ( ) -> Optional[int]: UpperCamelCase_ = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} UpperCamelCase_ = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} UpperCamelCase_ = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} UpperCamelCase_ = {1: [2, 3], 2: [1, 3], 3: [1, 2]} UpperCamelCase_ = { 1: [], 2: [] # all degree is zero } UpperCamelCase_ = 10 check_euler(UpperCamelCase_ , UpperCamelCase_ ) check_euler(UpperCamelCase_ , UpperCamelCase_ ) check_euler(UpperCamelCase_ , UpperCamelCase_ ) check_euler(UpperCamelCase_ , UpperCamelCase_ ) check_euler(UpperCamelCase_ , UpperCamelCase_ ) if __name__ == "__main__": main()
367
import math def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(UpperCamelCase_ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. _UpperCAmelCase = 'Enter the base and the power separated by a comma: ' _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) # We find the log of each number, using the function res(), which takes two # arguments. _UpperCAmelCase = res(xa, ya) _UpperCAmelCase = res(xa, ya) # We check for the largest number if resa > resa: print('Largest number is', xa, '^', ya) elif resa > resa: print('Largest number is', xa, '^', ya) else: print('Both are equal')
328
0
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def lowerCAmelCase_ ( UpperCamelCase_ = 100 ) -> int: UpperCamelCase_ = 1 UpperCamelCase_ = 2 for i in range(2 , max_n + 1 ): UpperCamelCase_ = pre_numerator UpperCamelCase_ = 2 * i // 3 if i % 3 == 0 else 1 UpperCamelCase_ = cur_numerator UpperCamelCase_ = e_cont * pre_numerator + temp return sum_digits(UpperCamelCase_ ) if __name__ == "__main__": print(f'''{solution() = }''')
368
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor _UpperCAmelCase = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> List[Any]: if isinstance(UpperCamelCase_ , torch.Tensor ): return image elif isinstance(UpperCamelCase_ , PIL.Image.Image ): UpperCamelCase_ = [image] UpperCamelCase_ = [trans(img.convert("RGB" ) ) for img in image] UpperCamelCase_ = torch.stack(UpperCamelCase_ ) return image class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase_ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[Any]: """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> int: """simple docstring""" UpperCamelCase_ = min(int(num_inference_steps * strength ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[int]=None ) -> List[Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = image.to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase_ = init_latents.shape UpperCamelCase_ = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) # get latents print("add noise to latents at timestep" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.scheduler.add_noise(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = init_latents return latents @torch.no_grad() def __call__( self: Dict , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, PIL.Image.Image] = None , _SCREAMING_SNAKE_CASE: float = 0.8 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: int = 50 , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" self.check_inputs(_SCREAMING_SNAKE_CASE ) # 2. Preprocess image UpperCamelCase_ = preprocess(_SCREAMING_SNAKE_CASE ) # 3. set timesteps self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=self.device ) UpperCamelCase_ , UpperCamelCase_ = self.get_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.device ) UpperCamelCase_ = timesteps[:1].repeat(_SCREAMING_SNAKE_CASE ) # 4. Prepare latent variables UpperCamelCase_ = self.prepare_latents(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.unet.dtype , self.device , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = latents # 5. Denoising loop for t in self.progress_bar(_SCREAMING_SNAKE_CASE ): # 1. predict noise model_output UpperCamelCase_ = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 UpperCamelCase_ = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , use_clipped_model_output=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample UpperCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
328
0
"""simple docstring""" import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers _UpperCAmelCase = 'python tqdm regex requests packaging filelock numpy tokenizers'.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append('dataclasses') if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append('importlib_metadata') for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_=None ) -> List[Any]: require_version(deps[pkg] , UpperCamelCase_ )
369
import re from filelock import FileLock try: import nltk _UpperCAmelCase = True except (ImportError, ModuleNotFoundError): _UpperCAmelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCAmelCase_ ( UpperCamelCase_ ) -> str: re.sub("<n>" , "" , UpperCamelCase_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase_ ) )
328
0
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _UpperCAmelCase = logging.getLogger(__name__) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = np.argmax(UpperCamelCase_ , axis=1 ) return np.sum(outputs == labels ) def lowerCAmelCase_ ( UpperCamelCase_ ): with open(UpperCamelCase_ , encoding="utf_8" ) as f: UpperCamelCase_ = csv.reader(UpperCamelCase_ ) UpperCamelCase_ = [] next(UpperCamelCase_ ) # skip the first line for line in tqdm(UpperCamelCase_ ): output.append((" ".join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = [] for dataset in encoded_datasets: UpperCamelCase_ = len(UpperCamelCase_ ) UpperCamelCase_ = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) UpperCamelCase_ = np.zeros((n_batch, 2) , dtype=np.intaa ) UpperCamelCase_ = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) UpperCamelCase_ = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(UpperCamelCase_ ): UpperCamelCase_ = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] UpperCamelCase_ = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] UpperCamelCase_ = with_conta UpperCamelCase_ = with_conta UpperCamelCase_ = len(UpperCamelCase_ ) - 1 UpperCamelCase_ = len(UpperCamelCase_ ) - 1 UpperCamelCase_ = with_conta UpperCamelCase_ = with_conta UpperCamelCase_ = mc_label UpperCamelCase_ = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(UpperCamelCase_ ) for t in all_inputs ) ) return tensor_datasets def lowerCAmelCase_ ( ): UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("--model_name" , type=UpperCamelCase_ , default="openai-gpt" , help="pretrained model name" ) parser.add_argument("--do_train" , action="store_true" , help="Whether to run training." ) parser.add_argument("--do_eval" , action="store_true" , help="Whether to run eval on the dev set." ) parser.add_argument( "--output_dir" , default=UpperCamelCase_ , type=UpperCamelCase_ , required=UpperCamelCase_ , help="The output directory where the model predictions and checkpoints will be written." , ) parser.add_argument("--train_dataset" , type=UpperCamelCase_ , default="" ) parser.add_argument("--eval_dataset" , type=UpperCamelCase_ , default="" ) parser.add_argument("--seed" , type=UpperCamelCase_ , default=42 ) parser.add_argument("--num_train_epochs" , type=UpperCamelCase_ , default=3 ) parser.add_argument("--train_batch_size" , type=UpperCamelCase_ , default=8 ) parser.add_argument("--eval_batch_size" , type=UpperCamelCase_ , default=16 ) parser.add_argument("--adam_epsilon" , default=1e-8 , type=UpperCamelCase_ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , type=UpperCamelCase_ , default=1 ) parser.add_argument( "--max_steps" , default=-1 , type=UpperCamelCase_ , help=( "If > 0: set total number of training steps to perform. Override num_train_epochs." ) , ) parser.add_argument( "--gradient_accumulation_steps" , type=UpperCamelCase_ , default=1 , help="Number of updates steps to accumulate before performing a backward/update pass." , ) parser.add_argument("--learning_rate" , type=UpperCamelCase_ , default=6.25e-5 ) parser.add_argument("--warmup_steps" , default=0 , type=UpperCamelCase_ , help="Linear warmup over warmup_steps." ) parser.add_argument("--lr_schedule" , type=UpperCamelCase_ , default="warmup_linear" ) parser.add_argument("--weight_decay" , type=UpperCamelCase_ , default=0.01 ) parser.add_argument("--lm_coef" , type=UpperCamelCase_ , default=0.9 ) parser.add_argument("--n_valid" , type=UpperCamelCase_ , default=374 ) parser.add_argument("--server_ip" , type=UpperCamelCase_ , default="" , help="Can be used for distant debugging." ) parser.add_argument("--server_port" , type=UpperCamelCase_ , default="" , help="Can be used for distant debugging." ) UpperCamelCase_ = parser.parse_args() print(UpperCamelCase_ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=UpperCamelCase_ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) UpperCamelCase_ = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) UpperCamelCase_ = torch.cuda.device_count() logger.info("device: {}, n_gpu {}".format(UpperCamelCase_ , UpperCamelCase_ ) ) if not args.do_train and not args.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True." ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset UpperCamelCase_ = ["_start_", "_delimiter_", "_classify_"] UpperCamelCase_ = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(UpperCamelCase_ ) UpperCamelCase_ = tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) UpperCamelCase_ = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(UpperCamelCase_ ) ) model.to(UpperCamelCase_ ) # Load and encode the datasets def tokenize_and_encode(UpperCamelCase_ ): if isinstance(UpperCamelCase_ , UpperCamelCase_ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(UpperCamelCase_ ) ) elif isinstance(UpperCamelCase_ , UpperCamelCase_ ): return obj return [tokenize_and_encode(UpperCamelCase_ ) for o in obj] logger.info("Encoding dataset..." ) UpperCamelCase_ = load_rocstories_dataset(args.train_dataset ) UpperCamelCase_ = load_rocstories_dataset(args.eval_dataset ) UpperCamelCase_ = (train_dataset, eval_dataset) UpperCamelCase_ = tokenize_and_encode(UpperCamelCase_ ) # Compute the max input length for the Transformer UpperCamelCase_ = model.config.n_positions // 2 - 2 UpperCamelCase_ = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) UpperCamelCase_ = min(UpperCamelCase_ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders UpperCamelCase_ = pre_process_datasets(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , *UpperCamelCase_ ) UpperCamelCase_ , UpperCamelCase_ = tensor_datasets[0], tensor_datasets[1] UpperCamelCase_ = TensorDataset(*UpperCamelCase_ ) UpperCamelCase_ = RandomSampler(UpperCamelCase_ ) UpperCamelCase_ = DataLoader(UpperCamelCase_ , sampler=UpperCamelCase_ , batch_size=args.train_batch_size ) UpperCamelCase_ = TensorDataset(*UpperCamelCase_ ) UpperCamelCase_ = SequentialSampler(UpperCamelCase_ ) UpperCamelCase_ = DataLoader(UpperCamelCase_ , sampler=UpperCamelCase_ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: UpperCamelCase_ = args.max_steps UpperCamelCase_ = args.max_steps // (len(UpperCamelCase_ ) // args.gradient_accumulation_steps) + 1 else: UpperCamelCase_ = len(UpperCamelCase_ ) // args.gradient_accumulation_steps * args.num_train_epochs UpperCamelCase_ = list(model.named_parameters() ) UpperCamelCase_ = ["bias", "LayerNorm.bias", "LayerNorm.weight"] UpperCamelCase_ = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], "weight_decay": args.weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], "weight_decay": 0.0}, ] UpperCamelCase_ = AdamW(UpperCamelCase_ , lr=args.learning_rate , eps=args.adam_epsilon ) UpperCamelCase_ = get_linear_schedule_with_warmup( UpperCamelCase_ , num_warmup_steps=args.warmup_steps , num_training_steps=UpperCamelCase_ ) if args.do_train: UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="Epoch" ): UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = tqdm(UpperCamelCase_ , desc="Training" ) for step, batch in enumerate(UpperCamelCase_ ): UpperCamelCase_ = tuple(t.to(UpperCamelCase_ ) for t in batch ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = batch UpperCamelCase_ = model(UpperCamelCase_ , mc_token_ids=UpperCamelCase_ , lm_labels=UpperCamelCase_ , mc_labels=UpperCamelCase_ ) UpperCamelCase_ = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() UpperCamelCase_ = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 UpperCamelCase_ = "Training loss: {:.2e} lr: {:.2e}".format(UpperCamelCase_ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer UpperCamelCase_ = model.module if hasattr(UpperCamelCase_ , "module" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` UpperCamelCase_ = os.path.join(args.output_dir , UpperCamelCase_ ) UpperCamelCase_ = os.path.join(args.output_dir , UpperCamelCase_ ) torch.save(model_to_save.state_dict() , UpperCamelCase_ ) model_to_save.config.to_json_file(UpperCamelCase_ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned UpperCamelCase_ = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) UpperCamelCase_ = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(UpperCamelCase_ ) if args.do_eval: model.eval() UpperCamelCase_ , UpperCamelCase_ = 0, 0 UpperCamelCase_ , UpperCamelCase_ = 0, 0 for batch in tqdm(UpperCamelCase_ , desc="Evaluating" ): UpperCamelCase_ = tuple(t.to(UpperCamelCase_ ) for t in batch ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = batch with torch.no_grad(): UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = model( UpperCamelCase_ , mc_token_ids=UpperCamelCase_ , lm_labels=UpperCamelCase_ , mc_labels=UpperCamelCase_ ) UpperCamelCase_ = mc_logits.detach().cpu().numpy() UpperCamelCase_ = mc_labels.to("cpu" ).numpy() UpperCamelCase_ = accuracy(UpperCamelCase_ , UpperCamelCase_ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 UpperCamelCase_ = eval_loss / nb_eval_steps UpperCamelCase_ = eval_accuracy / nb_eval_examples UpperCamelCase_ = tr_loss / nb_tr_steps if args.do_train else None UpperCamelCase_ = {"eval_loss": eval_loss, "eval_accuracy": eval_accuracy, "train_loss": train_loss} UpperCamelCase_ = os.path.join(args.output_dir , "eval_results.txt" ) with open(UpperCamelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key in sorted(result.keys() ): logger.info(" %s = %s" , UpperCamelCase_ , str(result[key] ) ) writer.write("%s = %s\n" % (key, str(result[key] )) ) if __name__ == "__main__": main()
370
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : Optional[Any] = DiTPipeline _UpperCamelCase : Any = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS _UpperCamelCase : Dict = PipelineTesterMixin.required_optional_params - { '''latents''', '''num_images_per_prompt''', '''callback''', '''callback_steps''', } _UpperCamelCase : Optional[int] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS _UpperCamelCase : Dict = False def lowercase ( self: str ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase_ = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_SCREAMING_SNAKE_CASE , activation_fn="gelu-approximate" , num_embeds_ada_norm=1000 , norm_type="ada_norm_zero" , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = AutoencoderKL() UpperCamelCase_ = DDIMScheduler() UpperCamelCase_ = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler} return components def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: List[str]=0 ) -> Dict: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "class_labels": [1], "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def lowercase ( self: Any ) -> List[str]: """simple docstring""" UpperCamelCase_ = "cpu" UpperCamelCase_ = self.get_dummy_components() UpperCamelCase_ = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(**_SCREAMING_SNAKE_CASE ).images UpperCamelCase_ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) UpperCamelCase_ = np.array([0.29_46, 0.66_01, 0.43_29, 0.32_96, 0.41_44, 0.53_19, 0.72_73, 0.50_13, 0.44_57] ) UpperCamelCase_ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1e-3 ) def lowercase ( self: Optional[int] ) -> Any: """simple docstring""" self._test_inference_batch_single_identical(relax_max_difference=_SCREAMING_SNAKE_CASE , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Optional[Any] ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: Optional[int] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self: Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256" ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella", "white shark", "white wolf"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=40 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( f'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-2 def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512" ) UpperCamelCase_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("cuda" ) UpperCamelCase_ = ["vase", "umbrella"] UpperCamelCase_ = pipe.get_label_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.manual_seed(0 ) UpperCamelCase_ = pipe(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=25 , output_type="np" ).images for word, image in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" f'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1e-1
328
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { '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', 'adapter_layer': 'encoder.layers.*.adapter_layer', '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', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } _UpperCAmelCase = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def lowerCAmelCase_ ( UpperCamelCase_ ) -> Tuple: UpperCamelCase_ = {} with open(UpperCamelCase_ , "r" ) as file: for line_number, line in enumerate(UpperCamelCase_ ): UpperCamelCase_ = line.strip() if line: UpperCamelCase_ = line.split() UpperCamelCase_ = line_number UpperCamelCase_ = words[0] UpperCamelCase_ = value return result def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: for attribute in key.split("." ): UpperCamelCase_ = getattr(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCamelCase_ ): UpperCamelCase_ = PARAM_MAPPING[full_name.split("." )[-1]] UpperCamelCase_ = "param" if weight_type is not None and weight_type != "param": UpperCamelCase_ = getattr(UpperCamelCase_ , UpperCamelCase_ ).shape elif weight_type is not None and weight_type == "param": UpperCamelCase_ = hf_pointer for attribute in hf_param_name.split("." ): UpperCamelCase_ = getattr(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = shape_pointer.shape # let's reduce dimension UpperCamelCase_ = value[0] else: UpperCamelCase_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCamelCase_ = value elif weight_type == "weight_g": UpperCamelCase_ = value elif weight_type == "weight_v": UpperCamelCase_ = value elif weight_type == "bias": UpperCamelCase_ = value elif weight_type == "param": for attribute in hf_param_name.split("." ): UpperCamelCase_ = getattr(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = value else: UpperCamelCase_ = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Any: UpperCamelCase_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCamelCase_ ): UpperCamelCase_ = PARAM_MAPPING[full_name.split("." )[-1]] UpperCamelCase_ = "param" if weight_type is not None and weight_type != "param": UpperCamelCase_ = ".".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": UpperCamelCase_ = ".".join([key, hf_param_name] ) else: UpperCamelCase_ = key UpperCamelCase_ = value if "lm_head" in full_key else value[0] _UpperCAmelCase = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=None ) -> int: UpperCamelCase_ = False for key, mapped_key in MAPPING.items(): UpperCamelCase_ = "wav2vec2." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: UpperCamelCase_ = True if "*" in mapped_key: UpperCamelCase_ = name.split(UpperCamelCase_ )[0].split("." )[-2] UpperCamelCase_ = mapped_key.replace("*" , UpperCamelCase_ ) if "weight_g" in name: UpperCamelCase_ = "weight_g" elif "weight_v" in name: UpperCamelCase_ = "weight_v" elif "bias" in name: UpperCamelCase_ = "bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase_ = "weight" else: UpperCamelCase_ = None if hf_dict is not None: rename_dict(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) else: set_recursively(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) return is_used return is_used def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Any: UpperCamelCase_ = [] UpperCamelCase_ = fairseq_model.state_dict() UpperCamelCase_ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase_ = False if "conv_layers" in name: load_conv_layer( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , hf_model.config.feat_extract_norm == "group" , ) UpperCamelCase_ = True else: UpperCamelCase_ = load_wavaveca_layer(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if not is_used: unused_weights.append(UpperCamelCase_ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> int: UpperCamelCase_ = full_name.split("conv_layers." )[-1] UpperCamelCase_ = name.split("." ) UpperCamelCase_ = int(items[0] ) UpperCamelCase_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCamelCase_ = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCamelCase_ = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) UpperCamelCase_ = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCamelCase_ = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(UpperCamelCase_ ) @torch.no_grad() def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=True , UpperCamelCase_=False ) -> List[str]: if config_path is not None: UpperCamelCase_ = WavaVecaConfig.from_pretrained(UpperCamelCase_ ) else: UpperCamelCase_ = WavaVecaConfig() if is_seq_class: UpperCamelCase_ = read_txt_into_dict(UpperCamelCase_ ) UpperCamelCase_ = idalabel UpperCamelCase_ = WavaVecaForSequenceClassification(UpperCamelCase_ ) UpperCamelCase_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , ) feature_extractor.save_pretrained(UpperCamelCase_ ) elif is_finetuned: if dict_path: UpperCamelCase_ = Dictionary.load(UpperCamelCase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCamelCase_ = target_dict.pad_index UpperCamelCase_ = target_dict.bos_index UpperCamelCase_ = target_dict.eos_index UpperCamelCase_ = len(target_dict.symbols ) UpperCamelCase_ = os.path.join(UpperCamelCase_ , "vocab.json" ) if not os.path.isdir(UpperCamelCase_ ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(UpperCamelCase_ ) ) return os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) UpperCamelCase_ = target_dict.indices # fairseq has the <pad> and <s> switched UpperCamelCase_ = 0 UpperCamelCase_ = 1 with open(UpperCamelCase_ , "w" , encoding="utf-8" ) as vocab_handle: json.dump(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = WavaVecaCTCTokenizer( UpperCamelCase_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=UpperCamelCase_ , ) UpperCamelCase_ = True if config.feat_extract_norm == "layer" else False UpperCamelCase_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , ) UpperCamelCase_ = WavaVecaProcessor(feature_extractor=UpperCamelCase_ , tokenizer=UpperCamelCase_ ) processor.save_pretrained(UpperCamelCase_ ) UpperCamelCase_ = WavaVecaForCTC(UpperCamelCase_ ) else: UpperCamelCase_ = WavaVecaForPreTraining(UpperCamelCase_ ) if is_finetuned or is_seq_class: UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: UpperCamelCase_ = argparse.Namespace(task="audio_pretraining" ) UpperCamelCase_ = fairseq.tasks.setup_task(UpperCamelCase_ ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=UpperCamelCase_ ) UpperCamelCase_ = model[0].eval() recursively_load_weights(UpperCamelCase_ , UpperCamelCase_ , not is_finetuned ) hf_wavavec.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) _UpperCAmelCase = parser.parse_args() _UpperCAmelCase = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
371
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _UpperCamelCase : def __init__( self: str ) -> Any: """simple docstring""" UpperCamelCase_ = "" UpperCamelCase_ = "" UpperCamelCase_ = [] UpperCamelCase_ = 0 UpperCamelCase_ = 256 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 UpperCamelCase_ = 0 def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" UpperCamelCase_ = cva.imread(_SCREAMING_SNAKE_CASE , 0 ) UpperCamelCase_ = copy.deepcopy(self.img ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = plt.hist(self.img.ravel() , 256 , [0, 256] , label="x" ) UpperCamelCase_ = np.sum(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): UpperCamelCase_ = x[i] / self.k self.sk += prk UpperCamelCase_ = (self.L - 1) * self.sk if self.rem != 0: UpperCamelCase_ = int(last % last ) UpperCamelCase_ = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = int(np.ma.count(self.img ) / self.img[1].size ) UpperCamelCase_ = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): UpperCamelCase_ = self.img[j][i] if num != self.last_list[num]: UpperCamelCase_ = self.last_list[num] cva.imwrite("output_data/output.jpg" , self.img ) def lowercase ( self: Any ) -> Optional[Any]: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def lowercase ( self: Tuple ) -> Union[str, Any]: """simple docstring""" cva.imshow("Output-Image" , self.img ) cva.imshow("Input-Image" , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": _UpperCAmelCase = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') _UpperCAmelCase = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
328
0
import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : Tuple = CodeGenTokenizer _UpperCamelCase : int = CodeGenTokenizerFast _UpperCamelCase : Any = True _UpperCamelCase : Optional[Any] = {'''add_prefix_space''': True} _UpperCamelCase : Dict = False def lowercase ( self: Dict ) -> Optional[Any]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase_ = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] UpperCamelCase_ = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) ) UpperCamelCase_ = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] UpperCamelCase_ = {"unk_token": "<unk>"} UpperCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(_SCREAMING_SNAKE_CASE ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(_SCREAMING_SNAKE_CASE ) ) def lowercase ( self: Union[str, Any] , **_SCREAMING_SNAKE_CASE: List[str] ) -> List[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> str: """simple docstring""" kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = "lower newer" UpperCamelCase_ = "lower newer" return input_text, output_text def lowercase ( self: Optional[int] ) -> str: """simple docstring""" UpperCamelCase_ = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase_ = "lower newer" UpperCamelCase_ = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] UpperCamelCase_ = tokenizer.tokenize(_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = tokens + [tokenizer.unk_token] UpperCamelCase_ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def lowercase ( self: int ) -> Optional[Any]: """simple docstring""" if not self.test_rust_tokenizer: return UpperCamelCase_ = self.get_tokenizer() UpperCamelCase_ = self.get_rust_tokenizer(add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = "lower newer" # Testing tokenization UpperCamelCase_ = tokenizer.tokenize(_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = rust_tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Testing conversion to ids without special tokens UpperCamelCase_ = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Testing conversion to ids with special tokens UpperCamelCase_ = self.get_rust_tokenizer(add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Testing the unknown token UpperCamelCase_ = tokens + [rust_tokenizer.unk_token] UpperCamelCase_ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def lowercase ( self: List[Any] , *_SCREAMING_SNAKE_CASE: str , **_SCREAMING_SNAKE_CASE: Optional[int] ) -> Optional[Any]: """simple docstring""" pass def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: List[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCamelCase_ = self.rust_tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) # Simple input UpperCamelCase_ = "This is a simple input" UpperCamelCase_ = ["This is a simple input 1", "This is a simple input 2"] UpperCamelCase_ = ("This is a simple input", "This is a pair") UpperCamelCase_ = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(_SCREAMING_SNAKE_CASE , tokenizer_r.encode , _SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding="max_length" ) # Simple input self.assertRaises(_SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , _SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding="max_length" ) # Simple input self.assertRaises( _SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , _SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding="max_length" , ) # Pair input self.assertRaises(_SCREAMING_SNAKE_CASE , tokenizer_r.encode , _SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding="max_length" ) # Pair input self.assertRaises(_SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , _SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding="max_length" ) # Pair input self.assertRaises( _SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , _SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding="max_length" , ) def lowercase ( self: List[str] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token="<pad>" ) # Simple input UpperCamelCase_ = "This is a simple input" UpperCamelCase_ = ["This is a simple input looooooooong", "This is a simple input"] UpperCamelCase_ = ("This is a simple input", "This is a pair") UpperCamelCase_ = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] UpperCamelCase_ = tokenizer.pad_token_id UpperCamelCase_ = tokenizer(_SCREAMING_SNAKE_CASE , padding="max_length" , max_length=30 , return_tensors="np" ) UpperCamelCase_ = tokenizer(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncate=_SCREAMING_SNAKE_CASE , return_tensors="np" ) UpperCamelCase_ = tokenizer(*_SCREAMING_SNAKE_CASE , padding="max_length" , max_length=60 , return_tensors="np" ) UpperCamelCase_ = tokenizer(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncate=_SCREAMING_SNAKE_CASE , return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def lowercase ( self: Optional[Any] ) -> int: """simple docstring""" UpperCamelCase_ = "$$$" UpperCamelCase_ = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=_SCREAMING_SNAKE_CASE , add_bos_token=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = "This is a simple input" UpperCamelCase_ = ["This is a simple input 1", "This is a simple input 2"] UpperCamelCase_ = tokenizer.bos_token_id UpperCamelCase_ = tokenizer(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = tokenizer(_SCREAMING_SNAKE_CASE ) self.assertEqual(out_s.input_ids[0] , _SCREAMING_SNAKE_CASE ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) UpperCamelCase_ = tokenizer.decode(out_s.input_ids ) UpperCamelCase_ = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , _SCREAMING_SNAKE_CASE ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def lowercase ( self: Optional[Any] ) -> List[str]: """simple docstring""" UpperCamelCase_ = CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono" ) UpperCamelCase_ = "\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#" UpperCamelCase_ = "\nif len_a > len_b: result = a\nelse: result = b" UpperCamelCase_ = tokenizer.encode(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = ["^#", re.escape("<|endoftext|>" ), "^'''", "^\"\"\"", "\n\n\n"] UpperCamelCase_ = tokenizer.decode(_SCREAMING_SNAKE_CASE , truncate_before_pattern=_SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowercase ( self: Tuple ) -> List[Any]: """simple docstring""" pass
350
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _UpperCAmelCase = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' _UpperCAmelCase = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' _UpperCAmelCase = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]: return float((preds == labels).mean() ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_="binary" ) -> Tuple: UpperCamelCase_ = simple_accuracy(UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average=UpperCamelCase_ ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: UpperCamelCase_ = {} for id_pred, label in zip(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = F'''{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}''' UpperCamelCase_ = id_pred["prediction"] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCamelCase_ = [(pred, label)] UpperCamelCase_ , UpperCamelCase_ = [], [] for question, preds_labels in question_map.items(): UpperCamelCase_ , UpperCamelCase_ = zip(*UpperCamelCase_ ) UpperCamelCase_ = fa_score(y_true=UpperCamelCase_ , y_pred=UpperCamelCase_ , average="macro" ) fas.append(UpperCamelCase_ ) UpperCamelCase_ = int(sum(pred == label for pred, label in preds_labels ) == len(UpperCamelCase_ ) ) ems.append(UpperCamelCase_ ) UpperCamelCase_ = float(sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) ) UpperCamelCase_ = sum(UpperCamelCase_ ) / len(UpperCamelCase_ ) UpperCamelCase_ = float(fa_score(y_true=UpperCamelCase_ , y_pred=[id_pred["prediction"] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCamelCase ( datasets.Metric ): def lowercase ( self: Optional[int] ) -> Optional[int]: """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="numpy" if not self.config_name == "record" and not self.config_name == "multirc" else None , ) def lowercase ( self: List[Any] ) -> int: """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "prediction_text": datasets.Value("string" ), }, "references": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "answers": datasets.Sequence(datasets.Value("string" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("int64" ), "paragraph": datasets.Value("int64" ), "question": datasets.Value("int64" ), }, "prediction": datasets.Value("int64" ), }, "references": datasets.Value("int64" ), } else: return { "predictions": datasets.Value("int64" ), "references": datasets.Value("int64" ), } def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> Dict: """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="macro" ) elif self.config_name == "record": UpperCamelCase_ = [ { "qas": [ {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]} for ref in references ] } ] UpperCamelCase_ = {pred["idx"]["query"]: pred["prediction_text"] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" )
328
0
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCAmelCase_ ( UpperCamelCase_ ) -> Tuple: return getitem, k def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: return setitem, k, v def lowerCAmelCase_ ( UpperCamelCase_ ) -> Tuple: return delitem, k def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , *UpperCamelCase_ ) -> Tuple: try: return fun(UpperCamelCase_ , *UpperCamelCase_ ), None except Exception as e: return None, e _UpperCAmelCase = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) _UpperCAmelCase = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] _UpperCAmelCase = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] _UpperCAmelCase = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] _UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] _UpperCAmelCase = [ *[_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_ ( UpperCamelCase_ ) -> Optional[Any]: UpperCamelCase_ = HashMap(initial_block_size=4 ) UpperCamelCase_ = {} for _, (fun, *args) in enumerate(UpperCamelCase_ ): UpperCamelCase_ , UpperCamelCase_ = _run_operation(UpperCamelCase_ , UpperCamelCase_ , *UpperCamelCase_ ) UpperCamelCase_ , UpperCamelCase_ = _run_operation(UpperCamelCase_ , UpperCamelCase_ , *UpperCamelCase_ ) assert my_res == py_res assert str(UpperCamelCase_ ) == str(UpperCamelCase_ ) assert set(UpperCamelCase_ ) == set(UpperCamelCase_ ) assert len(UpperCamelCase_ ) == len(UpperCamelCase_ ) assert set(my.items() ) == set(py.items() ) def lowerCAmelCase_ ( ) -> Union[str, Any]: def is_public(UpperCamelCase_ ) -> bool: return not name.startswith("_" ) UpperCamelCase_ = {name for name in dir({} ) if is_public(UpperCamelCase_ )} UpperCamelCase_ = {name for name in dir(HashMap() ) if is_public(UpperCamelCase_ )} assert dict_public_names > hash_public_names
351
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = '''mgp-str''' def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[int]=[32, 128] , _SCREAMING_SNAKE_CASE: Tuple=4 , _SCREAMING_SNAKE_CASE: Optional[Any]=3 , _SCREAMING_SNAKE_CASE: Optional[int]=27 , _SCREAMING_SNAKE_CASE: Tuple=38 , _SCREAMING_SNAKE_CASE: Tuple=50257 , _SCREAMING_SNAKE_CASE: List[Any]=30522 , _SCREAMING_SNAKE_CASE: Optional[Any]=768 , _SCREAMING_SNAKE_CASE: Dict=12 , _SCREAMING_SNAKE_CASE: List[str]=12 , _SCREAMING_SNAKE_CASE: Dict=4.0 , _SCREAMING_SNAKE_CASE: int=True , _SCREAMING_SNAKE_CASE: Tuple=False , _SCREAMING_SNAKE_CASE: Tuple=1e-5 , _SCREAMING_SNAKE_CASE: Optional[Any]=0.0 , _SCREAMING_SNAKE_CASE: Tuple=0.0 , _SCREAMING_SNAKE_CASE: List[Any]=0.0 , _SCREAMING_SNAKE_CASE: List[str]=False , _SCREAMING_SNAKE_CASE: int=0.02 , **_SCREAMING_SNAKE_CASE: Any , ) -> str: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = image_size UpperCamelCase_ = patch_size UpperCamelCase_ = num_channels UpperCamelCase_ = max_token_length UpperCamelCase_ = num_character_labels UpperCamelCase_ = num_bpe_labels UpperCamelCase_ = num_wordpiece_labels UpperCamelCase_ = hidden_size UpperCamelCase_ = num_hidden_layers UpperCamelCase_ = num_attention_heads UpperCamelCase_ = mlp_ratio UpperCamelCase_ = distilled UpperCamelCase_ = layer_norm_eps UpperCamelCase_ = drop_rate UpperCamelCase_ = qkv_bias UpperCamelCase_ = attn_drop_rate UpperCamelCase_ = drop_path_rate UpperCamelCase_ = output_aa_attentions UpperCamelCase_ = initializer_range
328
0
"""simple docstring""" from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean _UpperCAmelCase = 0 _UpperCAmelCase = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _UpperCAmelCase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right _UpperCAmelCase = tuple[int, int] class _UpperCamelCase : def __init__( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Node | None , ) -> None: """simple docstring""" UpperCamelCase_ = pos_x UpperCamelCase_ = pos_y UpperCamelCase_ = (pos_y, pos_x) UpperCamelCase_ = goal_x UpperCamelCase_ = goal_y UpperCamelCase_ = g_cost UpperCamelCase_ = parent UpperCamelCase_ = self.calculate_heuristic() UpperCamelCase_ = self.g_cost + self.h_cost def lowercase ( self: List[Any] ) -> float: """simple docstring""" UpperCamelCase_ = self.pos_x - self.goal_x UpperCamelCase_ = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(_SCREAMING_SNAKE_CASE ) + abs(_SCREAMING_SNAKE_CASE ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self: List[Any] , _SCREAMING_SNAKE_CASE: Node ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class _UpperCamelCase : def __init__( self: Dict , _SCREAMING_SNAKE_CASE: TPosition , _SCREAMING_SNAKE_CASE: TPosition ) -> Any: """simple docstring""" UpperCamelCase_ = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [self.start] UpperCamelCase_ = [] UpperCamelCase_ = False def lowercase ( self: Union[str, Any] ) -> list[TPosition]: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() UpperCamelCase_ = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(_SCREAMING_SNAKE_CASE ) self.closed_nodes.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.get_successors(_SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path UpperCamelCase_ = self.open_nodes.pop(self.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(_SCREAMING_SNAKE_CASE ) return [self.start.pos] def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Node ) -> list[Node]: """simple docstring""" UpperCamelCase_ = [] for action in delta: UpperCamelCase_ = parent.pos_x + action[1] UpperCamelCase_ = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _SCREAMING_SNAKE_CASE , ) ) return successors def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Node | None ) -> list[TPosition]: """simple docstring""" UpperCamelCase_ = node UpperCamelCase_ = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) UpperCamelCase_ = current_node.parent path.reverse() return path class _UpperCamelCase : def __init__( self: Optional[int] , _SCREAMING_SNAKE_CASE: TPosition , _SCREAMING_SNAKE_CASE: TPosition ) -> None: """simple docstring""" UpperCamelCase_ = AStar(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = AStar(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = False def lowercase ( self: int ) -> list[TPosition]: """simple docstring""" while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() UpperCamelCase_ = self.fwd_astar.open_nodes.pop(0 ) UpperCamelCase_ = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.fwd_astar.closed_nodes.append(_SCREAMING_SNAKE_CASE ) self.bwd_astar.closed_nodes.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = current_bwd_node UpperCamelCase_ = current_fwd_node UpperCamelCase_ = { self.fwd_astar: self.fwd_astar.get_successors(_SCREAMING_SNAKE_CASE ), self.bwd_astar: self.bwd_astar.get_successors(_SCREAMING_SNAKE_CASE ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: # retrieve the best current path UpperCamelCase_ = astar.open_nodes.pop( astar.open_nodes.index(_SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(_SCREAMING_SNAKE_CASE ) else: astar.open_nodes.append(_SCREAMING_SNAKE_CASE ) return [self.fwd_astar.start.pos] def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Node , _SCREAMING_SNAKE_CASE: Node ) -> list[TPosition]: """simple docstring""" UpperCamelCase_ = self.fwd_astar.retrace_path(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.bwd_astar.retrace_path(_SCREAMING_SNAKE_CASE ) bwd_path.pop() bwd_path.reverse() UpperCamelCase_ = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] _UpperCAmelCase = (0, 0) _UpperCAmelCase = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _UpperCAmelCase = time.time() _UpperCAmelCase = AStar(init, goal) _UpperCAmelCase = a_star.search() _UpperCAmelCase = time.time() - start_time print(f'''AStar execution time = {end_time:f} seconds''') _UpperCAmelCase = time.time() _UpperCAmelCase = BidirectionalAStar(init, goal) _UpperCAmelCase = time.time() - bd_start_time print(f'''BidirectionalAStar execution time = {bd_end_time:f} seconds''')
352
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _UpperCAmelCase = logging.getLogger(__name__) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _UpperCamelCase : Optional[str] = field( default=lowerCAmelCase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether tp freeze the encoder.'''} ) _UpperCamelCase : bool = field(default=lowerCAmelCase_ , metadata={'''help''': '''Whether to freeze the embeddings.'''} ) @dataclass class _UpperCamelCase : _UpperCamelCase : str = field( metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''} ) _UpperCamelCase : Optional[str] = field( default='''summarization''' , metadata={'''help''': '''Task name, summarization (or summarization_{dataset} for pegasus) or translation'''} , ) _UpperCamelCase : Optional[int] = 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 : Optional[int] = field( default=1_2_8 , metadata={ '''help''': ( '''The maximum total sequence length for target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for validation target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded. ''' '''This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ''' '''during ``evaluate`` and ``predict``.''' ) } , ) _UpperCamelCase : Optional[int] = field( default=1_4_2 , metadata={ '''help''': ( '''The maximum total sequence length for test target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# training examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# validation examples. -1 means use all.'''} ) _UpperCamelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# test examples. -1 means use all.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Source language id for translation.'''} ) _UpperCamelCase : Optional[str] = field(default=lowerCAmelCase_ , metadata={'''help''': '''Target language id for translation.'''} ) _UpperCamelCase : Optional[int] = field(default=lowerCAmelCase_ , metadata={'''help''': '''# num_beams to use for evaluation.'''} ) _UpperCamelCase : bool = field( default=lowerCAmelCase_ , metadata={'''help''': '''If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'''} , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[int]: logger.info(F'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(F''' {key} = {metrics[key]}''' ) save_json(UpperCamelCase_ , os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) ) def lowerCAmelCase_ ( ) -> Optional[int]: # 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. UpperCamelCase_ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = parser.parse_args_into_dataclasses() check_output_dir(UpperCamelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , UpperCamelCase_ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): assert hasattr(UpperCamelCase_ , UpperCamelCase_ ), F'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(UpperCamelCase_ , UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) UpperCamelCase_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCamelCase_ = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=UpperCamelCase_ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(UpperCamelCase_ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: UpperCamelCase_ = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(UpperCamelCase_ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase_ = tokenizer.lang_code_to_id[data_args.tgt_lang] else: UpperCamelCase_ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(UpperCamelCase_ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) UpperCamelCase_ = SeqaSeqDataset # Get datasets UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_train else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) UpperCamelCase_ = ( dataset_class( UpperCamelCase_ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_predict else None ) # Initialize our Trainer UpperCamelCase_ = ( build_compute_metrics_fn(data_args.task , UpperCamelCase_ ) if training_args.predict_with_generate else None ) UpperCamelCase_ = SeqaSeqTrainer( model=UpperCamelCase_ , args=UpperCamelCase_ , data_args=UpperCamelCase_ , train_dataset=UpperCamelCase_ , eval_dataset=UpperCamelCase_ , data_collator=SeqaSeqDataCollator( UpperCamelCase_ , UpperCamelCase_ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=UpperCamelCase_ , tokenizer=UpperCamelCase_ , ) UpperCamelCase_ = {} # Training if training_args.do_train: logger.info("*** Train ***" ) UpperCamelCase_ = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) UpperCamelCase_ = train_result.metrics UpperCamelCase_ = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("train" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) UpperCamelCase_ = trainer.evaluate(metric_key_prefix="val" ) UpperCamelCase_ = data_args.n_val UpperCamelCase_ = round(metrics["val_loss"] , 4 ) if trainer.is_world_process_zero(): handle_metrics("val" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.do_predict: logger.info("*** Predict ***" ) UpperCamelCase_ = trainer.predict(test_dataset=UpperCamelCase_ , metric_key_prefix="test" ) UpperCamelCase_ = test_output.metrics UpperCamelCase_ = data_args.n_test if trainer.is_world_process_zero(): UpperCamelCase_ = round(metrics["test_loss"] , 4 ) handle_metrics("test" , UpperCamelCase_ , training_args.output_dir ) all_metrics.update(UpperCamelCase_ ) if training_args.predict_with_generate: UpperCamelCase_ = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_ ) UpperCamelCase_ = lmap(str.strip , UpperCamelCase_ ) write_txt_file(UpperCamelCase_ , os.path.join(training_args.output_dir , "test_generations.txt" ) ) if trainer.is_world_process_zero(): save_json(UpperCamelCase_ , os.path.join(training_args.output_dir , "all_results.json" ) ) return all_metrics def lowerCAmelCase_ ( UpperCamelCase_ ) -> Optional[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
328
0
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor _UpperCAmelCase = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> List[Any]: if isinstance(UpperCamelCase_ , torch.Tensor ): return image elif isinstance(UpperCamelCase_ , PIL.Image.Image ): UpperCamelCase_ = [image] UpperCamelCase_ = [trans(img.convert("RGB" ) ) for img in image] UpperCamelCase_ = torch.stack(UpperCamelCase_ ) return image class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase_ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[Any]: """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> int: """simple docstring""" UpperCamelCase_ = min(int(num_inference_steps * strength ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[int]=None ) -> List[Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = image.to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase_ = init_latents.shape UpperCamelCase_ = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) # get latents print("add noise to latents at timestep" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.scheduler.add_noise(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = init_latents return latents @torch.no_grad() def __call__( self: Dict , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, PIL.Image.Image] = None , _SCREAMING_SNAKE_CASE: float = 0.8 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: int = 50 , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" self.check_inputs(_SCREAMING_SNAKE_CASE ) # 2. Preprocess image UpperCamelCase_ = preprocess(_SCREAMING_SNAKE_CASE ) # 3. set timesteps self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=self.device ) UpperCamelCase_ , UpperCamelCase_ = self.get_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.device ) UpperCamelCase_ = timesteps[:1].repeat(_SCREAMING_SNAKE_CASE ) # 4. Prepare latent variables UpperCamelCase_ = self.prepare_latents(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.unet.dtype , self.device , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = latents # 5. Denoising loop for t in self.progress_bar(_SCREAMING_SNAKE_CASE ): # 1. predict noise model_output UpperCamelCase_ = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 UpperCamelCase_ = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , use_clipped_model_output=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample UpperCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
353
def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = int(UpperCamelCase_ ) if n_element < 1: UpperCamelCase_ = ValueError("a should be a positive number" ) raise my_error UpperCamelCase_ = [1] UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = (0, 0, 0) UpperCamelCase_ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _UpperCAmelCase = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') _UpperCAmelCase = hamming(int(n)) print('-----------------------------------------------------') print(f'''The list with nth numbers is: {hamming_numbers}''') print('-----------------------------------------------------')
328
0
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) _UpperCAmelCase = parser.parse_args() _UpperCAmelCase = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) _UpperCAmelCase = CLIPImageProcessor() _UpperCAmelCase = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') _UpperCAmelCase = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
354
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : List[Any] = IFImgaImgSuperResolutionPipeline _UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} _UpperCamelCase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) _UpperCamelCase : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowercase ( self: List[str] ) -> Any: """simple docstring""" return self._get_superresolution_dummy_components() def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[int]=0 ) -> List[Any]: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Any ) -> Union[str, Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowercase ( self: int ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowercase ( self: Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowercase ( self: List[Any] ) -> Union[str, Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowercase ( self: Dict ) -> Any: """simple docstring""" self._test_save_load_local() def lowercase ( self: Any ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
328
0
"""simple docstring""" import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _UpperCAmelCase = False _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = 'ybelkada/fonts' def lowerCAmelCase_ ( ) -> Dict: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: requires_backends(UpperCamelCase_ , ["torch"] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase_ , UpperCamelCase_ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = 36 , UpperCamelCase_ = "black" , UpperCamelCase_ = "white" , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> Image.Image: requires_backends(UpperCamelCase_ , "vision" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase_ ) UpperCamelCase_ = "\n".join(UpperCamelCase_ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase_ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase_ , "Arial.TTF" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase_ , encoding="UTF-8" , size=UpperCamelCase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , UpperCamelCase_ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase_ , UpperCamelCase_ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("RGB" , (image_width, image_height) , UpperCamelCase_ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase_ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase_ , fill=UpperCamelCase_ , font=UpperCamelCase_ ) return image def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> Union[str, Any]: requires_backends(UpperCamelCase_ , "vision" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase_ ) UpperCamelCase_ = render_text(UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase_ ) if infer_channel_dimension_format(UpperCamelCase_ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase_ , ChannelDimension.LAST ) return new_image class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''flattened_patches'''] def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: Optional[Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: dict , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = patch_size["height"], patch_size["width"] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_SCREAMING_SNAKE_CASE ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_SCREAMING_SNAKE_CASE , antialias=_SCREAMING_SNAKE_CASE , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([rows, 1] ).repeat(1 , _SCREAMING_SNAKE_CASE ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([1, columns] ).repeat(_SCREAMING_SNAKE_CASE , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_SCREAMING_SNAKE_CASE , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) return result def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: List[str] ) -> np.ndarray: """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = np.std(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: Optional[Dict[str, int]] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> ImageInput: """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("data_format" , _SCREAMING_SNAKE_CASE ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) UpperCamelCase_ = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) UpperCamelCase_ = kwargs.pop("font_bytes" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("font_path" , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [header_text] * len(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [ render_header(_SCREAMING_SNAKE_CASE , header_text[i] , font_bytes=_SCREAMING_SNAKE_CASE , font_path=_SCREAMING_SNAKE_CASE ) for i, image in enumerate(_SCREAMING_SNAKE_CASE ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_SCREAMING_SNAKE_CASE , max_patches=_SCREAMING_SNAKE_CASE , patch_size=_SCREAMING_SNAKE_CASE ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_outputs
355
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent _UpperCAmelCase = {'UserAgent': UserAgent().random} def lowerCAmelCase_ ( UpperCamelCase_ ) -> dict: UpperCamelCase_ = script.contents[0] UpperCamelCase_ = json.loads(data[data.find("{\"config\"" ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class _UpperCamelCase : def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = f'''https://www.instagram.com/{username}/''' UpperCamelCase_ = self.get_json() def lowercase ( self: Union[str, Any] ) -> dict: """simple docstring""" UpperCamelCase_ = requests.get(self.url , headers=_SCREAMING_SNAKE_CASE ).text UpperCamelCase_ = BeautifulSoup(_SCREAMING_SNAKE_CASE , "html.parser" ).find_all("script" ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self: Tuple ) -> str: """simple docstring""" return f'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self: List[Any] ) -> str: """simple docstring""" return f'''{self.fullname} ({self.username}) is {self.biography}''' @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["username"] @property def lowercase ( self: int ) -> str: """simple docstring""" return self.user_data["full_name"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["biography"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["business_email"] @property def lowercase ( self: List[Any] ) -> str: """simple docstring""" return self.user_data["external_url"] @property def lowercase ( self: List[Any] ) -> int: """simple docstring""" return self.user_data["edge_followed_by"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_follow"]["count"] @property def lowercase ( self: List[str] ) -> int: """simple docstring""" return self.user_data["edge_owner_to_timeline_media"]["count"] @property def lowercase ( self: List[str] ) -> str: """simple docstring""" return self.user_data["profile_pic_url_hd"] @property def lowercase ( self: Optional[int] ) -> bool: """simple docstring""" return self.user_data["is_verified"] @property def lowercase ( self: List[str] ) -> bool: """simple docstring""" return self.user_data["is_private"] def lowerCAmelCase_ ( UpperCamelCase_ = "github" ) -> None: import os if os.environ.get("CI" ): return # test failing on GitHub Actions UpperCamelCase_ = InstagramUser(UpperCamelCase_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , UpperCamelCase_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram." ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = InstagramUser('github') print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
328
0
from __future__ import annotations import string from itertools import cycle, product from pathlib import Path _UpperCAmelCase = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) _UpperCAmelCase = [ord(letter) for letter in string.ascii_lowercase] _UpperCAmelCase = {ord(char) for char in VALID_CHARS} _UpperCAmelCase = ['the', 'be', 'to', 'of', 'and', 'in', 'that', 'have'] def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str | None: UpperCamelCase_ = "" UpperCamelCase_ = 42 UpperCamelCase_ = 42 UpperCamelCase_ = 42 for keychar, cipherchar in zip(cycle(UpperCamelCase_ ) , UpperCamelCase_ ): UpperCamelCase_ = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(UpperCamelCase_ ) return decoded def lowerCAmelCase_ ( UpperCamelCase_ ) -> list[str]: UpperCamelCase_ = [] for key in product(UpperCamelCase_ , repeat=3 ): UpperCamelCase_ = try_key(UpperCamelCase_ , UpperCamelCase_ ) if encoded is not None: possibles.append(UpperCamelCase_ ) return possibles def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> list[str]: return [possible for possible in possibles if common_word in possible.lower()] def lowerCAmelCase_ ( UpperCamelCase_ = "p059_cipher.txt" ) -> int: UpperCamelCase_ = 42 UpperCamelCase_ = 42 UpperCamelCase_ = 42 UpperCamelCase_ = 42 UpperCamelCase_ = Path(UpperCamelCase_ ).parent.joinpath(UpperCamelCase_ ).read_text(encoding="utf-8" ) UpperCamelCase_ = [int(UpperCamelCase_ ) for number in data.strip().split("," )] UpperCamelCase_ = filter_valid_chars(UpperCamelCase_ ) for common_word in COMMON_WORDS: UpperCamelCase_ = filter_common_word(UpperCamelCase_ , UpperCamelCase_ ) if len(UpperCamelCase_ ) == 1: break UpperCamelCase_ = possibles[0] return sum(ord(UpperCamelCase_ ) for char in decoded_text ) if __name__ == "__main__": print(f'''{solution() = }''')
356
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _UpperCAmelCase = False _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = 'ybelkada/fonts' def lowerCAmelCase_ ( ) -> Dict: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: requires_backends(UpperCamelCase_ , ["torch"] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase_ , UpperCamelCase_ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = 36 , UpperCamelCase_ = "black" , UpperCamelCase_ = "white" , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> Image.Image: requires_backends(UpperCamelCase_ , "vision" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase_ ) UpperCamelCase_ = "\n".join(UpperCamelCase_ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase_ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase_ , "Arial.TTF" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase_ , encoding="UTF-8" , size=UpperCamelCase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , UpperCamelCase_ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase_ , UpperCamelCase_ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("RGB" , (image_width, image_height) , UpperCamelCase_ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase_ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase_ , fill=UpperCamelCase_ , font=UpperCamelCase_ ) return image def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> Union[str, Any]: requires_backends(UpperCamelCase_ , "vision" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase_ ) UpperCamelCase_ = render_text(UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase_ ) if infer_channel_dimension_format(UpperCamelCase_ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase_ , ChannelDimension.LAST ) return new_image class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''flattened_patches'''] def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: Optional[Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: dict , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = patch_size["height"], patch_size["width"] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_SCREAMING_SNAKE_CASE ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_SCREAMING_SNAKE_CASE , antialias=_SCREAMING_SNAKE_CASE , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([rows, 1] ).repeat(1 , _SCREAMING_SNAKE_CASE ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([1, columns] ).repeat(_SCREAMING_SNAKE_CASE , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_SCREAMING_SNAKE_CASE , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) return result def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: List[str] ) -> np.ndarray: """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = np.std(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: Optional[Dict[str, int]] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> ImageInput: """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("data_format" , _SCREAMING_SNAKE_CASE ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) UpperCamelCase_ = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) UpperCamelCase_ = kwargs.pop("font_bytes" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("font_path" , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [header_text] * len(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [ render_header(_SCREAMING_SNAKE_CASE , header_text[i] , font_bytes=_SCREAMING_SNAKE_CASE , font_path=_SCREAMING_SNAKE_CASE ) for i, image in enumerate(_SCREAMING_SNAKE_CASE ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_SCREAMING_SNAKE_CASE , max_patches=_SCREAMING_SNAKE_CASE , patch_size=_SCREAMING_SNAKE_CASE ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_outputs
328
0
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _UpperCamelCase : def __init__( self: str , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Optional[Any]=3 , _SCREAMING_SNAKE_CASE: Tuple=32 , _SCREAMING_SNAKE_CASE: Any=3 , _SCREAMING_SNAKE_CASE: Optional[Any]=10 , _SCREAMING_SNAKE_CASE: str=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE: int=[1, 1, 2, 1] , _SCREAMING_SNAKE_CASE: List[str]=True , _SCREAMING_SNAKE_CASE: Optional[int]=True , _SCREAMING_SNAKE_CASE: List[str]="relu" , _SCREAMING_SNAKE_CASE: List[Any]=3 , _SCREAMING_SNAKE_CASE: int=None , ) -> int: """simple docstring""" UpperCamelCase_ = parent UpperCamelCase_ = batch_size UpperCamelCase_ = image_size UpperCamelCase_ = num_channels UpperCamelCase_ = embeddings_size UpperCamelCase_ = hidden_sizes UpperCamelCase_ = depths UpperCamelCase_ = is_training UpperCamelCase_ = use_labels UpperCamelCase_ = hidden_act UpperCamelCase_ = num_labels UpperCamelCase_ = scope UpperCamelCase_ = len(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Any ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase_ = None if self.use_labels: UpperCamelCase_ = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase_ = self.get_config() return config, pixel_values, labels def lowercase ( self: Dict ) -> int: """simple docstring""" return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Optional[Any] ) -> List[str]: """simple docstring""" UpperCamelCase_ = TFResNetModel(config=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = model(_SCREAMING_SNAKE_CASE ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: List[str] ) -> Dict: """simple docstring""" UpperCamelCase_ = self.num_labels UpperCamelCase_ = TFResNetForImageClassification(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase ( self: Optional[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.prepare_config_and_inputs() UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = config_and_inputs UpperCamelCase_ = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _UpperCamelCase : Union[str, Any] = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _UpperCamelCase : Optional[int] = False _UpperCamelCase : List[str] = False _UpperCamelCase : int = False _UpperCamelCase : str = False _UpperCamelCase : List[str] = False def lowercase ( self: str ) -> str: """simple docstring""" UpperCamelCase_ = TFResNetModelTester(self ) UpperCamelCase_ = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE ) def lowercase ( self: str ) -> Optional[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowercase ( self: List[Any] ) -> Union[str, Any]: """simple docstring""" return @unittest.skip(reason="ResNet does not use inputs_embeds" ) def lowercase ( self: List[Any] ) -> str: """simple docstring""" pass @unittest.skip(reason="ResNet does not support input and output embeddings" ) def lowercase ( self: Any ) -> Any: """simple docstring""" pass def lowercase ( self: Union[str, Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase_ = model_class(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase_ = [*signature.parameters.keys()] UpperCamelCase_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def lowercase ( self: List[Any] ) -> Dict: """simple docstring""" UpperCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def lowercase ( self: Any ) -> Optional[int]: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: str ): UpperCamelCase_ = model_class(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase_ = self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_ = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: UpperCamelCase_ = layer_type UpperCamelCase_ = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_ = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] ) -> Dict: """simple docstring""" UpperCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def lowercase ( self: Tuple ) -> Tuple: """simple docstring""" for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase_ = TFResNetModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ) -> str: UpperCamelCase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class _UpperCamelCase ( unittest.TestCase ): @cached_property def lowercase ( self: str ) -> List[str]: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowercase ( self: Union[str, Any] ) -> str: """simple docstring""" UpperCamelCase_ = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCamelCase_ = self.default_image_processor UpperCamelCase_ = prepare_img() UpperCamelCase_ = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="tf" ) # forward pass UpperCamelCase_ = model(**_SCREAMING_SNAKE_CASE ) # verify the logits UpperCamelCase_ = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = tf.constant([-11.10_69, -9.78_77, -8.37_77] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
357
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: Any , _SCREAMING_SNAKE_CASE: int = 768 , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(1 , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(torch.ones(1 , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[Union[str, torch.device]] = None , _SCREAMING_SNAKE_CASE: Optional[torch.dtype] = None , ) -> List[Any]: """simple docstring""" UpperCamelCase_ = nn.Parameter(self.mean.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase_ = nn.Parameter(self.std.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) return self def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = (embeds - self.mean) * 1.0 / self.std return embeds def lowercase ( self: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Dict: """simple docstring""" UpperCamelCase_ = (embeds * self.std) + self.mean return embeds
328
0
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json', } # fmt: off _UpperCAmelCase = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_7, 3_6_6, 4_3_8, 5_3_2, 6_8_5, 7_0_5, 7_9_6, 9_3_0, 1_0_5_8, 1_2_2_0, 1_2_6_7, 1_2_7_9, 1_3_0_3, 1_3_4_3, 1_3_7_7, 1_3_9_1, 1_6_3_5, 1_7_8_2, 1_8_7_5, 2_1_6_2, 2_3_6_1, 2_4_8_8, 3_4_6_7, 4_0_0_8, 4_2_1_1, 4_6_0_0, 4_8_0_8, 5_2_9_9, 5_8_5_5, 6_3_2_9, 7_2_0_3, 9_6_0_9, 9_9_5_9, 1_0_5_6_3, 1_0_7_8_6, 1_1_4_2_0, 1_1_7_0_9, 1_1_9_0_7, 1_3_1_6_3, 1_3_6_9_7, 1_3_7_0_0, 1_4_8_0_8, 1_5_3_0_6, 1_6_4_1_0, 1_6_7_9_1, 1_7_9_9_2, 1_9_2_0_3, 1_9_5_1_0, 2_0_7_2_4, 2_2_3_0_5, 2_2_9_3_5, 2_7_0_0_7, 3_0_1_0_9, 3_0_4_2_0, 3_3_4_0_9, 3_4_9_4_9, 4_0_2_8_3, 4_0_4_9_3, 4_0_5_4_9, 4_7_2_8_2, 4_9_1_4_6, 5_0_2_5_7, 5_0_3_5_9, 5_0_3_6_0, 5_0_3_6_1 ] _UpperCAmelCase = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_9, 5_0_3, 5_2_2, 5_4_2, 8_7_3, 8_9_3, 9_0_2, 9_1_8, 9_2_2, 9_3_1, 1_3_5_0, 1_8_5_3, 1_9_8_2, 2_4_6_0, 2_6_2_7, 3_2_4_6, 3_2_5_3, 3_2_6_8, 3_5_3_6, 3_8_4_6, 3_9_6_1, 4_1_8_3, 4_6_6_7, 6_5_8_5, 6_6_4_7, 7_2_7_3, 9_0_6_1, 9_3_8_3, 1_0_4_2_8, 1_0_9_2_9, 1_1_9_3_8, 1_2_0_3_3, 1_2_3_3_1, 1_2_5_6_2, 1_3_7_9_3, 1_4_1_5_7, 1_4_6_3_5, 1_5_2_6_5, 1_5_6_1_8, 1_6_5_5_3, 1_6_6_0_4, 1_8_3_6_2, 1_8_9_5_6, 2_0_0_7_5, 2_1_6_7_5, 2_2_5_2_0, 2_6_1_3_0, 2_6_1_6_1, 2_6_4_3_5, 2_8_2_7_9, 2_9_4_6_4, 3_1_6_5_0, 3_2_3_0_2, 3_2_4_7_0, 3_6_8_6_5, 4_2_8_6_3, 4_7_4_2_5, 4_9_8_7_0, 5_0_2_5_4, 5_0_2_5_8, 5_0_3_6_0, 5_0_3_6_1, 5_0_3_6_2 ] class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = '''whisper''' _UpperCamelCase : Optional[int] = ['''past_key_values'''] _UpperCamelCase : List[str] = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self: int , _SCREAMING_SNAKE_CASE: List[str]=51865 , _SCREAMING_SNAKE_CASE: List[str]=80 , _SCREAMING_SNAKE_CASE: List[Any]=6 , _SCREAMING_SNAKE_CASE: Any=4 , _SCREAMING_SNAKE_CASE: List[str]=6 , _SCREAMING_SNAKE_CASE: List[Any]=4 , _SCREAMING_SNAKE_CASE: int=1536 , _SCREAMING_SNAKE_CASE: str=1536 , _SCREAMING_SNAKE_CASE: Optional[int]=0.0 , _SCREAMING_SNAKE_CASE: Optional[int]=0.0 , _SCREAMING_SNAKE_CASE: Dict=50257 , _SCREAMING_SNAKE_CASE: Dict=True , _SCREAMING_SNAKE_CASE: Tuple=True , _SCREAMING_SNAKE_CASE: int="gelu" , _SCREAMING_SNAKE_CASE: Dict=256 , _SCREAMING_SNAKE_CASE: Union[str, Any]=0.0 , _SCREAMING_SNAKE_CASE: List[Any]=0.0 , _SCREAMING_SNAKE_CASE: List[Any]=0.0 , _SCREAMING_SNAKE_CASE: List[str]=0.02 , _SCREAMING_SNAKE_CASE: List[Any]=False , _SCREAMING_SNAKE_CASE: Tuple=1500 , _SCREAMING_SNAKE_CASE: Any=448 , _SCREAMING_SNAKE_CASE: Dict=50256 , _SCREAMING_SNAKE_CASE: Any=50256 , _SCREAMING_SNAKE_CASE: Dict=50256 , _SCREAMING_SNAKE_CASE: Optional[int]=None , _SCREAMING_SNAKE_CASE: str=[220, 50256] , _SCREAMING_SNAKE_CASE: Dict=False , _SCREAMING_SNAKE_CASE: str=256 , _SCREAMING_SNAKE_CASE: List[str]=False , _SCREAMING_SNAKE_CASE: List[str]=0.05 , _SCREAMING_SNAKE_CASE: Optional[int]=10 , _SCREAMING_SNAKE_CASE: str=2 , _SCREAMING_SNAKE_CASE: List[str]=0.0 , _SCREAMING_SNAKE_CASE: List[str]=10 , _SCREAMING_SNAKE_CASE: List[str]=0 , _SCREAMING_SNAKE_CASE: str=7 , **_SCREAMING_SNAKE_CASE: Tuple , ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = vocab_size UpperCamelCase_ = num_mel_bins UpperCamelCase_ = d_model UpperCamelCase_ = encoder_layers UpperCamelCase_ = encoder_attention_heads UpperCamelCase_ = decoder_layers UpperCamelCase_ = decoder_attention_heads UpperCamelCase_ = decoder_ffn_dim UpperCamelCase_ = encoder_ffn_dim UpperCamelCase_ = dropout UpperCamelCase_ = attention_dropout UpperCamelCase_ = activation_dropout UpperCamelCase_ = activation_function UpperCamelCase_ = init_std UpperCamelCase_ = encoder_layerdrop UpperCamelCase_ = decoder_layerdrop UpperCamelCase_ = use_cache UpperCamelCase_ = encoder_layers UpperCamelCase_ = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase_ = max_source_positions UpperCamelCase_ = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. UpperCamelCase_ = classifier_proj_size UpperCamelCase_ = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCamelCase_ = apply_spec_augment UpperCamelCase_ = mask_time_prob UpperCamelCase_ = mask_time_length UpperCamelCase_ = mask_time_min_masks UpperCamelCase_ = mask_feature_prob UpperCamelCase_ = mask_feature_length UpperCamelCase_ = mask_feature_min_masks UpperCamelCase_ = median_filter_width super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , is_encoder_decoder=_SCREAMING_SNAKE_CASE , decoder_start_token_id=_SCREAMING_SNAKE_CASE , suppress_tokens=_SCREAMING_SNAKE_CASE , begin_suppress_tokens=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) class _UpperCamelCase ( lowerCAmelCase_ ): @property def lowercase ( self: Dict ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" UpperCamelCase_ = OrderedDict( [ ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}), ] ) if self.use_past: UpperCamelCase_ = {0: "batch"} else: UpperCamelCase_ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(_SCREAMING_SNAKE_CASE , direction="inputs" ) return common_inputs def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: int = -1 , _SCREAMING_SNAKE_CASE: bool = False , _SCREAMING_SNAKE_CASE: Optional["TensorType"] = None , _SCREAMING_SNAKE_CASE: int = 22050 , _SCREAMING_SNAKE_CASE: float = 5.0 , _SCREAMING_SNAKE_CASE: int = 220 , ) -> Mapping[str, Any]: """simple docstring""" UpperCamelCase_ = OrderedDict() UpperCamelCase_ = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE , sampling_rate=_SCREAMING_SNAKE_CASE , time_duration=_SCREAMING_SNAKE_CASE , frequency=_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = encoder_inputs["input_features"].shape[2] UpperCamelCase_ = encoder_sequence_length // 2 if self.use_past else seq_length UpperCamelCase_ = super().generate_dummy_inputs( preprocessor.tokenizer , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = encoder_inputs.pop("input_features" ) UpperCamelCase_ = decoder_inputs.pop("decoder_input_ids" ) if "past_key_values" in decoder_inputs: UpperCamelCase_ = decoder_inputs.pop("past_key_values" ) return dummy_inputs @property def lowercase ( self: Any ) -> float: """simple docstring""" return 1e-3
358
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _UpperCAmelCase = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) _UpperCAmelCase = logging.getLogger() def lowerCAmelCase_ ( ) -> Optional[int]: UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCamelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_="eval" ) -> Any: UpperCamelCase_ = os.path.join(UpperCamelCase_ , F'''{split}_results.json''' ) if os.path.exists(UpperCamelCase_ ): with open(UpperCamelCase_ , "r" ) as f: return json.load(UpperCamelCase_ ) raise ValueError(F'''can\'t find {path}''' ) _UpperCAmelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _UpperCamelCase ( lowerCAmelCase_ ): def lowercase ( self: Optional[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_glue.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) @slow def lowercase ( self: int ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_clm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 100 ) @slow def lowercase ( self: Any ) -> Tuple: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_summarization_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE , split="test" ) self.assertGreaterEqual(result["test_rouge1"] , 10 ) self.assertGreaterEqual(result["test_rouge2"] , 2 ) self.assertGreaterEqual(result["test_rougeL"] , 7 ) self.assertGreaterEqual(result["test_rougeLsum"] , 7 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["eval_perplexity"] , 42 ) @slow def lowercase ( self: Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_ta_mlm_flax.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.42 ) @slow def lowercase ( self: str ) -> int: """simple docstring""" UpperCamelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_flax_ner.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertGreaterEqual(result["eval_f1"] , 0.3 ) @slow def lowercase ( self: Union[str, Any] ) -> Any: """simple docstring""" UpperCamelCase_ = self.get_auto_remove_tmp_dir() UpperCamelCase_ = f''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(_SCREAMING_SNAKE_CASE , "argv" , _SCREAMING_SNAKE_CASE ): run_qa.main() UpperCamelCase_ = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["eval_f1"] , 30 ) self.assertGreaterEqual(result["eval_exact"] , 30 )
328
0
def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: UpperCamelCase_ = hex_num.strip() if not hex_num: raise ValueError("No value was passed to the function" ) UpperCamelCase_ = hex_num[0] == "-" if is_negative: UpperCamelCase_ = hex_num[1:] try: UpperCamelCase_ = int(UpperCamelCase_ , 16 ) except ValueError: raise ValueError("Invalid value was passed to the function" ) UpperCamelCase_ = "" while int_num > 0: UpperCamelCase_ = str(int_num % 2 ) + bin_str int_num >>= 1 return int(("-" + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
359
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( UpperCamelCase_ ) -> int: for param in module.parameters(): UpperCamelCase_ = False def lowerCAmelCase_ ( ) -> Dict: UpperCamelCase_ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): UpperCamelCase_ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def lowerCAmelCase_ ( ) -> List[str]: UpperCamelCase_ = datetime.now() UpperCamelCase_ = current_time.strftime("%H:%M:%S" ) return timestamp
328
0
def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> int: return abs(UpperCamelCase_ ) if a == 0 else greatest_common_divisor(b % a , UpperCamelCase_ ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. UpperCamelCase_ , UpperCamelCase_ = y, x % y return abs(UpperCamelCase_ ) def lowerCAmelCase_ ( ) -> Any: try: UpperCamelCase_ = input("Enter two integers separated by comma (,): " ).split("," ) UpperCamelCase_ = int(nums[0] ) UpperCamelCase_ = int(nums[1] ) print( F'''greatest_common_divisor({num_a}, {num_a}) = ''' F'''{greatest_common_divisor(UpperCamelCase_ , UpperCamelCase_ )}''' ) print(F'''By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(UpperCamelCase_ , UpperCamelCase_ )}''' ) except (IndexError, UnboundLocalError, ValueError): print("Wrong input" ) if __name__ == "__main__": main()
360
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 _UpperCAmelCase = '▁' _UpperCAmelCase = {'vocab_file': 'spiece.model'} _UpperCAmelCase = { 'vocab_file': {'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'} } _UpperCAmelCase = { 'google/pegasus-xsum': 5_1_2, } _UpperCAmelCase = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = VOCAB_FILES_NAMES _UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[int] = ['''input_ids''', '''attention_mask'''] def __init__( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: str="<pad>" , _SCREAMING_SNAKE_CASE: Optional[Any]="</s>" , _SCREAMING_SNAKE_CASE: Any="<unk>" , _SCREAMING_SNAKE_CASE: int="<mask_2>" , _SCREAMING_SNAKE_CASE: List[Any]="<mask_1>" , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: Optional[int]=103 , _SCREAMING_SNAKE_CASE: Optional[Dict[str, Any]] = None , **_SCREAMING_SNAKE_CASE: Dict , ) -> None: """simple docstring""" UpperCamelCase_ = offset if additional_special_tokens is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError( f'''additional_special_tokens should be of type {type(_SCREAMING_SNAKE_CASE )}, but is''' f''' {type(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'''<unk_{i}>''' for i in range(len(_SCREAMING_SNAKE_CASE ) , self.offset - 1 ) ] if len(set(_SCREAMING_SNAKE_CASE ) ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError( "Please make sure that the provided additional_special_tokens do not contain an incorrectly" f''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) UpperCamelCase_ = additional_special_tokens_extended else: UpperCamelCase_ = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'''<unk_{i}>''' for i in range(2 , self.offset )] UpperCamelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token_sent=_SCREAMING_SNAKE_CASE , offset=_SCREAMING_SNAKE_CASE , additional_special_tokens=_SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = mask_token_sent UpperCamelCase_ = vocab_file UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_SCREAMING_SNAKE_CASE ) # add special tokens to encoder dict UpperCamelCase_ = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) UpperCamelCase_ = {v: k for k, v in self.encoder.items()} @property def lowercase ( self: Dict ) -> int: """simple docstring""" return len(self.sp_model ) + self.offset def lowercase ( self: int ) -> Dict[str, int]: """simple docstring""" UpperCamelCase_ = {self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self: Optional[int] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = self.__dict__.copy() UpperCamelCase_ = None return state def __setstate__( self: List[Any] , _SCREAMING_SNAKE_CASE: List[Any] ) -> Any: """simple docstring""" UpperCamelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCamelCase_ = {} UpperCamelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: str ) -> List[str]: """simple docstring""" return self.sp_model.encode(_SCREAMING_SNAKE_CASE , out_type=_SCREAMING_SNAKE_CASE ) def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: str ) -> int: """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] UpperCamelCase_ = self.sp_model.piece_to_id(_SCREAMING_SNAKE_CASE ) return sp_id + self.offset def lowercase ( self: str , _SCREAMING_SNAKE_CASE: int ) -> str: """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: UpperCamelCase_ = self.sp_model.IdToPiece(index - self.offset ) return token def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = [] UpperCamelCase_ = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) + token UpperCamelCase_ = [] else: current_sub_tokens.append(_SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE ) return out_string.strip() def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Optional[int]=False ) -> Union[str, Any]: """simple docstring""" return 1 def lowercase ( self: int , _SCREAMING_SNAKE_CASE: str ) -> str: """simple docstring""" UpperCamelCase_ = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: List , _SCREAMING_SNAKE_CASE: Optional[List] = None , _SCREAMING_SNAKE_CASE: bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) elif token_ids_a is None: return self._special_token_mask(_SCREAMING_SNAKE_CASE ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any]=None ) -> List[int]: """simple docstring""" if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def lowercase ( self: str , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCamelCase_ = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(_SCREAMING_SNAKE_CASE , "wb" ) as fi: UpperCamelCase_ = self.sp_model.serialized_model_proto() fi.write(_SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
328
0
# flake8: noqa # Lint as: python3 _UpperCAmelCase = [ 'VerificationMode', 'Version', 'disable_progress_bar', 'enable_progress_bar', 'is_progress_bar_enabled', 'experimental', ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
361
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase = { 'configuration_tapas': ['TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TapasConfig'], 'tokenization_tapas': ['TapasTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TapasForMaskedLM', 'TapasForQuestionAnswering', 'TapasForSequenceClassification', 'TapasModel', 'TapasPreTrainedModel', 'load_tf_weights_in_tapas', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFTapasForMaskedLM', 'TFTapasForQuestionAnswering', 'TFTapasForSequenceClassification', 'TFTapasModel', 'TFTapasPreTrainedModel', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
328
0
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class _UpperCamelCase ( unittest.TestCase ): @parameterized.expand([(None,), ("foo.json",)] ) def lowercase ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> Dict: """simple docstring""" UpperCamelCase_ = GenerationConfig( do_sample=_SCREAMING_SNAKE_CASE , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_SCREAMING_SNAKE_CASE , config_name=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE , config_name=_SCREAMING_SNAKE_CASE ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , _SCREAMING_SNAKE_CASE ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , _SCREAMING_SNAKE_CASE ) def lowercase ( self: Any ) -> Any: """simple docstring""" UpperCamelCase_ = AutoConfig.from_pretrained("gpt2" ) UpperCamelCase_ = GenerationConfig.from_model_config(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def lowercase ( self: Any ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ = GenerationConfig() UpperCamelCase_ = { "max_new_tokens": 1024, "foo": "bar", } UpperCamelCase_ = copy.deepcopy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = generation_config.update(**_SCREAMING_SNAKE_CASE ) # update_kwargs was not modified (no side effects) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(_SCREAMING_SNAKE_CASE , {"foo": "bar"} ) def lowercase ( self: Optional[Any] ) -> Dict: """simple docstring""" UpperCamelCase_ = GenerationConfig() UpperCamelCase_ = "bar" with tempfile.TemporaryDirectory("test-generation-config" ) as tmp_dir: generation_config.save_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , "bar" ) UpperCamelCase_ = GenerationConfig.from_model_config(_SCREAMING_SNAKE_CASE ) assert not hasattr(_SCREAMING_SNAKE_CASE , "foo" ) # no new kwargs should be initialized if from config def lowercase ( self: List[Any] ) -> str: """simple docstring""" UpperCamelCase_ = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , _SCREAMING_SNAKE_CASE ) self.assertEqual(default_config.num_beams , 1 ) UpperCamelCase_ = GenerationConfig( do_sample=_SCREAMING_SNAKE_CASE , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , _SCREAMING_SNAKE_CASE ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = GenerationConfig.from_pretrained(_SCREAMING_SNAKE_CASE , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , _SCREAMING_SNAKE_CASE ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class _UpperCamelCase ( unittest.TestCase ): @classmethod def lowercase ( cls: int ) -> List[Any]: """simple docstring""" UpperCamelCase_ = TOKEN HfFolder.save_token(_SCREAMING_SNAKE_CASE ) @classmethod def lowercase ( cls: List[Any] ) -> str: """simple docstring""" try: delete_repo(token=cls._token , repo_id="test-generation-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-generation-config-org" ) except HTTPError: pass def lowercase ( self: Union[str, Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ = GenerationConfig( do_sample=_SCREAMING_SNAKE_CASE , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub("test-generation-config" , use_auth_token=self._token ) UpperCamelCase_ = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_SCREAMING_SNAKE_CASE , getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # Reset repo delete_repo(token=self._token , repo_id="test-generation-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _SCREAMING_SNAKE_CASE , repo_id="test-generation-config" , push_to_hub=_SCREAMING_SNAKE_CASE , use_auth_token=self._token ) UpperCamelCase_ = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_SCREAMING_SNAKE_CASE , getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) def lowercase ( self: Optional[int] ) -> List[str]: """simple docstring""" UpperCamelCase_ = GenerationConfig( do_sample=_SCREAMING_SNAKE_CASE , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub("valid_org/test-generation-config-org" , use_auth_token=self._token ) UpperCamelCase_ = GenerationConfig.from_pretrained("valid_org/test-generation-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_SCREAMING_SNAKE_CASE , getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-generation-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _SCREAMING_SNAKE_CASE , repo_id="valid_org/test-generation-config-org" , push_to_hub=_SCREAMING_SNAKE_CASE , use_auth_token=self._token ) UpperCamelCase_ = GenerationConfig.from_pretrained("valid_org/test-generation-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_SCREAMING_SNAKE_CASE , getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
362
import argparse import json from tqdm import tqdm def lowerCAmelCase_ ( ) -> Tuple: UpperCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--src_path" , type=UpperCamelCase_ , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , ) parser.add_argument( "--evaluation_set" , type=UpperCamelCase_ , help="where to store parsed evaluation_set file" , ) parser.add_argument( "--gold_data_path" , type=UpperCamelCase_ , help="where to store parsed gold_data_path file" , ) UpperCamelCase_ = parser.parse_args() with open(args.src_path , "r" ) as src_file, open(args.evaluation_set , "w" ) as eval_file, open( args.gold_data_path , "w" ) as gold_file: UpperCamelCase_ = json.load(UpperCamelCase_ ) for dpr_record in tqdm(UpperCamelCase_ ): UpperCamelCase_ = dpr_record["question"] UpperCamelCase_ = [context["title"] for context in dpr_record["positive_ctxs"]] eval_file.write(question + "\n" ) gold_file.write("\t".join(UpperCamelCase_ ) + "\n" ) if __name__ == "__main__": main()
328
0
import math def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> List[str]: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(UpperCamelCase_ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. _UpperCAmelCase = 'Enter the base and the power separated by a comma: ' _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) _UpperCAmelCase , _UpperCAmelCase = map(int, input(prompt).split(',')) # We find the log of each number, using the function res(), which takes two # arguments. _UpperCAmelCase = res(xa, ya) _UpperCAmelCase = res(xa, ya) # We check for the largest number if resa > resa: print('Largest number is', xa, '^', ya) elif resa > resa: print('Largest number is', xa, '^', ya) else: print('Both are equal')
363
import requests from bsa import BeautifulSoup def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = BeautifulSoup(requests.get(UpperCamelCase_ , params=UpperCamelCase_ ).content , "html.parser" ) UpperCamelCase_ = soup.find("div" , attrs={"class": "gs_ri"} ) UpperCamelCase_ = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": _UpperCAmelCase = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
328
0
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed _UpperCAmelCase = logging.getLogger(__name__) def lowerCAmelCase_ ( UpperCamelCase_=2 , UpperCamelCase_=3 , UpperCamelCase_=16 , UpperCamelCase_ = 10 , UpperCamelCase_ = 2 ) -> Optional[int]: def get_dataset(UpperCamelCase_ ): UpperCamelCase_ = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(UpperCamelCase_ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) UpperCamelCase_ = get_dataset(UpperCamelCase_ ) UpperCamelCase_ = get_dataset(UpperCamelCase_ ) UpperCamelCase_ = DataLoader(UpperCamelCase_ , shuffle=UpperCamelCase_ , batch_size=UpperCamelCase_ , num_workers=4 ) UpperCamelCase_ = DataLoader(UpperCamelCase_ , shuffle=UpperCamelCase_ , batch_size=UpperCamelCase_ , num_workers=4 ) return (train_dataloader, valid_dataloader) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None ) -> Any: UpperCamelCase_ = [] for epoch in range(UpperCamelCase_ ): # Train quickly model.train() for batch in dataloader: UpperCamelCase_ , UpperCamelCase_ = batch UpperCamelCase_ = model(UpperCamelCase_ ) UpperCamelCase_ = torch.nn.functional.mse_loss(UpperCamelCase_ , UpperCamelCase_ ) accelerator.backward(UpperCamelCase_ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class _UpperCamelCase ( nn.Module ): def __init__( self: Tuple ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.randn(1 ) ) UpperCamelCase_ = nn.Parameter(torch.randn(1 ) ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" return x * self.a + self.b class _UpperCamelCase ( unittest.TestCase ): def lowercase ( self: List[Any] ) -> List[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase_ = DummyModel() UpperCamelCase_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase_ , UpperCamelCase_ = dummy_dataloaders() UpperCamelCase_ = ProjectConfiguration(total_limit=1 , project_dir=_SCREAMING_SNAKE_CASE , automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE ) # Train baseline UpperCamelCase_ = Accelerator(project_config=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def lowercase ( self: Tuple ) -> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase_ = DummyModel() UpperCamelCase_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase_ , UpperCamelCase_ = dummy_dataloaders() # Train baseline UpperCamelCase_ = Accelerator() UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save initial UpperCamelCase_ = os.path.join(_SCREAMING_SNAKE_CASE , "initial" ) accelerator.save_state(_SCREAMING_SNAKE_CASE ) ((UpperCamelCase_) , (UpperCamelCase_)) = model.a.item(), model.b.item() UpperCamelCase_ = optimizer.state_dict() UpperCamelCase_ = train(3 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ((UpperCamelCase_) , (UpperCamelCase_)) = model.a.item(), model.b.item() UpperCamelCase_ = optimizer.state_dict() # Train partially set_seed(42 ) UpperCamelCase_ = DummyModel() UpperCamelCase_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase_ , UpperCamelCase_ = dummy_dataloaders() UpperCamelCase_ = Accelerator() UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) accelerator.load_state(_SCREAMING_SNAKE_CASE ) ((UpperCamelCase_) , (UpperCamelCase_)) = model.a.item(), model.b.item() UpperCamelCase_ = optimizer.state_dict() self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = train(2 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save everything UpperCamelCase_ = os.path.join(_SCREAMING_SNAKE_CASE , "checkpoint" ) accelerator.save_state(_SCREAMING_SNAKE_CASE ) # Load everything back in and make sure all states work accelerator.load_state(_SCREAMING_SNAKE_CASE ) test_rands += train(1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ((UpperCamelCase_) , (UpperCamelCase_)) = model.a.item(), model.b.item() UpperCamelCase_ = optimizer.state_dict() self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowercase ( self: List[Any] ) -> int: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase_ = DummyModel() UpperCamelCase_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase_ , UpperCamelCase_ = dummy_dataloaders() UpperCamelCase_ = ProjectConfiguration(automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE ) # Train baseline UpperCamelCase_ = Accelerator(project_dir=_SCREAMING_SNAKE_CASE , project_config=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save initial accelerator.save_state() ((UpperCamelCase_) , (UpperCamelCase_)) = model.a.item(), model.b.item() UpperCamelCase_ = optimizer.state_dict() UpperCamelCase_ = train(3 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ((UpperCamelCase_) , (UpperCamelCase_)) = model.a.item(), model.b.item() UpperCamelCase_ = optimizer.state_dict() # Train partially set_seed(42 ) UpperCamelCase_ = DummyModel() UpperCamelCase_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase_ , UpperCamelCase_ = dummy_dataloaders() UpperCamelCase_ = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = Accelerator(project_dir=_SCREAMING_SNAKE_CASE , project_config=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) accelerator.load_state(os.path.join(_SCREAMING_SNAKE_CASE , "checkpoints" , "checkpoint_0" ) ) ((UpperCamelCase_) , (UpperCamelCase_)) = model.a.item(), model.b.item() UpperCamelCase_ = optimizer.state_dict() self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = train(2 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(_SCREAMING_SNAKE_CASE , "checkpoints" , "checkpoint_1" ) ) test_rands += train(1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ((UpperCamelCase_) , (UpperCamelCase_)) = model.a.item(), model.b.item() UpperCamelCase_ = optimizer.state_dict() self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowercase ( self: str ) -> Tuple: """simple docstring""" UpperCamelCase_ = torch.tensor([1, 2, 3] ) UpperCamelCase_ = torch.tensor([2, 3, 4] ) UpperCamelCase_ = DummyModel() UpperCamelCase_ = torch.optim.Adam(net.parameters() ) UpperCamelCase_ = Accelerator() with self.assertRaises(_SCREAMING_SNAKE_CASE ) as ve: accelerator.register_for_checkpointing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = str(ve.exception ) self.assertTrue("Item at index 0" in message ) self.assertTrue("Item at index 1" in message ) self.assertFalse("Item at index 2" in message ) self.assertFalse("Item at index 3" in message ) def lowercase ( self: Tuple ) -> List[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase_ = DummyModel() UpperCamelCase_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase_ = torch.optim.lr_scheduler.StepLR(_SCREAMING_SNAKE_CASE , step_size=1 , gamma=0.99 ) UpperCamelCase_ , UpperCamelCase_ = dummy_dataloaders() UpperCamelCase_ = ProjectConfiguration(automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE ) # Train baseline UpperCamelCase_ = Accelerator(project_dir=_SCREAMING_SNAKE_CASE , project_config=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save initial accelerator.save_state() UpperCamelCase_ = scheduler.state_dict() train(3 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertNotEqual(_SCREAMING_SNAKE_CASE , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(_SCREAMING_SNAKE_CASE , "checkpoints" , "checkpoint_0" ) ) self.assertEqual(_SCREAMING_SNAKE_CASE , scheduler.state_dict() ) def lowercase ( self: Dict ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase_ = DummyModel() UpperCamelCase_ = ProjectConfiguration(automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE , total_limit=2 ) # Train baseline UpperCamelCase_ = Accelerator(project_dir=_SCREAMING_SNAKE_CASE , project_config=_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = accelerator.prepare(_SCREAMING_SNAKE_CASE ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , "checkpoints" , "checkpoint_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , "checkpoints" , "checkpoint_9" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , "checkpoints" , "checkpoint_10" ) ) ) @require_cuda def lowercase ( self: List[str] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ = ["torchrun", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] execute_subprocess_async(_SCREAMING_SNAKE_CASE , env=os.environ.copy() ) if __name__ == "__main__": _UpperCAmelCase = '/tmp/accelerate/state_checkpointing' _UpperCAmelCase = DummyModel() _UpperCAmelCase = torch.optim.Adam(params=model.parameters(), lr=1e-3) _UpperCAmelCase = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) _UpperCAmelCase , _UpperCAmelCase = dummy_dataloaders() _UpperCAmelCase = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline _UpperCAmelCase = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) _UpperCAmelCase , _UpperCAmelCase = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: _UpperCAmelCase = group['params'][0].device break assert param_device.type == accelerator.device.type _UpperCAmelCase = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: _UpperCAmelCase = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: _UpperCAmelCase = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
364
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ): @register_to_config def __init__( self: List[str] , *, _SCREAMING_SNAKE_CASE: int = 4 , _SCREAMING_SNAKE_CASE: int = 768 , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: str , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase_ = nn.Parameter(torch.zeros(_SCREAMING_SNAKE_CASE ) ) # parameters for additional clip time embeddings UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # parameters for encoder hidden states UpperCamelCase_ = clip_extra_context_tokens UpperCamelCase_ = nn.Linear( _SCREAMING_SNAKE_CASE , self.clip_extra_context_tokens * cross_attention_dim ) UpperCamelCase_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = nn.LayerNorm(_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , *, _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple ) -> str: """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings UpperCamelCase_ = image_embeddings.shape[0] UpperCamelCase_ = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) UpperCamelCase_ = classifier_free_guidance_embeddings.expand( _SCREAMING_SNAKE_CASE , -1 ) UpperCamelCase_ = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] UpperCamelCase_ = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... UpperCamelCase_ = self.embedding_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.clip_image_embeddings_project_to_time_embeddings(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" UpperCamelCase_ = self.clip_extra_context_tokens_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = clip_extra_context_tokens.reshape(_SCREAMING_SNAKE_CASE , -1 , self.clip_extra_context_tokens ) UpperCamelCase_ = clip_extra_context_tokens.permute(0 , 2 , 1 ) UpperCamelCase_ = self.encoder_hidden_states_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.text_encoder_hidden_states_norm(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
328
0