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
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = BioGptTokenizer __SCREAMING_SNAKE_CASE : Tuple = False def __lowerCAmelCase ( self ) ->List[str]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE : int = [ '''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>''', ] SCREAMING_SNAKE_CASE : Any = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE : Optional[Any] = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] SCREAMING_SNAKE_CASE : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(_lowerCamelCase ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(_lowerCamelCase ) ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : List[str] = '''lower newer''' SCREAMING_SNAKE_CASE : Optional[Any] = '''lower newer''' return input_text, output_text def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE : str = BioGptTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE : Optional[Any] = '''lower''' SCREAMING_SNAKE_CASE : Optional[Any] = ['''low''', '''er</w>'''] SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = tokens + ['''<unk>'''] SCREAMING_SNAKE_CASE : Any = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , _lowerCamelCase ) @slow def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : int = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode('''sequence builders''' , add_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
19
from math import pi, sqrt, tan def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''surface_area_cube() only accepts non-negative values''' ) return 6 * side_length**2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if length < 0 or breadth < 0 or height < 0: raise ValueError('''surface_area_cuboid() only accepts non-negative values''' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_sphere() only accepts non-negative values''' ) return 4 * pi * radius**2 def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' ) return 3 * pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cone() only accepts non-negative values''' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( '''surface_area_conical_frustum() only accepts non-negative values''' ) SCREAMING_SNAKE_CASE : Optional[Any] = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cylinder() only accepts non-negative values''' ) return 2 * pi * radius * (height + radius) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if torus_radius < 0 or tube_radius < 0: raise ValueError('''surface_area_torus() only accepts non-negative values''' ) if torus_radius < tube_radius: raise ValueError( '''surface_area_torus() does not support spindle or self intersecting tori''' ) return 4 * pow(a__ , 2 ) * torus_radius * tube_radius def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if length < 0 or width < 0: raise ValueError('''area_rectangle() only accepts non-negative values''' ) return length * width def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''area_square() only accepts non-negative values''' ) return side_length**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_triangle() only accepts non-negative values''' ) return (base * height) / 2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('''Given three sides do not form a triangle''' ) SCREAMING_SNAKE_CASE : int = (sidea + sidea + sidea) / 2 SCREAMING_SNAKE_CASE : List[str] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_parallelogram() only accepts non-negative values''' ) return base * height def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if basea < 0 or basea < 0 or height < 0: raise ValueError('''area_trapezium() only accepts non-negative values''' ) return 1 / 2 * (basea + basea) * height def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''area_circle() only accepts non-negative values''' ) return pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius_x < 0 or radius_y < 0: raise ValueError('''area_ellipse() only accepts non-negative values''' ) return pi * radius_x * radius_y def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if diagonal_a < 0 or diagonal_a < 0: raise ValueError('''area_rhombus() only accepts non-negative values''' ) return 1 / 2 * diagonal_a * diagonal_a def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if not isinstance(a__ , a__ ) or sides < 3: raise ValueError( '''area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides''' ) elif length < 0: raise ValueError( '''area_reg_polygon() only accepts non-negative values as \ length of a side''' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('''[DEMO] Areas of various geometric shapes: \n''') print(F"Rectangle: {area_rectangle(10, 20) = }") print(F"Square: {area_square(10) = }") print(F"Triangle: {area_triangle(10, 10) = }") print(F"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(F"Parallelogram: {area_parallelogram(10, 20) = }") print(F"Rhombus: {area_rhombus(10, 20) = }") print(F"Trapezium: {area_trapezium(10, 20, 30) = }") print(F"Circle: {area_circle(20) = }") print(F"Ellipse: {area_ellipse(10, 20) = }") print('''\nSurface Areas of various geometric shapes: \n''') print(F"Cube: {surface_area_cube(20) = }") print(F"Cuboid: {surface_area_cuboid(10, 20, 30) = }") print(F"Sphere: {surface_area_sphere(20) = }") print(F"Hemisphere: {surface_area_hemisphere(20) = }") print(F"Cone: {surface_area_cone(10, 20) = }") print(F"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") print(F"Cylinder: {surface_area_cylinder(10, 20) = }") print(F"Torus: {surface_area_torus(20, 10) = }") print(F"Equilateral Triangle: {area_reg_polygon(3, 10) = }") print(F"Square: {area_reg_polygon(4, 10) = }") print(F"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
19
1
# 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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = 'philschmid/bart-large-cnn-samsum' __SCREAMING_SNAKE_CASE : Optional[Any] = ( 'This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, ' 'and returns a summary of the text.' ) __SCREAMING_SNAKE_CASE : Tuple = 'summarizer' __SCREAMING_SNAKE_CASE : int = AutoTokenizer __SCREAMING_SNAKE_CASE : int = AutoModelForSeqaSeqLM __SCREAMING_SNAKE_CASE : List[Any] = ['text'] __SCREAMING_SNAKE_CASE : Optional[Any] = ['text'] def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: return self.pre_processor(_lowerCamelCase , return_tensors='''pt''' , truncation=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[Any]: return self.model.generate(**_lowerCamelCase )[0] def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: return self.pre_processor.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase )
19
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: a__ : List[str] = None a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Dict = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/mbart-large-en-ro''': '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json''', '''facebook/mbart-large-cc25''': '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json''', }, } a__ : str = { '''facebook/mbart-large-en-ro''': 1_024, '''facebook/mbart-large-cc25''': 1_024, } # fmt: off a__ : List[str] = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = ['input_ids', 'attention_mask'] __SCREAMING_SNAKE_CASE : Tuple = MBartTokenizer __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase , ) ->List[Any]: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : List[str] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token super().__init__( vocab_file=_lowerCamelCase , tokenizer_file=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , src_lang=_lowerCamelCase , tgt_lang=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Any = vocab_file SCREAMING_SNAKE_CASE : List[Any] = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : Any = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) SCREAMING_SNAKE_CASE : int = { lang_code: self.convert_tokens_to_ids(_lowerCamelCase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE : List[str] = src_lang if src_lang is not None else '''en_XX''' SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __lowerCAmelCase ( self ) ->str: return self._src_lang @src_lang.setter def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[int] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : str = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) ->Optional[Any]: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[str] = self(_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang_id return inputs def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = "en_XX" , _lowerCamelCase = None , _lowerCamelCase = "ro_RO" , **_lowerCamelCase , ) ->BatchEncoding: SCREAMING_SNAKE_CASE : List[str] = src_lang SCREAMING_SNAKE_CASE : List[str] = tgt_lang return super().prepare_seqaseq_batch(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Dict: return self.set_src_lang_special_tokens(self.src_lang ) def __lowerCAmelCase ( self ) ->List[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : str = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Any = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file , _lowerCamelCase ) return (out_vocab_file,)
19
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() a__ : Optional[Any] = logging.get_logger(__name__) def UpperCAmelCase_( a__ , a__=False , a__=False ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = '''backbone.''' if is_semantic else '''''' SCREAMING_SNAKE_CASE : Dict = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""{prefix}blocks.{i}.norm1.weight""", F"""beit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""{prefix}blocks.{i}.norm1.bias""", F"""beit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""{prefix}blocks.{i}.attn.proj.weight""", F"""beit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append( (F"""{prefix}blocks.{i}.attn.proj.bias""", F"""beit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""{prefix}blocks.{i}.norm2.weight""", F"""beit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""{prefix}blocks.{i}.norm2.bias""", F"""beit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc1.weight""", F"""beit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc1.bias""", F"""beit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc2.weight""", F"""beit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc2.bias""", F"""beit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ (F"""{prefix}cls_token""", '''beit.embeddings.cls_token'''), (F"""{prefix}patch_embed.proj.weight""", '''beit.embeddings.patch_embeddings.projection.weight'''), (F"""{prefix}patch_embed.proj.bias""", '''beit.embeddings.patch_embeddings.projection.bias'''), (F"""{prefix}pos_embed""", '''beit.embeddings.position_embeddings'''), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ('''mask_token''', '''beit.embeddings.mask_token'''), ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ] ) else: # layernorm + classification head rename_keys.extend( [ ('''fc_norm.weight''', '''beit.pooler.layernorm.weight'''), ('''fc_norm.bias''', '''beit.pooler.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def UpperCAmelCase_( a__ , a__ , a__=False , a__=False ): """simple docstring""" for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE : Any = '''backbone.''' if is_semantic else '''''' # queries, keys and values SCREAMING_SNAKE_CASE : str = state_dict.pop(F"""{prefix}blocks.{i}.attn.qkv.weight""" ) SCREAMING_SNAKE_CASE : int = state_dict.pop(F"""{prefix}blocks.{i}.attn.q_bias""" ) SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(F"""{prefix}blocks.{i}.attn.v_bias""" ) SCREAMING_SNAKE_CASE : Any = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE : Tuple = q_bias SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE : Optional[int] = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained SCREAMING_SNAKE_CASE : str = state_dict.pop(F"""{prefix}blocks.{i}.gamma_1""" ) SCREAMING_SNAKE_CASE : Any = state_dict.pop(F"""{prefix}blocks.{i}.gamma_2""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = gamma_a SCREAMING_SNAKE_CASE : Dict = gamma_a def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = dct.pop(a__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = val def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : Dict = Image.open(requests.get(a__ , stream=a__ ).raw ) return im @torch.no_grad() def UpperCAmelCase_( a__ , a__ , a__=False ): """simple docstring""" SCREAMING_SNAKE_CASE : str = False if '''rvlcdip''' in checkpoint_url else True SCREAMING_SNAKE_CASE : str = BeitConfig(use_absolute_position_embeddings=a__ , use_mask_token=a__ ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: SCREAMING_SNAKE_CASE : Tuple = 1_024 SCREAMING_SNAKE_CASE : str = 4_096 SCREAMING_SNAKE_CASE : int = 24 SCREAMING_SNAKE_CASE : List[str] = 16 # labels if "rvlcdip" in checkpoint_url: SCREAMING_SNAKE_CASE : List[str] = 16 SCREAMING_SNAKE_CASE : Optional[int] = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Optional[Any] = '''rvlcdip-id2label.json''' SCREAMING_SNAKE_CASE : str = json.load(open(hf_hub_download(a__ , a__ , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE : Tuple = {int(a__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = idalabel SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE : List[str] = torch.hub.load_state_dict_from_url(a__ , map_location='''cpu''' )['''model'''] SCREAMING_SNAKE_CASE : Union[str, Any] = create_rename_keys(a__ , has_lm_head=a__ ) for src, dest in rename_keys: rename_key(a__ , a__ , a__ ) read_in_q_k_v(a__ , a__ , has_lm_head=a__ ) # load HuggingFace model SCREAMING_SNAKE_CASE : Any = BeitForMaskedImageModeling(a__ ) if has_lm_head else BeitForImageClassification(a__ ) model.eval() model.load_state_dict(a__ ) # Check outputs on an image SCREAMING_SNAKE_CASE : Tuple = BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=a__ ) SCREAMING_SNAKE_CASE : Dict = prepare_img() SCREAMING_SNAKE_CASE : List[Any] = image_processor(images=a__ , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = encoding['''pixel_values'''] SCREAMING_SNAKE_CASE : Tuple = model(a__ ) SCREAMING_SNAKE_CASE : str = outputs.logits # verify logits SCREAMING_SNAKE_CASE : Optional[int] = [1, 16] if '''rvlcdip''' in checkpoint_url else [1, 196, 8_192] assert logits.shape == torch.Size(a__ ), "Shape of logits not as expected" Path(a__ ).mkdir(exist_ok=a__ ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(a__ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(a__ ) if push_to_hub: if has_lm_head: SCREAMING_SNAKE_CASE : Optional[Any] = '''dit-base''' if '''base''' in checkpoint_url else '''dit-large''' else: SCREAMING_SNAKE_CASE : Union[str, Any] = '''dit-base-finetuned-rvlcdip''' if '''dit-b''' in checkpoint_url else '''dit-large-finetuned-rvlcdip''' image_processor.push_to_hub( repo_path_or_name=Path(a__ , a__ ) , organization='''nielsr''' , commit_message='''Add image processor''' , use_temp_dir=a__ , ) model.push_to_hub( repo_path_or_name=Path(a__ , a__ ) , organization='''nielsr''' , commit_message='''Add model''' , use_temp_dir=a__ , ) if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_url''', default='''https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth''', type=str, help='''URL to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', ) a__ : int = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
19
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging a__ : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=768 ) ->List[Any]: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = proj_size SCREAMING_SNAKE_CASE : Any = CLIPVisionModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = PaintByExampleMapper(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = nn.LayerNorm(config.hidden_size ) SCREAMING_SNAKE_CASE : int = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=False ) ->int: SCREAMING_SNAKE_CASE : Optional[Any] = self.model(pixel_values=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = clip_output.pooler_output SCREAMING_SNAKE_CASE : Optional[Any] = self.mapper(latent_states[:, None] ) SCREAMING_SNAKE_CASE : Tuple = self.final_layer_norm(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.proj_out(_lowerCamelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->List[str]: super().__init__() SCREAMING_SNAKE_CASE : str = (config.num_hidden_layers + 1) // 5 SCREAMING_SNAKE_CASE : List[Any] = config.hidden_size SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : Optional[Any] = nn.ModuleList( [ BasicTransformerBlock(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , activation_fn='''gelu''' , attention_bias=_lowerCamelCase ) for _ in range(_lowerCamelCase ) ] ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: for block in self.blocks: SCREAMING_SNAKE_CASE : Optional[int] = block(_lowerCamelCase ) return hidden_states
19
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Tuple = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE : Any = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on SCREAMING_SNAKE_CASE : Tuple = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE : List[Any] = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] SCREAMING_SNAKE_CASE : Optional[int] = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE : Tuple = 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(_lowerCamelCase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], '''image_std''': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } SCREAMING_SNAKE_CASE : str = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self , **_lowerCamelCase ) ->Dict: return CLIPTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def __lowerCAmelCase ( self , **_lowerCamelCase ) ->Dict: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def __lowerCAmelCase ( self , **_lowerCamelCase ) ->List[str]: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[int]: shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : Dict = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : List[Any] = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE : Any = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Any = self.get_image_processor() SCREAMING_SNAKE_CASE : Any = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : str = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : str = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _lowerCamelCase ) self.assertIsInstance(processor_fast.tokenizer , _lowerCamelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _lowerCamelCase ) self.assertIsInstance(processor_fast.image_processor , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : str = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) SCREAMING_SNAKE_CASE : int = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) SCREAMING_SNAKE_CASE : str = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Dict = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Tuple = image_processor(_lowerCamelCase , return_tensors='''np''' ) SCREAMING_SNAKE_CASE : List[Any] = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : int = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = '''lower newer''' SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : str = self.get_image_processor() SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = '''lower newer''' SCREAMING_SNAKE_CASE : Tuple = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : List[str] = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(_lowerCamelCase ): processor() def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Dict = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Optional[int] = processor.batch_decode(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[Any] = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = '''lower newer''' SCREAMING_SNAKE_CASE : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : List[str] = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
19
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 a__ : Tuple = '''▁''' a__ : List[Any] = {'''vocab_file''': '''spiece.model'''} a__ : Optional[Any] = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } a__ : str = { '''google/pegasus-xsum''': 512, } a__ : str = logging.get_logger(__name__) class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : str = ['input_ids', 'attention_mask'] def __init__( self , _lowerCamelCase , _lowerCamelCase="<pad>" , _lowerCamelCase="</s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<mask_2>" , _lowerCamelCase="<mask_1>" , _lowerCamelCase=None , _lowerCamelCase=103 , _lowerCamelCase = None , **_lowerCamelCase , ) ->None: SCREAMING_SNAKE_CASE : Dict = offset if additional_special_tokens is not None: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError( F"""additional_special_tokens should be of type {type(_lowerCamelCase )}, but is""" F""" {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : List[Any] = ( ([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(_lowerCamelCase ) , self.offset - 1 ) ] if len(set(_lowerCamelCase ) ) != len(_lowerCamelCase ): 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}.""" ) SCREAMING_SNAKE_CASE : Dict = additional_special_tokens_extended else: SCREAMING_SNAKE_CASE : str = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F"""<unk_{i}>""" for i in range(2 , self.offset )] SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , mask_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token_sent=_lowerCamelCase , offset=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[str] = mask_token_sent SCREAMING_SNAKE_CASE : Optional[int] = vocab_file SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) # add special tokens to encoder dict SCREAMING_SNAKE_CASE : Dict[int, str] = { 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 )} ) SCREAMING_SNAKE_CASE : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def __lowerCAmelCase ( self ) ->int: return len(self.sp_model ) + self.offset def __lowerCAmelCase ( self ) ->Dict[str, int]: SCREAMING_SNAKE_CASE : Union[str, Any] = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = self.__dict__.copy() SCREAMING_SNAKE_CASE : str = None return state def __setstate__( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : List[str] = {} SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.piece_to_id(_lowerCamelCase ) return sp_id + self.offset def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: SCREAMING_SNAKE_CASE : Dict = self.sp_model.IdToPiece(index - self.offset ) return token def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : int = '''''' 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(_lowerCamelCase ) + token SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(_lowerCamelCase ) out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def __lowerCAmelCase ( self , _lowerCamelCase=False ) ->str: return 1 def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Dict = 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ) ->List[int]: if already_has_special_tokens: return self._special_token_mask(_lowerCamelCase ) elif token_ids_a is None: return self._special_token_mask(_lowerCamelCase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->List[int]: 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : int = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE : Tuple = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
19
1
import pytest a__ : List[str] = '''__dummy_dataset1__''' a__ : str = ''' import json import os import datasets REPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/" URLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"} class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self): features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ "O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", ] ) ), "langs": datasets.Sequence(datasets.Value("string")), "spans": datasets.Sequence(datasets.Value("string")), } ) return datasets.DatasetInfo(features=features) def _split_generators(self, dl_manager): dl_path = dl_manager.download(URLS) return [ datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}), datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}), ] def _generate_examples(self, filepath): with open(filepath, "r", encoding="utf-8") as f: for i, line in enumerate(f): yield i, json.loads(line) ''' @pytest.fixture def UpperCAmelCase_( ): """simple docstring""" return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def UpperCAmelCase_( ): """simple docstring""" return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = dataset_loading_script_name SCREAMING_SNAKE_CASE : Dict = tmp_path / '''datasets''' / script_name script_dir.mkdir(parents=a__ ) SCREAMING_SNAKE_CASE : Any = script_dir / F"""{script_name}.py""" with open(a__ , '''w''' ) as f: f.write(a__ ) return str(a__ )
19
def UpperCAmelCase_( a__ ): """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Tuple = 1 while repunit: SCREAMING_SNAKE_CASE : Dict = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def UpperCAmelCase_( a__ = 1_000_000 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(a__ ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F"{solution() = }")
19
1
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , ) ->int: SCREAMING_SNAKE_CASE : Optional[int] = parent SCREAMING_SNAKE_CASE : Optional[Any] = 13 SCREAMING_SNAKE_CASE : List[Any] = 7 SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Tuple = True SCREAMING_SNAKE_CASE : List[Any] = True SCREAMING_SNAKE_CASE : Dict = 99 SCREAMING_SNAKE_CASE : Dict = 32 SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = 4 SCREAMING_SNAKE_CASE : List[Any] = 37 SCREAMING_SNAKE_CASE : Optional[Any] = '''gelu''' SCREAMING_SNAKE_CASE : Tuple = 0.1 SCREAMING_SNAKE_CASE : str = 0.1 SCREAMING_SNAKE_CASE : Optional[Any] = 512 SCREAMING_SNAKE_CASE : Optional[Any] = 16 SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : int = 0.0_2 SCREAMING_SNAKE_CASE : int = 3 SCREAMING_SNAKE_CASE : Optional[Any] = 4 SCREAMING_SNAKE_CASE : Optional[Any] = None def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : int = None if self.use_labels: SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : List[str] = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self ) ->List[str]: ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : List[str] = TFEsmModel(config=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = {'''input_ids''': input_ids, '''attention_mask''': input_mask} SCREAMING_SNAKE_CASE : List[str] = model(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = [input_ids, input_mask] SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : Tuple = TFEsmModel(config=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } SCREAMING_SNAKE_CASE : str = model(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = [input_ids, input_mask] SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase , encoder_hidden_states=_lowerCamelCase ) # Also check the case where encoder outputs are not passed SCREAMING_SNAKE_CASE : List[Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Any = TFEsmForMaskedLM(config=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[Any] = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = TFEsmForTokenClassification(config=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} SCREAMING_SNAKE_CASE : List[Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __SCREAMING_SNAKE_CASE : Any = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Dict = False def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : List[Any] = TFEsmModelTester(self ) SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=37 ) def __lowerCAmelCase ( self ) ->Optional[int]: self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_lowerCamelCase ) def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase ) @slow def __lowerCAmelCase ( self ) ->str: for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : List[str] = TFEsmModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __lowerCAmelCase ( self ) ->Tuple: pass @unittest.skip('''Protein models do not support embedding resizing.''' ) def __lowerCAmelCase ( self ) ->Union[str, Any]: pass def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer SCREAMING_SNAKE_CASE : Optional[int] = model.get_bias() assert isinstance(_lowerCamelCase , _lowerCamelCase ) for k, v in name.items(): assert isinstance(_lowerCamelCase , tf.Variable ) else: SCREAMING_SNAKE_CASE : Any = model.get_output_embeddings() assert x is None SCREAMING_SNAKE_CASE : Tuple = model.get_bias() assert name is None @require_tf class a_ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Optional[Any] = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase )[0] SCREAMING_SNAKE_CASE : List[Any] = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _lowerCamelCase ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE : Any = tf.constant( [ [ [8.9_2_1_5_1_8, -1_0.5_8_9_8_1_4, -6.4_6_7_1_3_0_7], [-6.3_9_6_7_1_5_6, -1_3.9_1_1_3_7_7, -1.1_2_1_1_9_1_5], [-7.7_8_1_2_4_7, -1_3.9_5_1_5_5_7, -3.7_4_0_5_9_2], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-2 ) ) @slow def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : List[Any] = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) SCREAMING_SNAKE_CASE : Tuple = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase )[0] # compare the actual values for a slice. SCREAMING_SNAKE_CASE : int = tf.constant( [ [ [0.1_4_4_4_3_0_9_2, 0.5_4_1_2_5_3_2_7, 0.3_2_4_7_7_3_9], [0.3_0_3_4_0_4_8_4, 0.0_0_5_2_6_6_7_6, 0.3_1_0_7_7_7_2_2], [0.3_2_2_7_8_0_4_3, -0.2_4_9_8_7_0_9_6, 0.3_4_1_4_6_2_8], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
19
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=32 , _lowerCamelCase=3 , _lowerCamelCase=4 , _lowerCamelCase=[10, 20, 30, 40] , _lowerCamelCase=[2, 2, 3, 2] , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=10 , _lowerCamelCase=0.0_2 , _lowerCamelCase=["stage2", "stage3", "stage4"] , _lowerCamelCase=3 , _lowerCamelCase=None , ) ->Dict: SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Optional[Any] = batch_size SCREAMING_SNAKE_CASE : Optional[Any] = image_size SCREAMING_SNAKE_CASE : str = num_channels SCREAMING_SNAKE_CASE : Any = num_stages SCREAMING_SNAKE_CASE : List[str] = hidden_sizes SCREAMING_SNAKE_CASE : Optional[Any] = depths SCREAMING_SNAKE_CASE : Any = is_training SCREAMING_SNAKE_CASE : Tuple = use_labels SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : int = out_features SCREAMING_SNAKE_CASE : List[str] = num_labels SCREAMING_SNAKE_CASE : int = scope SCREAMING_SNAKE_CASE : Optional[Any] = num_stages def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : str = None if self.use_labels: SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) ->List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def __lowerCAmelCase ( self ) ->Any: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_lowerCamelCase , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_lowerCamelCase , loss_ignore_index=255 , num_labels=self.num_labels , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : List[Any] = UperNetForSemanticSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = (UperNetForSemanticSegmentation,) if is_torch_available() else () __SCREAMING_SNAKE_CASE : List[str] = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {} __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Union[str, Any] = False __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : Any = False def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[Any] = UperNetModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def __lowerCAmelCase ( self ) ->str: 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 __lowerCAmelCase ( self ) ->str: return def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Optional[int] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase ) @unittest.skip(reason='''UperNet does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) ->Union[str, Any]: pass @unittest.skip(reason='''UperNet does not support input and output embeddings''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->str: pass @require_torch_multi_gpu @unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def __lowerCAmelCase ( self ) ->str: pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowerCAmelCase ( self ) ->Tuple: pass def __lowerCAmelCase ( self ) ->int: def check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) SCREAMING_SNAKE_CASE : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # ConvNext'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] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Union[str, Any] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : str = _config_zero_init(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip(reason='''UperNet does not have tied weights''' ) def __lowerCAmelCase ( self ) ->List[Any]: pass @slow def __lowerCAmelCase ( self ) ->List[Any]: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Any = UperNetForSemanticSegmentation.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = hf_hub_download( repo_id='''hf-internal-testing/fixtures_ade20k''' , repo_type='''dataset''' , filename='''ADE_val_00000001.jpg''' ) SCREAMING_SNAKE_CASE : Any = Image.open(a__ ).convert('''RGB''' ) return image @require_torch @require_vision @slow class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny''' ) SCREAMING_SNAKE_CASE : Tuple = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny''' ) SCREAMING_SNAKE_CASE : str = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) )
19
1
def UpperCAmelCase_( a__ ): """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Tuple = 1 while repunit: SCREAMING_SNAKE_CASE : Dict = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def UpperCAmelCase_( a__ = 1_000_000 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(a__ ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F"{solution() = }")
19
import datasets from .evaluate import evaluate a__ : Dict = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' a__ : List[str] = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' a__ : List[Any] = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric("cuad") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': { '''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.features.Sequence(datasets.Value('''string''' ) ), }, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://www.atticusprojectai.org/cuad'''] , reference_urls=['''https://www.atticusprojectai.org/cuad'''] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Any = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} SCREAMING_SNAKE_CASE : int = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] SCREAMING_SNAKE_CASE : Dict = evaluate(dataset=_lowerCamelCase , predictions=_lowerCamelCase ) return score
19
1
from __future__ import annotations from math import pi, sqrt def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
19
from sklearn.metrics import matthews_corrcoef import datasets a__ : Optional[Any] = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' a__ : str = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' a__ : Union[str, Any] = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ) ->List[str]: return { "matthews_correlation": float(matthews_corrcoef(_lowerCamelCase , _lowerCamelCase , sample_weight=_lowerCamelCase ) ), }
19
1
from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = 9, 14 # noqa: F841 SCREAMING_SNAKE_CASE : Optional[int] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] SCREAMING_SNAKE_CASE : Optional[int] = defaultdict(a__ ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) SCREAMING_SNAKE_CASE : str = mst(a__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: SCREAMING_SNAKE_CASE : int = tuple(answer[:2] ) SCREAMING_SNAKE_CASE : Optional[Any] = tuple(edge[::-1] ) assert edge in result or reverse in result
19
# Copyright 2021 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 argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=a__ ) SCREAMING_SNAKE_CASE : int = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=a__ ) env_command_parser(subparsers=a__ ) launch_command_parser(subparsers=a__ ) tpu_command_parser(subparsers=a__ ) test_command_parser(subparsers=a__ ) # Let's go SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() if not hasattr(a__ , '''func''' ): parser.print_help() exit(1 ) # Run args.func(a__ ) if __name__ == "__main__": main()
19
1
a__ : dict[tuple[int, int, int], int] = {} def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on SCREAMING_SNAKE_CASE : Any = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one SCREAMING_SNAKE_CASE : int = _calculate(days - 1 , a__ , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 SCREAMING_SNAKE_CASE : Dict = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter SCREAMING_SNAKE_CASE : Dict = _calculate(days - 1 , a__ , 0 ) SCREAMING_SNAKE_CASE : Any = state_late + state_absent + state_ontime SCREAMING_SNAKE_CASE : Optional[Any] = prizestrings return prizestrings def UpperCAmelCase_( a__ = 30 ): """simple docstring""" return _calculate(a__ , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
19
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Optional[Any] = {'''vocab_file''': '''vocab.json'''} a__ : str = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } a__ : Tuple = {'''mgp-str''': 27} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _lowerCamelCase , _lowerCamelCase="[GO]" , _lowerCamelCase="[GO]" , _lowerCamelCase="[s]" , _lowerCamelCase="[GO]" , **_lowerCamelCase ) ->Dict: super().__init__( unk_token=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , pad_token=_lowerCamelCase , **_lowerCamelCase , ) with open(_lowerCamelCase , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE : List[Any] = json.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.vocab.items()} @property def __lowerCAmelCase ( self ) ->List[Any]: return len(self.vocab ) def __lowerCAmelCase ( self ) ->Union[str, Any]: return dict(self.vocab , **self.added_tokens_encoder ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Union[str, Any] = [] for s in text: char_tokens.extend(_lowerCamelCase ) return char_tokens def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: return self.vocab.get(_lowerCamelCase , self.vocab.get(self.unk_token ) ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: return self.decoder.get(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(_lowerCamelCase ) ) return SCREAMING_SNAKE_CASE : str = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=_lowerCamelCase , ensure_ascii=_lowerCamelCase ) + '''\n''' ) return (vocab_file,)
19
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''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 a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a__ : Optional[Any] = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['''DeiTFeatureExtractor'''] a__ : Any = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ '''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 a__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
1
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('''dataset_size''' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('''input_in_memory_max_size''' , ['''default''', 0, 100 * 2**20, 900 * 2**20] ) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , '''IN_MEMORY_MAX_SIZE''' , a__ ) SCREAMING_SNAKE_CASE : List[str] = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: SCREAMING_SNAKE_CASE : List[Any] = dataset_size < in_memory_max_size else: SCREAMING_SNAKE_CASE : str = False SCREAMING_SNAKE_CASE : Tuple = is_small_dataset(a__ ) assert result == expected
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''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 a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
19
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() a__ : str = logging.get_logger(__name__) a__ : Optional[int] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''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''', } a__ : Tuple = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def UpperCAmelCase_( a__ , a__ , a__ , a__ , a__ ): """simple docstring""" for attribute in key.split('''.''' ): SCREAMING_SNAKE_CASE : List[Any] = getattr(a__ , a__ ) if weight_type is not None: SCREAMING_SNAKE_CASE : Tuple = getattr(a__ , a__ ).shape else: SCREAMING_SNAKE_CASE : List[Any] = 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": SCREAMING_SNAKE_CASE : int = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE : List[str] = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE : Any = value elif weight_type == "bias": SCREAMING_SNAKE_CASE : List[Any] = value elif weight_type == "running_mean": SCREAMING_SNAKE_CASE : List[Any] = value elif weight_type == "running_var": SCREAMING_SNAKE_CASE : Optional[int] = value elif weight_type == "num_batches_tracked": SCREAMING_SNAKE_CASE : int = value elif weight_type == "inv_freq": SCREAMING_SNAKE_CASE : List[str] = value else: SCREAMING_SNAKE_CASE : Dict = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = fairseq_model.state_dict() SCREAMING_SNAKE_CASE : str = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE : Optional[int] = False if "conv_layers" in name: load_conv_layer( a__ , a__ , a__ , a__ , hf_model.config.feat_extract_norm == '''group''' , ) SCREAMING_SNAKE_CASE : Optional[int] = True else: for key, mapped_key in MAPPING.items(): SCREAMING_SNAKE_CASE : List[Any] = '''wav2vec2_conformer.''' + 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]: SCREAMING_SNAKE_CASE : Optional[int] = True if "*" in mapped_key: SCREAMING_SNAKE_CASE : List[str] = name.split(a__ )[0].split('''.''' )[-2] SCREAMING_SNAKE_CASE : Union[str, Any] = mapped_key.replace('''*''' , a__ ) if "pos_bias_u" in name: SCREAMING_SNAKE_CASE : str = None elif "pos_bias_v" in name: SCREAMING_SNAKE_CASE : Dict = None elif "weight_g" in name: SCREAMING_SNAKE_CASE : Dict = '''weight_g''' elif "weight_v" in name: SCREAMING_SNAKE_CASE : str = '''weight_v''' elif "bias" in name: SCREAMING_SNAKE_CASE : Any = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj SCREAMING_SNAKE_CASE : List[str] = '''weight''' elif "running_mean" in name: SCREAMING_SNAKE_CASE : List[str] = '''running_mean''' elif "inv_freq" in name: SCREAMING_SNAKE_CASE : str = '''inv_freq''' elif "running_var" in name: SCREAMING_SNAKE_CASE : Any = '''running_var''' elif "num_batches_tracked" in name: SCREAMING_SNAKE_CASE : Optional[Any] = '''num_batches_tracked''' else: SCREAMING_SNAKE_CASE : Optional[Any] = None set_recursively(a__ , a__ , a__ , a__ , a__ ) continue if not is_used: unused_weights.append(a__ ) logger.warning(F"""Unused weights: {unused_weights}""" ) def UpperCAmelCase_( a__ , a__ , a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = full_name.split('''conv_layers.''' )[-1] SCREAMING_SNAKE_CASE : str = name.split('''.''' ) SCREAMING_SNAKE_CASE : str = int(items[0] ) SCREAMING_SNAKE_CASE : Dict = 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.""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = 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.""" ) SCREAMING_SNAKE_CASE : Optional[Any] = 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.""" ) SCREAMING_SNAKE_CASE : Optional[Any] = 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.""" ) SCREAMING_SNAKE_CASE : Dict = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a__ ) @torch.no_grad() def UpperCAmelCase_( a__ , a__ , a__=None , a__=None , a__=True ): """simple docstring""" if config_path is not None: SCREAMING_SNAKE_CASE : List[str] = WavaVecaConformerConfig.from_pretrained(a__ , hidden_act='''swish''' ) else: SCREAMING_SNAKE_CASE : List[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = '''rotary''' if is_finetuned: if dict_path: SCREAMING_SNAKE_CASE : Union[str, Any] = Dictionary.load(a__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq SCREAMING_SNAKE_CASE : Tuple = target_dict.pad_index SCREAMING_SNAKE_CASE : List[Any] = target_dict.bos_index SCREAMING_SNAKE_CASE : Dict = target_dict.eos_index SCREAMING_SNAKE_CASE : Dict = len(target_dict.symbols ) SCREAMING_SNAKE_CASE : Tuple = os.path.join(a__ , '''vocab.json''' ) if not os.path.isdir(a__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(a__ ) ) return os.makedirs(a__ , exist_ok=a__ ) SCREAMING_SNAKE_CASE : Tuple = target_dict.indices # fairseq has the <pad> and <s> switched SCREAMING_SNAKE_CASE : Tuple = 0 SCREAMING_SNAKE_CASE : Any = 1 with open(a__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(a__ , a__ ) SCREAMING_SNAKE_CASE : Optional[int] = WavaVecaCTCTokenizer( a__ , 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=a__ , ) SCREAMING_SNAKE_CASE : Any = True if config.feat_extract_norm == '''layer''' else False SCREAMING_SNAKE_CASE : Optional[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=a__ , return_attention_mask=a__ , ) SCREAMING_SNAKE_CASE : Dict = WavaVecaProcessor(feature_extractor=a__ , tokenizer=a__ ) processor.save_pretrained(a__ ) SCREAMING_SNAKE_CASE : str = WavaVecaConformerForCTC(a__ ) else: SCREAMING_SNAKE_CASE : Any = WavaVecaConformerForPreTraining(a__ ) if is_finetuned: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.Namespace(task='''audio_pretraining''' ) SCREAMING_SNAKE_CASE : str = fairseq.tasks.setup_task(a__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a__ ) SCREAMING_SNAKE_CASE : List[str] = model[0].eval() recursively_load_weights(a__ , a__ , not is_finetuned ) hf_wavavec.save_pretrained(a__ ) if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--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''' ) a__ : Optional[int] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
19
import math from collections.abc import Iterator from itertools import takewhile def UpperCAmelCase_( a__ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = 2 while True: if is_prime(a__ ): yield num num += 1 def UpperCAmelCase_( a__ = 2_000_000 ): """simple docstring""" return sum(takewhile(lambda a__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"{solution() = }")
19
1
def UpperCAmelCase_( a__ ): """simple docstring""" return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = credit_card_number SCREAMING_SNAKE_CASE : Tuple = 0 SCREAMING_SNAKE_CASE : Dict = len(a__ ) - 2 for i in range(a__ , -1 , -2 ): # double the value of every second digit SCREAMING_SNAKE_CASE : Optional[int] = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 SCREAMING_SNAKE_CASE : Union[str, Any] = cc_number[:i] + str(a__ ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(a__ ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = F"""{credit_card_number} is an invalid credit card number because""" if not credit_card_number.isdigit(): print(F"""{error_message} it has nonnumerical characters.""" ) return False if not 13 <= len(a__ ) <= 16: print(F"""{error_message} of its length.""" ) return False if not validate_initial_digits(a__ ): print(F"""{error_message} of its first two digits.""" ) return False if not luhn_validation(a__ ): print(F"""{error_message} it fails the Luhn check.""" ) return False print(F"""{credit_card_number} is a valid credit card number.""" ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
19
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a_ ( a__ ): """simple docstring""" def __init__( self , *_lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase ) ->int: super().__init__(*_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = eval_examples SCREAMING_SNAKE_CASE : Optional[int] = post_process_function def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase=None , _lowerCamelCase = None , _lowerCamelCase = "eval" , **_lowerCamelCase , ) ->Dict[str, float]: SCREAMING_SNAKE_CASE : Any = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) SCREAMING_SNAKE_CASE : Dict = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) SCREAMING_SNAKE_CASE : Any = gen_kwargs SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : str = self.get_eval_dataloader(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Optional[Any] = self.compute_metrics SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : Optional[Any] = time.time() SCREAMING_SNAKE_CASE : List[str] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Tuple = eval_loop( _lowerCamelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Dict = compute_metrics SCREAMING_SNAKE_CASE : Tuple = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : Optional[int] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_lowerCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : int = self.callback_handler.on_evaluate(self.args , self.state , self.control , _lowerCamelCase ) return metrics def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase = "test" , **_lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : str = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(_lowerCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[str] = time.time() SCREAMING_SNAKE_CASE : Optional[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Any = eval_loop( _lowerCamelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Optional[int] = compute_metrics SCREAMING_SNAKE_CASE : List[Any] = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , '''predict''' ) SCREAMING_SNAKE_CASE : Dict = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : List[Any] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_lowerCamelCase )
19
1
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a__ : List[str] = logging.get_logger(__name__) # General docstring a__ : Tuple = '''MobileNetV1Config''' # Base docstring a__ : Optional[Any] = '''google/mobilenet_v1_1.0_224''' a__ : Tuple = [1, 1_024, 7, 7] # Image classification docstring a__ : Optional[int] = '''google/mobilenet_v1_1.0_224''' a__ : int = '''tabby, tabby cat''' a__ : List[Any] = [ '''google/mobilenet_v1_1.0_224''', '''google/mobilenet_v1_0.75_192''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def UpperCAmelCase_( a__ , a__ , a__=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = {} if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[str] = model.mobilenet_va else: SCREAMING_SNAKE_CASE : Union[str, Any] = model SCREAMING_SNAKE_CASE : Optional[int] = '''MobilenetV1/Conv2d_0/''' SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.convolution.weight SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = backbone.conv_stem.normalization.weight SCREAMING_SNAKE_CASE : Union[str, Any] = backbone.conv_stem.normalization.running_mean SCREAMING_SNAKE_CASE : Any = backbone.conv_stem.normalization.running_var for i in range(13 ): SCREAMING_SNAKE_CASE : Dict = i + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = i * 2 SCREAMING_SNAKE_CASE : Any = backbone.layer[pt_index] SCREAMING_SNAKE_CASE : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" SCREAMING_SNAKE_CASE : Any = pointer.convolution.weight SCREAMING_SNAKE_CASE : Tuple = pointer.normalization.bias SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.running_var SCREAMING_SNAKE_CASE : List[Any] = backbone.layer[pt_index + 1] SCREAMING_SNAKE_CASE : Any = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" SCREAMING_SNAKE_CASE : Dict = pointer.convolution.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : int = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : str = pointer.normalization.running_var if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[Any] = '''MobilenetV1/Logits/Conv2d_1c_1x1/''' SCREAMING_SNAKE_CASE : List[str] = model.classifier.weight SCREAMING_SNAKE_CASE : List[str] = model.classifier.bias return tf_to_pt_map def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ''' '''https://www.tensorflow.org/install/ for installation instructions.''' ) raise # Load weights from TF model SCREAMING_SNAKE_CASE : Optional[Any] = tf.train.list_variables(a__ ) SCREAMING_SNAKE_CASE : List[Any] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) SCREAMING_SNAKE_CASE : Tuple = tf.train.load_variable(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = array # Build TF to PyTorch weights loading map SCREAMING_SNAKE_CASE : int = _build_tf_to_pytorch_map(a__ , a__ , a__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue SCREAMING_SNAKE_CASE : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('''Transposing depthwise''' ) SCREAMING_SNAKE_CASE : Tuple = np.transpose(a__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('''Transposing''' ) if len(pointer.shape ) == 2: # copying into linear layer SCREAMING_SNAKE_CASE : Union[str, Any] = array.squeeze().transpose() else: SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(a__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(a__ ) tf_weights.pop(a__ , a__ ) tf_weights.pop(name + '''/RMSProp''' , a__ ) tf_weights.pop(name + '''/RMSProp_1''' , a__ ) tf_weights.pop(name + '''/ExponentialMovingAverage''' , a__ ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = features.shape[-2:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = conv_layer.stride SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = conv_layer.kernel_size if in_height % stride_height == 0: SCREAMING_SNAKE_CASE : List[str] = max(kernel_height - stride_height , 0 ) else: SCREAMING_SNAKE_CASE : str = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: SCREAMING_SNAKE_CASE : int = max(kernel_width - stride_width , 0 ) else: SCREAMING_SNAKE_CASE : Tuple = max(kernel_width - (in_width % stride_width) , 0 ) SCREAMING_SNAKE_CASE : List[str] = pad_along_width // 2 SCREAMING_SNAKE_CASE : Any = pad_along_width - pad_left SCREAMING_SNAKE_CASE : str = pad_along_height // 2 SCREAMING_SNAKE_CASE : Optional[int] = pad_along_height - pad_top SCREAMING_SNAKE_CASE : List[Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(a__ , a__ , '''constant''' , 0.0 ) class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 1 , _lowerCamelCase = 1 , _lowerCamelCase = False , _lowerCamelCase = True , _lowerCamelCase = True , ) ->None: super().__init__() SCREAMING_SNAKE_CASE : Any = config if in_channels % groups != 0: raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) SCREAMING_SNAKE_CASE : Any = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) SCREAMING_SNAKE_CASE : List[str] = nn.Convad( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=_lowerCamelCase , stride=_lowerCamelCase , padding=_lowerCamelCase , groups=_lowerCamelCase , bias=_lowerCamelCase , padding_mode='''zeros''' , ) if use_normalization: SCREAMING_SNAKE_CASE : List[Any] = nn.BatchNormad( num_features=_lowerCamelCase , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=_lowerCamelCase , track_running_stats=_lowerCamelCase , ) else: SCREAMING_SNAKE_CASE : Dict = None if use_activation: if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Any = ACTaFN[use_activation] elif isinstance(config.hidden_act , _lowerCamelCase ): SCREAMING_SNAKE_CASE : List[str] = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : List[Any] = config.hidden_act else: SCREAMING_SNAKE_CASE : Optional[Any] = None def __lowerCAmelCase ( self , _lowerCamelCase ) ->torch.Tensor: if self.config.tf_padding: SCREAMING_SNAKE_CASE : List[Any] = apply_tf_padding(_lowerCamelCase , self.convolution ) SCREAMING_SNAKE_CASE : Dict = self.convolution(_lowerCamelCase ) if self.normalization is not None: SCREAMING_SNAKE_CASE : int = self.normalization(_lowerCamelCase ) if self.activation is not None: SCREAMING_SNAKE_CASE : List[Any] = self.activation(_lowerCamelCase ) return features class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = MobileNetVaConfig __SCREAMING_SNAKE_CASE : List[Any] = load_tf_weights_in_mobilenet_va __SCREAMING_SNAKE_CASE : int = 'mobilenet_v1' __SCREAMING_SNAKE_CASE : int = 'pixel_values' __SCREAMING_SNAKE_CASE : List[str] = False def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: if isinstance(_lowerCamelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_lowerCamelCase , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) a__ : str = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Union[str, Any] = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase = True ) ->Dict: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = config SCREAMING_SNAKE_CASE : Dict = 32 SCREAMING_SNAKE_CASE : Optional[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) SCREAMING_SNAKE_CASE : str = MobileNetVaConvLayer( _lowerCamelCase , in_channels=config.num_channels , out_channels=_lowerCamelCase , kernel_size=3 , stride=2 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] SCREAMING_SNAKE_CASE : Any = nn.ModuleList() for i in range(13 ): SCREAMING_SNAKE_CASE : int = out_channels if strides[i] == 2 or i == 0: depth *= 2 SCREAMING_SNAKE_CASE : Tuple = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=3 , stride=strides[i] , groups=_lowerCamelCase , ) ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=1 , ) ) SCREAMING_SNAKE_CASE : int = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: raise NotImplementedError @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.conv_stem(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): SCREAMING_SNAKE_CASE : Optional[int] = layer_module(_lowerCamelCase ) if output_hidden_states: SCREAMING_SNAKE_CASE : List[str] = all_hidden_states + (hidden_states,) SCREAMING_SNAKE_CASE : List[str] = hidden_states if self.pooler is not None: SCREAMING_SNAKE_CASE : Tuple = torch.flatten(self.pooler(_lowerCamelCase ) , start_dim=1 ) else: SCREAMING_SNAKE_CASE : List[Any] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_lowerCamelCase , pooler_output=_lowerCamelCase , hidden_states=_lowerCamelCase , ) @add_start_docstrings( '\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->None: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = config.num_labels SCREAMING_SNAKE_CASE : str = MobileNetVaModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head SCREAMING_SNAKE_CASE : Optional[int] = nn.Dropout(config.classifier_dropout_prob , inplace=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = nn.Linear(_lowerCamelCase , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, ImageClassifierOutputWithNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va(_lowerCamelCase , output_hidden_states=_lowerCamelCase , return_dict=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE : Tuple = self.classifier(self.dropout(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : int = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : Any = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : Optional[int] = '''single_label_classification''' else: SCREAMING_SNAKE_CASE : Dict = '''multi_label_classification''' if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Any = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : Dict = loss_fct(_lowerCamelCase , _lowerCamelCase ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : List[Any] = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : List[Any] = loss_fct(_lowerCamelCase , _lowerCamelCase ) if not return_dict: SCREAMING_SNAKE_CASE : Optional[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_lowerCamelCase , logits=_lowerCamelCase , hidden_states=outputs.hidden_states , )
19
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = DDIMPipeline __SCREAMING_SNAKE_CASE : Tuple = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __SCREAMING_SNAKE_CASE : Tuple = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } __SCREAMING_SNAKE_CASE : str = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = False def __lowerCAmelCase ( self ) ->int: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler() SCREAMING_SNAKE_CASE : Dict = {'''unet''': unet, '''scheduler''': scheduler} return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->int: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : int = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Optional[int] = '''cpu''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[Any] = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) SCREAMING_SNAKE_CASE : int = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) SCREAMING_SNAKE_CASE : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def __lowerCAmelCase ( self ) ->Optional[int]: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_save_load_local(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Union[str, Any]: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[int] = '''google/ddpm-cifar10-32''' SCREAMING_SNAKE_CASE : Dict = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler() SCREAMING_SNAKE_CASE : Optional[int] = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddim.to(_lowerCamelCase ) ddim.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = ddim(generator=_lowerCamelCase , eta=0.0 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[Any] = '''google/ddpm-ema-bedroom-256''' SCREAMING_SNAKE_CASE : List[str] = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = DDIMScheduler.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddpm.to(_lowerCamelCase ) ddpm.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = ddpm(generator=_lowerCamelCase , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
19
1
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE : Optional[int] = TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''' ) SCREAMING_SNAKE_CASE : Tuple = { '''input_ids''': tf.convert_to_tensor([[0, 2646, 1_0269, 83, 9_9942, 2]] , dtype=tf.intaa ), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } SCREAMING_SNAKE_CASE : str = model(_lowerCamelCase )['''last_hidden_state'''] SCREAMING_SNAKE_CASE : Any = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , _lowerCamelCase ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE : Union[str, Any] = tf.convert_to_tensor( [ [ [0.0_6_8_1_7_6_2, 0.1_0_8_9_4_4_5_1, 0.0_6_7_7_2_5_0_4], [-0.0_6_4_2_3_6_6_8, 0.0_2_3_6_6_6_1_5, 0.0_4_3_2_9_3_4_4], [-0.0_6_0_5_7_2_9_5, 0.0_9_9_7_4_1_3_5, -0.0_0_0_7_0_5_8_4], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
19
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = XLMProphetNetTokenizer __SCREAMING_SNAKE_CASE : List[str] = False __SCREAMING_SNAKE_CASE : Dict = True def __lowerCAmelCase ( self ) ->Dict: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE : Optional[Any] = XLMProphetNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : List[str] = '''[PAD]''' SCREAMING_SNAKE_CASE : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''[PAD]''' ) self.assertEqual(vocab_keys[1] , '''[CLS]''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(_lowerCamelCase ) , 1012 ) def __lowerCAmelCase ( self ) ->List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = XLMProphetNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''[UNK]''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''[UNK]''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self ) ->List[str]: return XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased''' ) @slow def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Union[str, Any] = '''Hello World!''' SCREAMING_SNAKE_CASE : int = [3_5389, 6672, 49, 2] self.assertListEqual(_lowerCamelCase , self.big_tokenizer.encode(_lowerCamelCase ) ) @slow def __lowerCAmelCase ( self ) ->int: # fmt: off SCREAMING_SNAKE_CASE : str = {'''input_ids''': [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''microsoft/xprophetnet-large-wiki100-cased''' , revision='''1acad1643ddd54a44df6a1b797ada8373685d90e''' , )
19
1
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Optional[Any] = logging.get_logger(__name__) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) ->List[str]: SCREAMING_SNAKE_CASE : str = feature_size SCREAMING_SNAKE_CASE : Union[str, Any] = sampling_rate SCREAMING_SNAKE_CASE : Union[str, Any] = padding_value SCREAMING_SNAKE_CASE : int = kwargs.pop('''padding_side''' , '''right''' ) SCREAMING_SNAKE_CASE : int = kwargs.pop('''return_attention_mask''' , _lowerCamelCase ) super().__init__(**_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(_lowerCamelCase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): SCREAMING_SNAKE_CASE : Tuple = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( '''You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`''' F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) SCREAMING_SNAKE_CASE : Dict = processed_features[self.model_input_names[0]] SCREAMING_SNAKE_CASE : Tuple = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(_lowerCamelCase ) == 0: if return_attention_mask: SCREAMING_SNAKE_CASE : Union[str, Any] = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch SCREAMING_SNAKE_CASE : int = required_input[0] if isinstance(_lowerCamelCase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. SCREAMING_SNAKE_CASE : int = 0 while len(required_input[index] ) == 0: index += 1 if index < len(_lowerCamelCase ): SCREAMING_SNAKE_CASE : List[str] = required_input[index][0] if return_tensors is None: if is_tf_tensor(_lowerCamelCase ): SCREAMING_SNAKE_CASE : str = '''tf''' elif is_torch_tensor(_lowerCamelCase ): SCREAMING_SNAKE_CASE : Optional[Any] = '''pt''' elif isinstance(_lowerCamelCase , (int, float, list, tuple, np.ndarray) ): SCREAMING_SNAKE_CASE : List[Any] = '''np''' else: raise ValueError( F"""type of {first_element} unknown: {type(_lowerCamelCase )}. """ '''Should be one of a python, numpy, pytorch or tensorflow object.''' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): SCREAMING_SNAKE_CASE : Optional[Any] = to_numpy(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : Optional[Any] = [to_numpy(_lowerCamelCase ) for v in value] # Convert padding_strategy in PaddingStrategy SCREAMING_SNAKE_CASE : Dict = self._get_padding_strategies(padding=_lowerCamelCase , max_length=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = processed_features[self.model_input_names[0]] SCREAMING_SNAKE_CASE : Optional[int] = len(_lowerCamelCase ) if not all(len(_lowerCamelCase ) == batch_size for v in processed_features.values() ): raise ValueError('''Some items in the output dictionary have a different batch size than others.''' ) SCREAMING_SNAKE_CASE : Tuple = [] for i in range(_lowerCamelCase ): SCREAMING_SNAKE_CASE : Any = {k: v[i] for k, v in processed_features.items()} # truncation SCREAMING_SNAKE_CASE : List[str] = self._truncate( _lowerCamelCase , max_length=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , truncation=_lowerCamelCase , ) truncated_inputs.append(_lowerCamelCase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length SCREAMING_SNAKE_CASE : List[str] = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) SCREAMING_SNAKE_CASE : Optional[int] = PaddingStrategy.MAX_LENGTH SCREAMING_SNAKE_CASE : Tuple = {} for i in range(_lowerCamelCase ): # padding SCREAMING_SNAKE_CASE : Tuple = self._pad( truncated_inputs[i] , max_length=_lowerCamelCase , padding_strategy=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , ) for key, value in outputs.items(): if key not in batch_outputs: SCREAMING_SNAKE_CASE : Optional[int] = [] if value.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE : Optional[Any] = value.astype(np.floataa ) batch_outputs[key].append(_lowerCamelCase ) return BatchFeature(_lowerCamelCase , tensor_type=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = PaddingStrategy.DO_NOT_PAD , _lowerCamelCase = None , _lowerCamelCase = None , ) ->dict: SCREAMING_SNAKE_CASE : int = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: SCREAMING_SNAKE_CASE : Dict = len(_lowerCamelCase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): SCREAMING_SNAKE_CASE : Optional[int] = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of SCREAMING_SNAKE_CASE : int = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(_lowerCamelCase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: SCREAMING_SNAKE_CASE : List[str] = np.ones(len(_lowerCamelCase ) , dtype=np.intaa ) if needs_to_be_padded: SCREAMING_SNAKE_CASE : Optional[int] = max_length - len(_lowerCamelCase ) if self.padding_side == "right": if return_attention_mask: SCREAMING_SNAKE_CASE : str = np.pad( processed_features['''attention_mask'''] , (0, difference) ) SCREAMING_SNAKE_CASE : Optional[int] = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) SCREAMING_SNAKE_CASE : Tuple = np.pad( _lowerCamelCase , _lowerCamelCase , '''constant''' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: SCREAMING_SNAKE_CASE : Union[str, Any] = np.pad( processed_features['''attention_mask'''] , (difference, 0) ) SCREAMING_SNAKE_CASE : str = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) SCREAMING_SNAKE_CASE : List[str] = np.pad( _lowerCamelCase , _lowerCamelCase , '''constant''' , constant_values=self.padding_value ) else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return processed_features def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('''When setting ``truncation=True``, make sure that ``max_length`` is defined.''' ) SCREAMING_SNAKE_CASE : Dict = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): SCREAMING_SNAKE_CASE : int = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of SCREAMING_SNAKE_CASE : Optional[Any] = len(_lowerCamelCase ) > max_length if needs_to_be_truncated: SCREAMING_SNAKE_CASE : int = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: SCREAMING_SNAKE_CASE : List[Any] = processed_features['''attention_mask'''][:max_length] return processed_features def __lowerCAmelCase ( self , _lowerCamelCase=False , _lowerCamelCase=None ) ->List[Any]: # Get padding strategy if padding is not False: if padding is True: SCREAMING_SNAKE_CASE : Any = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Optional[Any] = PaddingStrategy(_lowerCamelCase ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : str = padding else: SCREAMING_SNAKE_CASE : Union[str, Any] = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( '''Asking to pad but the feature_extractor does not have a padding value. Please select a value to use''' ''' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.''' ) return padding_strategy
19
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = StableDiffusionSAGPipeline __SCREAMING_SNAKE_CASE : Dict = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : int = False def __lowerCAmelCase ( self ) ->Optional[int]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = 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 , ) SCREAMING_SNAKE_CASE : int = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = 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 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->str: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''prompt''': '''.''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 1.0, '''sag_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) SCREAMING_SNAKE_CASE : Tuple = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = '''.''' SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : int = output.images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : int = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = '''.''' SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : List[str] = output.images SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : str = np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : int = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : Optional[int] = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = '''.''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , width=768 , height=512 , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : List[Any] = output.images assert image.shape == (1, 512, 768, 3)
19
1
from __future__ import annotations def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [True] * limit SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : int = False SCREAMING_SNAKE_CASE : Union[str, Any] = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): SCREAMING_SNAKE_CASE : Optional[int] = i * 2 while index < limit: SCREAMING_SNAKE_CASE : int = False SCREAMING_SNAKE_CASE : Optional[Any] = index + i SCREAMING_SNAKE_CASE : Any = [2] for i in range(3 , a__ , 2 ): if is_prime[i]: primes.append(a__ ) return primes def UpperCAmelCase_( a__ = 1_000_000 ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = prime_sieve(a__ ) SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : List[str] = 0 for i in range(len(a__ ) ): for j in range(i + length , len(a__ ) ): SCREAMING_SNAKE_CASE : Dict = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: SCREAMING_SNAKE_CASE : Union[str, Any] = j - i SCREAMING_SNAKE_CASE : int = sol return largest if __name__ == "__main__": print(F"{solution() = }")
19
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Tuple = { '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } a__ : Optional[Any] = {'''mobilebert-uncased''': 512} a__ : List[Any] = {} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : int = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_INIT_CONFIGURATION __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Optional[int] = MobileBertTokenizer def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase="[UNK]" , _lowerCamelCase="[SEP]" , _lowerCamelCase="[PAD]" , _lowerCamelCase="[CLS]" , _lowerCamelCase="[MASK]" , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ) ->Optional[int]: super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE : Optional[int] = strip_accents SCREAMING_SNAKE_CASE : Union[str, Any] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = do_lower_case def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->Any: SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: SCREAMING_SNAKE_CASE : Any = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
19
1
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : List[Any] = '''▁''' a__ : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = BertGenerationTokenizer __SCREAMING_SNAKE_CASE : int = False __SCREAMING_SNAKE_CASE : List[str] = True def __lowerCAmelCase ( self ) ->str: super().setUp() SCREAMING_SNAKE_CASE : Optional[int] = BertGenerationTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : List[str] = '''<s>''' SCREAMING_SNAKE_CASE : Optional[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(_lowerCamelCase ) , 1002 ) def __lowerCAmelCase ( self ) ->List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Dict = BertGenerationTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [285, 46, 10, 170, 382] , ) SCREAMING_SNAKE_CASE : str = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) SCREAMING_SNAKE_CASE : Any = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self ) ->str: return BertGenerationTokenizer.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) @slow def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : List[Any] = '''Hello World!''' SCREAMING_SNAKE_CASE : Union[str, Any] = [1_8536, 2260, 101] self.assertListEqual(_lowerCamelCase , self.big_tokenizer.encode(_lowerCamelCase ) ) @slow def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : List[str] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) SCREAMING_SNAKE_CASE : List[str] = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 3_4324, 497, 391, 408, 1_1342, 1244, 385, 100, 938, 985, 456, 574, 362, 1_2597, 3200, 3129, 1172, ] self.assertListEqual(_lowerCamelCase , self.big_tokenizer.encode(_lowerCamelCase ) ) @require_torch @slow def __lowerCAmelCase ( self ) ->List[str]: import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence SCREAMING_SNAKE_CASE : List[str] = list(self.big_tokenizer.get_vocab().keys() )[:10] SCREAMING_SNAKE_CASE : str = ''' '''.join(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = self.big_tokenizer.encode_plus(_lowerCamelCase , return_tensors='''pt''' , return_token_type_ids=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = BertGenerationConfig() SCREAMING_SNAKE_CASE : str = BertGenerationEncoder(_lowerCamelCase ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_lowerCamelCase ) model(**_lowerCamelCase ) @slow def __lowerCAmelCase ( self ) ->Optional[Any]: # fmt: off SCREAMING_SNAKE_CASE : int = {'''input_ids''': [[3_9286, 458, 3_6335, 2001, 456, 1_3073, 1_3266, 455, 113, 7746, 1741, 1_1157, 391, 1_3073, 1_3266, 455, 113, 3967, 3_5412, 113, 4936, 109, 3870, 2377, 113, 3_0084, 4_5720, 458, 134, 1_7496, 112, 503, 1_1672, 113, 118, 112, 5665, 1_3347, 3_8687, 112, 1496, 3_1389, 112, 3268, 4_7264, 134, 962, 112, 1_6377, 8035, 2_3130, 430, 1_2169, 1_5518, 2_8592, 458, 146, 4_1697, 109, 391, 1_2169, 1_5518, 1_6689, 458, 146, 4_1358, 109, 452, 726, 4034, 111, 763, 3_5412, 5082, 388, 1903, 111, 9051, 391, 2870, 4_8918, 1900, 1123, 550, 998, 112, 9586, 1_5985, 455, 391, 410, 2_2955, 3_7636, 114], [448, 1_7496, 419, 3663, 385, 763, 113, 2_7533, 2870, 3283, 1_3043, 1639, 2_4713, 523, 656, 2_4013, 1_8550, 2521, 517, 2_7014, 2_1244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 1_1786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 2_1932, 1_8146, 726, 363, 1_7032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''google/bert_for_seq_generation_L-24_bbc_encoder''' , revision='''c817d1fd1be2ffa69431227a1fe320544943d4db''' , )
19
import math a__ : List[str] = 10 a__ : Optional[int] = 7 a__ : int = BALLS_PER_COLOUR * NUM_COLOURS def UpperCAmelCase_( a__ = 20 ): """simple docstring""" SCREAMING_SNAKE_CASE : str = math.comb(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) SCREAMING_SNAKE_CASE : Any = NUM_COLOURS * (1 - missing_colour / total) return F"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
19
1
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class a_ : """simple docstring""" def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: raise NotImplementedError() def __lowerCAmelCase ( self ) ->Optional[int]: raise NotImplementedError() class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase = False , **_lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Any = tokenizer SCREAMING_SNAKE_CASE : List[Any] = skip_prompt SCREAMING_SNAKE_CASE : Dict = decode_kwargs # variables used in the streaming process SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Union[str, Any] = 0 SCREAMING_SNAKE_CASE : int = True def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError('''TextStreamer only supports batch size 1''' ) elif len(value.shape ) > 1: SCREAMING_SNAKE_CASE : Union[str, Any] = value[0] if self.skip_prompt and self.next_tokens_are_prompt: SCREAMING_SNAKE_CASE : Optional[int] = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) SCREAMING_SNAKE_CASE : Tuple = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith('''\n''' ): SCREAMING_SNAKE_CASE : Dict = text[self.print_len :] SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : int = 0 # If the last token is a CJK character, we print the characters. elif len(_lowerCamelCase ) > 0 and self._is_chinese_char(ord(text[-1] ) ): SCREAMING_SNAKE_CASE : List[Any] = text[self.print_len :] self.print_len += len(_lowerCamelCase ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: SCREAMING_SNAKE_CASE : Optional[int] = text[self.print_len : text.rfind(''' ''' ) + 1] self.print_len += len(_lowerCamelCase ) self.on_finalized_text(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[Any]: # Flush the cache, if it exists if len(self.token_cache ) > 0: SCREAMING_SNAKE_CASE : List[str] = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) SCREAMING_SNAKE_CASE : str = text[self.print_len :] SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Optional[int] = 0 else: SCREAMING_SNAKE_CASE : Any = '''''' SCREAMING_SNAKE_CASE : Optional[int] = True self.on_finalized_text(_lowerCamelCase , stream_end=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = False ) ->Tuple: print(_lowerCamelCase , flush=_lowerCamelCase , end='''''' if not stream_end else None ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ( (cp >= 0x4_e00 and cp <= 0x9_fff) or (cp >= 0x3_400 and cp <= 0x4_dbf) # or (cp >= 0x20_000 and cp <= 0x2a_6df) # or (cp >= 0x2a_700 and cp <= 0x2b_73f) # or (cp >= 0x2b_740 and cp <= 0x2b_81f) # or (cp >= 0x2b_820 and cp <= 0x2c_eaf) # or (cp >= 0xf_900 and cp <= 0xf_aff) or (cp >= 0x2f_800 and cp <= 0x2f_a1f) # ): # return True return False class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase = False , _lowerCamelCase = None , **_lowerCamelCase ) ->Union[str, Any]: super().__init__(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = Queue() SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[str] = timeout def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = False ) ->str: self.text_queue.put(_lowerCamelCase , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ) ->Tuple: return self def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
19
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a__ : List[str] = logging.get_logger(__name__) # General docstring a__ : Tuple = '''MobileNetV1Config''' # Base docstring a__ : Optional[Any] = '''google/mobilenet_v1_1.0_224''' a__ : Tuple = [1, 1_024, 7, 7] # Image classification docstring a__ : Optional[int] = '''google/mobilenet_v1_1.0_224''' a__ : int = '''tabby, tabby cat''' a__ : List[Any] = [ '''google/mobilenet_v1_1.0_224''', '''google/mobilenet_v1_0.75_192''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def UpperCAmelCase_( a__ , a__ , a__=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = {} if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[str] = model.mobilenet_va else: SCREAMING_SNAKE_CASE : Union[str, Any] = model SCREAMING_SNAKE_CASE : Optional[int] = '''MobilenetV1/Conv2d_0/''' SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.convolution.weight SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = backbone.conv_stem.normalization.weight SCREAMING_SNAKE_CASE : Union[str, Any] = backbone.conv_stem.normalization.running_mean SCREAMING_SNAKE_CASE : Any = backbone.conv_stem.normalization.running_var for i in range(13 ): SCREAMING_SNAKE_CASE : Dict = i + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = i * 2 SCREAMING_SNAKE_CASE : Any = backbone.layer[pt_index] SCREAMING_SNAKE_CASE : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" SCREAMING_SNAKE_CASE : Any = pointer.convolution.weight SCREAMING_SNAKE_CASE : Tuple = pointer.normalization.bias SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.running_var SCREAMING_SNAKE_CASE : List[Any] = backbone.layer[pt_index + 1] SCREAMING_SNAKE_CASE : Any = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" SCREAMING_SNAKE_CASE : Dict = pointer.convolution.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : int = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : str = pointer.normalization.running_var if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[Any] = '''MobilenetV1/Logits/Conv2d_1c_1x1/''' SCREAMING_SNAKE_CASE : List[str] = model.classifier.weight SCREAMING_SNAKE_CASE : List[str] = model.classifier.bias return tf_to_pt_map def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ''' '''https://www.tensorflow.org/install/ for installation instructions.''' ) raise # Load weights from TF model SCREAMING_SNAKE_CASE : Optional[Any] = tf.train.list_variables(a__ ) SCREAMING_SNAKE_CASE : List[Any] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) SCREAMING_SNAKE_CASE : Tuple = tf.train.load_variable(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = array # Build TF to PyTorch weights loading map SCREAMING_SNAKE_CASE : int = _build_tf_to_pytorch_map(a__ , a__ , a__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue SCREAMING_SNAKE_CASE : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('''Transposing depthwise''' ) SCREAMING_SNAKE_CASE : Tuple = np.transpose(a__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('''Transposing''' ) if len(pointer.shape ) == 2: # copying into linear layer SCREAMING_SNAKE_CASE : Union[str, Any] = array.squeeze().transpose() else: SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(a__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(a__ ) tf_weights.pop(a__ , a__ ) tf_weights.pop(name + '''/RMSProp''' , a__ ) tf_weights.pop(name + '''/RMSProp_1''' , a__ ) tf_weights.pop(name + '''/ExponentialMovingAverage''' , a__ ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = features.shape[-2:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = conv_layer.stride SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = conv_layer.kernel_size if in_height % stride_height == 0: SCREAMING_SNAKE_CASE : List[str] = max(kernel_height - stride_height , 0 ) else: SCREAMING_SNAKE_CASE : str = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: SCREAMING_SNAKE_CASE : int = max(kernel_width - stride_width , 0 ) else: SCREAMING_SNAKE_CASE : Tuple = max(kernel_width - (in_width % stride_width) , 0 ) SCREAMING_SNAKE_CASE : List[str] = pad_along_width // 2 SCREAMING_SNAKE_CASE : Any = pad_along_width - pad_left SCREAMING_SNAKE_CASE : str = pad_along_height // 2 SCREAMING_SNAKE_CASE : Optional[int] = pad_along_height - pad_top SCREAMING_SNAKE_CASE : List[Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(a__ , a__ , '''constant''' , 0.0 ) class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 1 , _lowerCamelCase = 1 , _lowerCamelCase = False , _lowerCamelCase = True , _lowerCamelCase = True , ) ->None: super().__init__() SCREAMING_SNAKE_CASE : Any = config if in_channels % groups != 0: raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) SCREAMING_SNAKE_CASE : Any = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) SCREAMING_SNAKE_CASE : List[str] = nn.Convad( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=_lowerCamelCase , stride=_lowerCamelCase , padding=_lowerCamelCase , groups=_lowerCamelCase , bias=_lowerCamelCase , padding_mode='''zeros''' , ) if use_normalization: SCREAMING_SNAKE_CASE : List[Any] = nn.BatchNormad( num_features=_lowerCamelCase , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=_lowerCamelCase , track_running_stats=_lowerCamelCase , ) else: SCREAMING_SNAKE_CASE : Dict = None if use_activation: if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Any = ACTaFN[use_activation] elif isinstance(config.hidden_act , _lowerCamelCase ): SCREAMING_SNAKE_CASE : List[str] = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : List[Any] = config.hidden_act else: SCREAMING_SNAKE_CASE : Optional[Any] = None def __lowerCAmelCase ( self , _lowerCamelCase ) ->torch.Tensor: if self.config.tf_padding: SCREAMING_SNAKE_CASE : List[Any] = apply_tf_padding(_lowerCamelCase , self.convolution ) SCREAMING_SNAKE_CASE : Dict = self.convolution(_lowerCamelCase ) if self.normalization is not None: SCREAMING_SNAKE_CASE : int = self.normalization(_lowerCamelCase ) if self.activation is not None: SCREAMING_SNAKE_CASE : List[Any] = self.activation(_lowerCamelCase ) return features class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = MobileNetVaConfig __SCREAMING_SNAKE_CASE : List[Any] = load_tf_weights_in_mobilenet_va __SCREAMING_SNAKE_CASE : int = 'mobilenet_v1' __SCREAMING_SNAKE_CASE : int = 'pixel_values' __SCREAMING_SNAKE_CASE : List[str] = False def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: if isinstance(_lowerCamelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_lowerCamelCase , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) a__ : str = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Union[str, Any] = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase = True ) ->Dict: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = config SCREAMING_SNAKE_CASE : Dict = 32 SCREAMING_SNAKE_CASE : Optional[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) SCREAMING_SNAKE_CASE : str = MobileNetVaConvLayer( _lowerCamelCase , in_channels=config.num_channels , out_channels=_lowerCamelCase , kernel_size=3 , stride=2 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] SCREAMING_SNAKE_CASE : Any = nn.ModuleList() for i in range(13 ): SCREAMING_SNAKE_CASE : int = out_channels if strides[i] == 2 or i == 0: depth *= 2 SCREAMING_SNAKE_CASE : Tuple = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=3 , stride=strides[i] , groups=_lowerCamelCase , ) ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=1 , ) ) SCREAMING_SNAKE_CASE : int = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: raise NotImplementedError @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.conv_stem(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): SCREAMING_SNAKE_CASE : Optional[int] = layer_module(_lowerCamelCase ) if output_hidden_states: SCREAMING_SNAKE_CASE : List[str] = all_hidden_states + (hidden_states,) SCREAMING_SNAKE_CASE : List[str] = hidden_states if self.pooler is not None: SCREAMING_SNAKE_CASE : Tuple = torch.flatten(self.pooler(_lowerCamelCase ) , start_dim=1 ) else: SCREAMING_SNAKE_CASE : List[Any] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_lowerCamelCase , pooler_output=_lowerCamelCase , hidden_states=_lowerCamelCase , ) @add_start_docstrings( '\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->None: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = config.num_labels SCREAMING_SNAKE_CASE : str = MobileNetVaModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head SCREAMING_SNAKE_CASE : Optional[int] = nn.Dropout(config.classifier_dropout_prob , inplace=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = nn.Linear(_lowerCamelCase , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, ImageClassifierOutputWithNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va(_lowerCamelCase , output_hidden_states=_lowerCamelCase , return_dict=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE : Tuple = self.classifier(self.dropout(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : int = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : Any = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : Optional[int] = '''single_label_classification''' else: SCREAMING_SNAKE_CASE : Dict = '''multi_label_classification''' if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Any = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : Dict = loss_fct(_lowerCamelCase , _lowerCamelCase ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : List[Any] = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : List[Any] = loss_fct(_lowerCamelCase , _lowerCamelCase ) if not return_dict: SCREAMING_SNAKE_CASE : Optional[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_lowerCamelCase , logits=_lowerCamelCase , hidden_states=outputs.hidden_states , )
19
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer a__ : Any = logging.get_logger(__name__) a__ : Tuple = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Optional[int] = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } a__ : Any = { '''yjernite/retribert-base-uncased''': 512, } a__ : int = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : str = PRETRAINED_INIT_CONFIGURATION __SCREAMING_SNAKE_CASE : List[str] = RetriBertTokenizer __SCREAMING_SNAKE_CASE : List[str] = ['input_ids', 'attention_mask'] def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase="[UNK]" , _lowerCamelCase="[SEP]" , _lowerCamelCase="[PAD]" , _lowerCamelCase="[CLS]" , _lowerCamelCase="[MASK]" , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ) ->int: super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[str] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = do_lower_case SCREAMING_SNAKE_CASE : List[Any] = strip_accents SCREAMING_SNAKE_CASE : List[Any] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : Optional[int] = normalizer_class(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = do_lower_case def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->List[str]: SCREAMING_SNAKE_CASE : int = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: SCREAMING_SNAKE_CASE : Union[str, Any] = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
19
import math def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(a__ ) def UpperCAmelCase_( a__ = 1 / 12_345 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : int = 3 while True: SCREAMING_SNAKE_CASE : Union[str, Any] = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(a__ ): SCREAMING_SNAKE_CASE : List[str] = int(a__ ) total_partitions += 1 if check_partition_perfect(a__ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(a__ ) integer += 1 if __name__ == "__main__": print(F"{solution() = }")
19
1
import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = TaConfig.from_json_file(a__ ) print(F"""Building PyTorch model from configuration: {config}""" ) SCREAMING_SNAKE_CASE : Dict = TaForConditionalGeneration(a__ ) # Load weights from tf checkpoint load_tf_weights_in_ta(a__ , a__ , a__ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(a__ ) if __name__ == "__main__": a__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) a__ : Optional[int] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
19
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar a__ : Any = TypeVar('''T''') def UpperCAmelCase_( a__ ): """simple docstring""" return (position - 1) // 2 def UpperCAmelCase_( a__ ): """simple docstring""" return (2 * position) + 1 def UpperCAmelCase_( a__ ): """simple docstring""" return (2 * position) + 2 class a_ ( Generic[T] ): """simple docstring""" def __init__( self ) ->None: SCREAMING_SNAKE_CASE : list[tuple[T, int]] = [] SCREAMING_SNAKE_CASE : dict[T, int] = {} SCREAMING_SNAKE_CASE : int = 0 def __len__( self ) ->int: return self.elements def __repr__( self ) ->str: return str(self.heap ) def __lowerCAmelCase ( self ) ->bool: # Check if the priority queue is empty return self.elements == 0 def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) SCREAMING_SNAKE_CASE : Tuple = self.elements self.elements += 1 self._bubble_up(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.heap[0] self._bubble_down(_lowerCamelCase ) return elem def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Update the weight of the given key SCREAMING_SNAKE_CASE : List[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE : Any = (elem, weight) if position > 0: SCREAMING_SNAKE_CASE : List[Any] = get_parent_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._bubble_up(_lowerCamelCase ) else: self._bubble_down(_lowerCamelCase ) else: self._bubble_down(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Place a node at the proper position (upward movement) [to be used internally # only] SCREAMING_SNAKE_CASE : Optional[Any] = self.position_map[elem] if curr_pos == 0: return None SCREAMING_SNAKE_CASE : str = get_parent_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.heap[curr_pos] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_up(_lowerCamelCase ) return None def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Place a node at the proper position (downward movement) [to be used # internally only] SCREAMING_SNAKE_CASE : Optional[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.heap[curr_pos] SCREAMING_SNAKE_CASE : List[str] = get_child_left_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = get_child_right_position(_lowerCamelCase ) if child_left_position < self.elements and child_right_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.heap[child_left_position] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) if child_left_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) else: return None if child_right_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) return None def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Swap the nodes at the given positions SCREAMING_SNAKE_CASE : Optional[int] = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE : Any = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) SCREAMING_SNAKE_CASE : Optional[int] = nodea_pos SCREAMING_SNAKE_CASE : List[str] = nodea_pos class a_ ( Generic[T] ): """simple docstring""" def __init__( self ) ->None: SCREAMING_SNAKE_CASE : dict[T, dict[T, int]] = {} SCREAMING_SNAKE_CASE : int = 0 def __repr__( self ) ->str: return str(self.connections ) def __len__( self ) ->int: return self.nodes def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Add a node in the graph if it is not in the graph if node not in self.connections: SCREAMING_SNAKE_CASE : Any = {} self.nodes += 1 def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->None: # Add an edge between 2 nodes in the graph self.add_node(_lowerCamelCase ) self.add_node(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = weight SCREAMING_SNAKE_CASE : str = weight def UpperCAmelCase_( a__ , ): """simple docstring""" SCREAMING_SNAKE_CASE : dict[T, int] = {node: maxsize for node in graph.connections} SCREAMING_SNAKE_CASE : dict[T, T | None] = {node: None for node in graph.connections} SCREAMING_SNAKE_CASE : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(a__ , a__ ) if priority_queue.is_empty(): return dist, parent # initialization SCREAMING_SNAKE_CASE : List[Any] = priority_queue.extract_min() SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE : Any = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) SCREAMING_SNAKE_CASE : str = node # running prim's algorithm while not priority_queue.is_empty(): SCREAMING_SNAKE_CASE : List[str] = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE : List[Any] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) SCREAMING_SNAKE_CASE : str = node return dist, parent
19
1
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE : Any = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Any = logging.get_verbosity() SCREAMING_SNAKE_CASE : Any = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) SCREAMING_SNAKE_CASE : List[Any] = '''Testing 1, 2, 3''' # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(_lowerCamelCase ) as cl: logger.warning(_lowerCamelCase ) self.assertEqual(cl.out , msg + '''\n''' ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(_lowerCamelCase ) as cl: logger.warning(_lowerCamelCase ) self.assertEqual(cl.out , '''''' ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(_lowerCamelCase ) as cl: logger.warning(_lowerCamelCase ) self.assertEqual(cl.out , msg + '''\n''' ) # restore to the original level logging.set_verbosity(_lowerCamelCase ) @mockenv(TRANSFORMERS_VERBOSITY='''error''' ) def __lowerCAmelCase ( self ) ->int: # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE : List[str] = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) SCREAMING_SNAKE_CASE : List[str] = os.getenv('''TRANSFORMERS_VERBOSITY''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : str = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_verbosity() self.assertEqual( _lowerCamelCase , _lowerCamelCase , F"""TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}""" , ) # restore to the original level SCREAMING_SNAKE_CASE : Optional[int] = '''''' transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY='''super-error''' ) def __lowerCAmelCase ( self ) ->Optional[int]: # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE : str = logging.logging.getLogger() with CaptureLogger(_lowerCamelCase ) as cl: # this action activates the env var logging.get_logger('''transformers.models.bart.tokenization_bart''' ) self.assertIn('''Unknown option TRANSFORMERS_VERBOSITY=super-error''' , cl.out ) # no need to restore as nothing was changed def __lowerCAmelCase ( self ) ->List[Any]: # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE : Dict = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) SCREAMING_SNAKE_CASE : Dict = '''Testing 1, 2, 3''' with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''1''' ): # nothing should be logged as env var disables this method with CaptureLogger(_lowerCamelCase ) as cl: logger.warning_advice(_lowerCamelCase ) self.assertEqual(cl.out , '''''' ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''''' ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(_lowerCamelCase ) as cl: logger.warning_advice(_lowerCamelCase ) self.assertEqual(cl.out , msg + '''\n''' ) def UpperCAmelCase_( ): """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
19
from math import pi, sqrt, tan def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''surface_area_cube() only accepts non-negative values''' ) return 6 * side_length**2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if length < 0 or breadth < 0 or height < 0: raise ValueError('''surface_area_cuboid() only accepts non-negative values''' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_sphere() only accepts non-negative values''' ) return 4 * pi * radius**2 def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' ) return 3 * pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cone() only accepts non-negative values''' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( '''surface_area_conical_frustum() only accepts non-negative values''' ) SCREAMING_SNAKE_CASE : Optional[Any] = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cylinder() only accepts non-negative values''' ) return 2 * pi * radius * (height + radius) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if torus_radius < 0 or tube_radius < 0: raise ValueError('''surface_area_torus() only accepts non-negative values''' ) if torus_radius < tube_radius: raise ValueError( '''surface_area_torus() does not support spindle or self intersecting tori''' ) return 4 * pow(a__ , 2 ) * torus_radius * tube_radius def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if length < 0 or width < 0: raise ValueError('''area_rectangle() only accepts non-negative values''' ) return length * width def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''area_square() only accepts non-negative values''' ) return side_length**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_triangle() only accepts non-negative values''' ) return (base * height) / 2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('''Given three sides do not form a triangle''' ) SCREAMING_SNAKE_CASE : int = (sidea + sidea + sidea) / 2 SCREAMING_SNAKE_CASE : List[str] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_parallelogram() only accepts non-negative values''' ) return base * height def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if basea < 0 or basea < 0 or height < 0: raise ValueError('''area_trapezium() only accepts non-negative values''' ) return 1 / 2 * (basea + basea) * height def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''area_circle() only accepts non-negative values''' ) return pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius_x < 0 or radius_y < 0: raise ValueError('''area_ellipse() only accepts non-negative values''' ) return pi * radius_x * radius_y def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if diagonal_a < 0 or diagonal_a < 0: raise ValueError('''area_rhombus() only accepts non-negative values''' ) return 1 / 2 * diagonal_a * diagonal_a def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if not isinstance(a__ , a__ ) or sides < 3: raise ValueError( '''area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides''' ) elif length < 0: raise ValueError( '''area_reg_polygon() only accepts non-negative values as \ length of a side''' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('''[DEMO] Areas of various geometric shapes: \n''') print(F"Rectangle: {area_rectangle(10, 20) = }") print(F"Square: {area_square(10) = }") print(F"Triangle: {area_triangle(10, 10) = }") print(F"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(F"Parallelogram: {area_parallelogram(10, 20) = }") print(F"Rhombus: {area_rhombus(10, 20) = }") print(F"Trapezium: {area_trapezium(10, 20, 30) = }") print(F"Circle: {area_circle(20) = }") print(F"Ellipse: {area_ellipse(10, 20) = }") print('''\nSurface Areas of various geometric shapes: \n''') print(F"Cube: {surface_area_cube(20) = }") print(F"Cuboid: {surface_area_cuboid(10, 20, 30) = }") print(F"Sphere: {surface_area_sphere(20) = }") print(F"Hemisphere: {surface_area_hemisphere(20) = }") print(F"Cone: {surface_area_cone(10, 20) = }") print(F"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") print(F"Cylinder: {surface_area_cylinder(10, 20) = }") print(F"Torus: {surface_area_torus(20, 10) = }") print(F"Equilateral Triangle: {area_reg_polygon(3, 10) = }") print(F"Square: {area_reg_polygon(4, 10) = }") print(F"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
19
1
import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = PhobertTokenizer __SCREAMING_SNAKE_CASE : Optional[Any] = False def __lowerCAmelCase ( self ) ->List[Any]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE : Optional[Any] = ['''T@@''', '''i''', '''I''', '''R@@''', '''r''', '''e@@'''] SCREAMING_SNAKE_CASE : Union[str, Any] = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) ) SCREAMING_SNAKE_CASE : str = ['''#version: 0.2''', '''l à</w>'''] SCREAMING_SNAKE_CASE : Dict = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: for token in vocab_tokens: fp.write(F"""{token} {vocab_tokens[token]}\n""" ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(_lowerCamelCase ) ) def __lowerCAmelCase ( self , **_lowerCamelCase ) ->Union[str, Any]: kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Any = '''Tôi là VinAI Research''' SCREAMING_SNAKE_CASE : List[Any] = '''T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>''' return input_text, output_text def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Union[str, Any] = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE : Any = '''Tôi là VinAI Research''' SCREAMING_SNAKE_CASE : List[str] = '''T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h'''.split() SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(_lowerCamelCase ) print(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE : Optional[Any] = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , _lowerCamelCase )
19
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: a__ : List[str] = None a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Dict = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/mbart-large-en-ro''': '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json''', '''facebook/mbart-large-cc25''': '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json''', }, } a__ : str = { '''facebook/mbart-large-en-ro''': 1_024, '''facebook/mbart-large-cc25''': 1_024, } # fmt: off a__ : List[str] = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = ['input_ids', 'attention_mask'] __SCREAMING_SNAKE_CASE : Tuple = MBartTokenizer __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase , ) ->List[Any]: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : List[str] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token super().__init__( vocab_file=_lowerCamelCase , tokenizer_file=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , src_lang=_lowerCamelCase , tgt_lang=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Any = vocab_file SCREAMING_SNAKE_CASE : List[Any] = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : Any = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) SCREAMING_SNAKE_CASE : int = { lang_code: self.convert_tokens_to_ids(_lowerCamelCase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE : List[str] = src_lang if src_lang is not None else '''en_XX''' SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __lowerCAmelCase ( self ) ->str: return self._src_lang @src_lang.setter def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[int] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : str = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) ->Optional[Any]: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[str] = self(_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang_id return inputs def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = "en_XX" , _lowerCamelCase = None , _lowerCamelCase = "ro_RO" , **_lowerCamelCase , ) ->BatchEncoding: SCREAMING_SNAKE_CASE : List[str] = src_lang SCREAMING_SNAKE_CASE : List[str] = tgt_lang return super().prepare_seqaseq_batch(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Dict: return self.set_src_lang_special_tokens(self.src_lang ) def __lowerCAmelCase ( self ) ->List[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : str = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Any = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file , _lowerCamelCase ) return (out_vocab_file,)
19
1
def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
19
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging a__ : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=768 ) ->List[Any]: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = proj_size SCREAMING_SNAKE_CASE : Any = CLIPVisionModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = PaintByExampleMapper(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = nn.LayerNorm(config.hidden_size ) SCREAMING_SNAKE_CASE : int = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=False ) ->int: SCREAMING_SNAKE_CASE : Optional[Any] = self.model(pixel_values=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = clip_output.pooler_output SCREAMING_SNAKE_CASE : Optional[Any] = self.mapper(latent_states[:, None] ) SCREAMING_SNAKE_CASE : Tuple = self.final_layer_norm(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.proj_out(_lowerCamelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->List[str]: super().__init__() SCREAMING_SNAKE_CASE : str = (config.num_hidden_layers + 1) // 5 SCREAMING_SNAKE_CASE : List[Any] = config.hidden_size SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : Optional[Any] = nn.ModuleList( [ BasicTransformerBlock(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , activation_fn='''gelu''' , attention_bias=_lowerCamelCase ) for _ in range(_lowerCamelCase ) ] ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: for block in self.blocks: SCREAMING_SNAKE_CASE : Optional[int] = block(_lowerCamelCase ) return hidden_states
19
1
import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import logging a__ : List[Any] = ['''bart.large''', '''bart.large.mnli''', '''bart.large.cnn''', '''bart_xsum/model.pt'''] a__ : int = {'''bart.large''': BartModel, '''bart.large.mnli''': BartForSequenceClassification} if version.parse(fairseq.__version__) < version.parse('''0.9.0'''): raise Exception('''requires fairseq >= 0.9.0''') logging.set_verbosity_info() a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Union[str, Any] = ''' Hello world! cécé herlolip''' a__ : Tuple = [ ('''model.classification_heads.mnli.dense.weight''', '''classification_head.dense.weight'''), ('''model.classification_heads.mnli.dense.bias''', '''classification_head.dense.bias'''), ('''model.classification_heads.mnli.out_proj.weight''', '''classification_head.out_proj.weight'''), ('''model.classification_heads.mnli.out_proj.bias''', '''classification_head.out_proj.bias'''), ] def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', ] for k in ignore_keys: state_dict.pop(a__ , a__ ) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = dct.pop(a__ ) SCREAMING_SNAKE_CASE : List[str] = val def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = torch.load(a__ , map_location='''cpu''' ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.hub.load('''pytorch/fairseq''' , '''bart.large.cnn''' ).eval() hub_interface.model.load_state_dict(sd['''model'''] ) return hub_interface def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = emb.weight.shape SCREAMING_SNAKE_CASE : Optional[Any] = nn.Linear(a__ , a__ , bias=a__ ) SCREAMING_SNAKE_CASE : Any = emb.weight.data return lin_layer @torch.no_grad() def UpperCAmelCase_( a__ , a__ , a__=None ): """simple docstring""" if not os.path.exists(a__ ): SCREAMING_SNAKE_CASE : int = torch.hub.load('''pytorch/fairseq''' , a__ ).eval() else: SCREAMING_SNAKE_CASE : Optional[int] = load_xsum_checkpoint(a__ ) bart.model.upgrade_state_dict(bart.model.state_dict() ) if hf_checkpoint_name is None: SCREAMING_SNAKE_CASE : List[Any] = checkpoint_path.replace('''.''' , '''-''' ) SCREAMING_SNAKE_CASE : str = BartConfig.from_pretrained(a__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = bart.encode(a__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = BartTokenizer.from_pretrained(a__ ).encode(a__ , return_tensors='''pt''' ).unsqueeze(0 ) if not torch.eq(a__ , a__ ).all(): raise ValueError( F"""converted tokenizer and pretrained tokenizer returned different output: {tokens} != {tokensa}""" ) if checkpoint_path == "bart.large.mnli": SCREAMING_SNAKE_CASE : List[str] = bart.state_dict() remove_ignore_keys_(a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = state_dict['''model.decoder.embed_tokens.weight'''] for src, dest in mnli_rename_keys: rename_key(a__ , a__ , a__ ) SCREAMING_SNAKE_CASE : str = BartForSequenceClassification(a__ ).eval() model.load_state_dict(a__ ) SCREAMING_SNAKE_CASE : List[Any] = bart.predict('''mnli''' , a__ , return_logits=a__ ) SCREAMING_SNAKE_CASE : Dict = model(a__ )[0] # logits else: # no classification heads to worry about SCREAMING_SNAKE_CASE : Union[str, Any] = bart.model.state_dict() remove_ignore_keys_(a__ ) SCREAMING_SNAKE_CASE : List[Any] = state_dict['''decoder.embed_tokens.weight'''] SCREAMING_SNAKE_CASE : Optional[Any] = bart.extract_features(a__ ) if hf_checkpoint_name == "facebook/bart-large": SCREAMING_SNAKE_CASE : Dict = BartModel(a__ ).eval() model.load_state_dict(a__ ) SCREAMING_SNAKE_CASE : Any = model(a__ ).model[0] else: SCREAMING_SNAKE_CASE : Tuple = BartForConditionalGeneration(a__ ).eval() # an existing summarization ckpt model.model.load_state_dict(a__ ) if hasattr(a__ , '''lm_head''' ): SCREAMING_SNAKE_CASE : List[str] = make_linear_from_emb(model.model.shared ) SCREAMING_SNAKE_CASE : Optional[Any] = model.model(a__ )[0] # Check results if fairseq_output.shape != new_model_outputs.shape: raise ValueError( F"""`fairseq_output` shape and `new_model_output` shape are different: {fairseq_output.shape=}, {new_model_outputs.shape}""" ) if (fairseq_output != new_model_outputs).any().item(): raise ValueError('''Some values in `fairseq_output` are different from `new_model_outputs`''' ) Path(a__ ).mkdir(exist_ok=a__ ) model.save_pretrained(a__ ) if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default=None, type=str, help='''Which huggingface architecture to use: bart-large-xsum''' ) a__ : Tuple = parser.parse_args() convert_bart_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, hf_checkpoint_name=args.hf_config)
19
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 a__ : Tuple = '''▁''' a__ : List[Any] = {'''vocab_file''': '''spiece.model'''} a__ : Optional[Any] = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } a__ : str = { '''google/pegasus-xsum''': 512, } a__ : str = logging.get_logger(__name__) class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : str = ['input_ids', 'attention_mask'] def __init__( self , _lowerCamelCase , _lowerCamelCase="<pad>" , _lowerCamelCase="</s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<mask_2>" , _lowerCamelCase="<mask_1>" , _lowerCamelCase=None , _lowerCamelCase=103 , _lowerCamelCase = None , **_lowerCamelCase , ) ->None: SCREAMING_SNAKE_CASE : Dict = offset if additional_special_tokens is not None: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError( F"""additional_special_tokens should be of type {type(_lowerCamelCase )}, but is""" F""" {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : List[Any] = ( ([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(_lowerCamelCase ) , self.offset - 1 ) ] if len(set(_lowerCamelCase ) ) != len(_lowerCamelCase ): 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}.""" ) SCREAMING_SNAKE_CASE : Dict = additional_special_tokens_extended else: SCREAMING_SNAKE_CASE : str = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F"""<unk_{i}>""" for i in range(2 , self.offset )] SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , mask_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token_sent=_lowerCamelCase , offset=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[str] = mask_token_sent SCREAMING_SNAKE_CASE : Optional[int] = vocab_file SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) # add special tokens to encoder dict SCREAMING_SNAKE_CASE : Dict[int, str] = { 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 )} ) SCREAMING_SNAKE_CASE : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def __lowerCAmelCase ( self ) ->int: return len(self.sp_model ) + self.offset def __lowerCAmelCase ( self ) ->Dict[str, int]: SCREAMING_SNAKE_CASE : Union[str, Any] = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = self.__dict__.copy() SCREAMING_SNAKE_CASE : str = None return state def __setstate__( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : List[str] = {} SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.piece_to_id(_lowerCamelCase ) return sp_id + self.offset def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: SCREAMING_SNAKE_CASE : Dict = self.sp_model.IdToPiece(index - self.offset ) return token def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : int = '''''' 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(_lowerCamelCase ) + token SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(_lowerCamelCase ) out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def __lowerCAmelCase ( self , _lowerCamelCase=False ) ->str: return 1 def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Dict = 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ) ->List[int]: if already_has_special_tokens: return self._special_token_mask(_lowerCamelCase ) elif token_ids_a is None: return self._special_token_mask(_lowerCamelCase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->List[int]: 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : int = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE : Tuple = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
19
1
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class a_ ( unittest.TestCase ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=99 , _lowerCamelCase=32 , _lowerCamelCase=5 , _lowerCamelCase=4 , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=512 , _lowerCamelCase=16 , _lowerCamelCase=2 , _lowerCamelCase=0.0_2 , _lowerCamelCase=4 , ) ->Optional[int]: SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : Tuple = batch_size SCREAMING_SNAKE_CASE : Union[str, Any] = seq_length SCREAMING_SNAKE_CASE : Any = is_training SCREAMING_SNAKE_CASE : Optional[int] = use_attention_mask SCREAMING_SNAKE_CASE : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : List[Any] = use_labels SCREAMING_SNAKE_CASE : str = vocab_size SCREAMING_SNAKE_CASE : List[Any] = hidden_size SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE : List[str] = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[int] = type_vocab_size SCREAMING_SNAKE_CASE : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = num_choices def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Tuple = None if self.use_attention_mask: SCREAMING_SNAKE_CASE : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Tuple = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE : List[str] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Dict = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Any = FlaxRobertaModelTester(self ) @slow def __lowerCAmelCase ( self ) ->List[Any]: for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[Any] = model_class_name.from_pretrained('''roberta-base''' , from_pt=_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase )
19
def UpperCAmelCase_( a__ ): """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Tuple = 1 while repunit: SCREAMING_SNAKE_CASE : Dict = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def UpperCAmelCase_( a__ = 1_000_000 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(a__ ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F"{solution() = }")
19
1
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def UpperCAmelCase_( *a__ , a__ = None , a__=True , a__=2 ): """simple docstring""" from .. import __version__ SCREAMING_SNAKE_CASE : Tuple = take_from SCREAMING_SNAKE_CASE : List[str] = () if not isinstance(args[0] , a__ ): SCREAMING_SNAKE_CASE : Dict = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a__ ).base_version ) >= version.parse(a__ ): raise ValueError( F"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" F""" version {__version__} is >= {version_name}""" ) SCREAMING_SNAKE_CASE : Optional[int] = None if isinstance(a__ , a__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a__ ),) SCREAMING_SNAKE_CASE : Union[str, Any] = F"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(a__ , a__ ): values += (getattr(a__ , a__ ),) SCREAMING_SNAKE_CASE : str = F"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: SCREAMING_SNAKE_CASE : Optional[Any] = F"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: SCREAMING_SNAKE_CASE : int = warning + ''' ''' if standard_warn else '''''' warnings.warn(warning + message , a__ , stacklevel=a__ ) if isinstance(a__ , a__ ) and len(a__ ) > 0: SCREAMING_SNAKE_CASE : str = inspect.getouterframes(inspect.currentframe() )[1] SCREAMING_SNAKE_CASE : Tuple = call_frame.filename SCREAMING_SNAKE_CASE : Optional[Any] = call_frame.lineno SCREAMING_SNAKE_CASE : Tuple = call_frame.function SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(a__ ) == 0: return elif len(a__ ) == 1: return values[0] return values
19
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=32 , _lowerCamelCase=3 , _lowerCamelCase=4 , _lowerCamelCase=[10, 20, 30, 40] , _lowerCamelCase=[2, 2, 3, 2] , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=10 , _lowerCamelCase=0.0_2 , _lowerCamelCase=["stage2", "stage3", "stage4"] , _lowerCamelCase=3 , _lowerCamelCase=None , ) ->Dict: SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Optional[Any] = batch_size SCREAMING_SNAKE_CASE : Optional[Any] = image_size SCREAMING_SNAKE_CASE : str = num_channels SCREAMING_SNAKE_CASE : Any = num_stages SCREAMING_SNAKE_CASE : List[str] = hidden_sizes SCREAMING_SNAKE_CASE : Optional[Any] = depths SCREAMING_SNAKE_CASE : Any = is_training SCREAMING_SNAKE_CASE : Tuple = use_labels SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : int = out_features SCREAMING_SNAKE_CASE : List[str] = num_labels SCREAMING_SNAKE_CASE : int = scope SCREAMING_SNAKE_CASE : Optional[Any] = num_stages def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : str = None if self.use_labels: SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) ->List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def __lowerCAmelCase ( self ) ->Any: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_lowerCamelCase , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_lowerCamelCase , loss_ignore_index=255 , num_labels=self.num_labels , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : List[Any] = UperNetForSemanticSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = (UperNetForSemanticSegmentation,) if is_torch_available() else () __SCREAMING_SNAKE_CASE : List[str] = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {} __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Union[str, Any] = False __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : Any = False def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[Any] = UperNetModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def __lowerCAmelCase ( self ) ->str: 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 __lowerCAmelCase ( self ) ->str: return def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Optional[int] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase ) @unittest.skip(reason='''UperNet does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) ->Union[str, Any]: pass @unittest.skip(reason='''UperNet does not support input and output embeddings''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->str: pass @require_torch_multi_gpu @unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def __lowerCAmelCase ( self ) ->str: pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowerCAmelCase ( self ) ->Tuple: pass def __lowerCAmelCase ( self ) ->int: def check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) SCREAMING_SNAKE_CASE : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # ConvNext'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] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Union[str, Any] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : str = _config_zero_init(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip(reason='''UperNet does not have tied weights''' ) def __lowerCAmelCase ( self ) ->List[Any]: pass @slow def __lowerCAmelCase ( self ) ->List[Any]: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Any = UperNetForSemanticSegmentation.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = hf_hub_download( repo_id='''hf-internal-testing/fixtures_ade20k''' , repo_type='''dataset''' , filename='''ADE_val_00000001.jpg''' ) SCREAMING_SNAKE_CASE : Any = Image.open(a__ ).convert('''RGB''' ) return image @require_torch @require_vision @slow class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny''' ) SCREAMING_SNAKE_CASE : Tuple = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny''' ) SCREAMING_SNAKE_CASE : str = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) )
19
1
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging a__ : List[Any] = logging.get_logger(__name__) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(a__ ) == len(a__ ), F"""{len(a__ )} != {len(a__ )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) a__ : List[str] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } a__ : List[str] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def UpperCAmelCase_( a__ , a__ ): """simple docstring""" try: SCREAMING_SNAKE_CASE : Tuple = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" F""" {n_student}""" ) return list(range(a__ ) ) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if n_student > n_teacher: raise ValueError(F"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(a__ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def UpperCAmelCase_( a__ , a__ = "student" , a__ = None , a__ = None , a__=False , a__=None , a__=None , **a__ , ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = '''encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.''' assert (e is not None) or (d is not None), _msg if isinstance(a__ , a__ ): AutoTokenizer.from_pretrained(a__ ).save_pretrained(a__ ) # purely for convenience SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained(a__ ).eval() else: assert isinstance(a__ , a__ ), F"""teacher must be a model or string got type {type(a__ )}""" SCREAMING_SNAKE_CASE : List[Any] = teacher.config.to_diff_dict() try: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: SCREAMING_SNAKE_CASE : Optional[Any] = teacher_e if d is None: SCREAMING_SNAKE_CASE : Any = teacher_d init_kwargs.update({'''encoder_layers''': e, '''decoder_layers''': d} ) except AttributeError: # T5 if hasattr(teacher.config , '''num_encoder_layers''' ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: SCREAMING_SNAKE_CASE : List[Any] = teacher_e if d is None: SCREAMING_SNAKE_CASE : List[str] = teacher_d if hasattr(teacher.config , '''num_encoder_layers''' ): init_kwargs.update({'''num_encoder_layers''': e, '''num_decoder_layers''': d} ) else: init_kwargs.update({'''num_layers''': e, '''num_decoder_layers''': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(a__ ) # Copy weights SCREAMING_SNAKE_CASE : Dict = teacher.config_class(**a__ ) SCREAMING_SNAKE_CASE : int = AutoModelForSeqaSeqLM.from_config(a__ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. SCREAMING_SNAKE_CASE : Union[str, Any] = student.load_state_dict(teacher.state_dict() , strict=a__ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = list(range(a__ ) ), list(range(a__ ) ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" F""" {save_path}""" ) student.save_pretrained(a__ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: SCREAMING_SNAKE_CASE : List[int] = pick_layers_to_copy(a__ , a__ ) if d_layers_to_copy is None: SCREAMING_SNAKE_CASE : List[int] = pick_layers_to_copy(a__ , a__ ) try: if hasattr( a__ , '''prophetnet''' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , a__ ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , a__ ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , a__ ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , a__ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , a__ ) copy_layers(teacher.decoder.block , student.decoder.block , a__ ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) SCREAMING_SNAKE_CASE : Tuple = { '''teacher_type''': teacher.config.model_type, '''copied_encoder_layers''': e_layers_to_copy, '''copied_decoder_layers''': d_layers_to_copy, } student.save_pretrained(a__ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
19
import datasets from .evaluate import evaluate a__ : Dict = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' a__ : List[str] = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' a__ : List[Any] = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric("cuad") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': { '''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.features.Sequence(datasets.Value('''string''' ) ), }, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://www.atticusprojectai.org/cuad'''] , reference_urls=['''https://www.atticusprojectai.org/cuad'''] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Any = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} SCREAMING_SNAKE_CASE : int = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] SCREAMING_SNAKE_CASE : Dict = evaluate(dataset=_lowerCamelCase , predictions=_lowerCamelCase ) return score
19
1
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) a__ : Tuple = logging.getLogger(__name__) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = git.Repo(search_parent_directories=a__ ) SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(a__ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), } with open(os.path.join(a__ , '''git_log.json''' ) , '''w''' ) as f: json.dump(a__ , a__ , indent=4 ) def UpperCAmelCase_( a__ ): """simple docstring""" if params.n_gpu <= 0: SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Optional[int] = -1 SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Optional[Any] = False return assert torch.cuda.is_available() logger.info('''Initializing GPUs''' ) if params.n_gpu > 1: assert params.local_rank != -1 SCREAMING_SNAKE_CASE : Tuple = int(os.environ['''WORLD_SIZE'''] ) SCREAMING_SNAKE_CASE : Optional[int] = int(os.environ['''N_GPU_NODE'''] ) SCREAMING_SNAKE_CASE : List[Any] = int(os.environ['''RANK'''] ) # number of nodes / node ID SCREAMING_SNAKE_CASE : List[Any] = params.world_size // params.n_gpu_per_node SCREAMING_SNAKE_CASE : Optional[int] = params.global_rank // params.n_gpu_per_node SCREAMING_SNAKE_CASE : Optional[Any] = True assert params.n_nodes == int(os.environ['''N_NODES'''] ) assert params.node_id == int(os.environ['''NODE_RANK'''] ) # local job (single GPU) else: assert params.local_rank == -1 SCREAMING_SNAKE_CASE : List[str] = 1 SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : Any = 1 SCREAMING_SNAKE_CASE : List[str] = 1 SCREAMING_SNAKE_CASE : Dict = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode SCREAMING_SNAKE_CASE : str = params.node_id == 0 and params.local_rank == 0 SCREAMING_SNAKE_CASE : Union[str, Any] = params.n_nodes > 1 # summary SCREAMING_SNAKE_CASE : Optional[Any] = F"""--- Global rank: {params.global_rank} - """ logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes ) logger.info(PREFIX + '''Node ID : %i''' % params.node_id ) logger.info(PREFIX + '''Local rank : %i''' % params.local_rank ) logger.info(PREFIX + '''World size : %i''' % params.world_size ) logger.info(PREFIX + '''GPUs per node : %i''' % params.n_gpu_per_node ) logger.info(PREFIX + '''Master : %s''' % str(params.is_master ) ) logger.info(PREFIX + '''Multi-node : %s''' % str(params.multi_node ) ) logger.info(PREFIX + '''Multi-GPU : %s''' % str(params.multi_gpu ) ) logger.info(PREFIX + '''Hostname : %s''' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('''Initializing PyTorch distributed''' ) torch.distributed.init_process_group( init_method='''env://''' , backend='''nccl''' , ) def UpperCAmelCase_( a__ ): """simple docstring""" np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
19
from sklearn.metrics import matthews_corrcoef import datasets a__ : Optional[Any] = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' a__ : str = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' a__ : Union[str, Any] = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ) ->List[str]: return { "matthews_correlation": float(matthews_corrcoef(_lowerCamelCase , _lowerCamelCase , sample_weight=_lowerCamelCase ) ), }
19
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a__ : Optional[Any] = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['''DeiTFeatureExtractor'''] a__ : Any = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ '''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 a__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
# Copyright 2021 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 argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=a__ ) SCREAMING_SNAKE_CASE : int = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=a__ ) env_command_parser(subparsers=a__ ) launch_command_parser(subparsers=a__ ) tpu_command_parser(subparsers=a__ ) test_command_parser(subparsers=a__ ) # Let's go SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() if not hasattr(a__ , '''func''' ): parser.print_help() exit(1 ) # Run args.func(a__ ) if __name__ == "__main__": main()
19
1
# Copyright 2021 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. import argparse import os from accelerate.test_utils import execute_subprocess_async def UpperCAmelCase_( a__=None ): """simple docstring""" if subparsers is not None: SCREAMING_SNAKE_CASE : Tuple = subparsers.add_parser('''test''' ) else: SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser('''Accelerate test command''' ) parser.add_argument( '''--config_file''' , default=a__ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=a__ ) return parser def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] ) if args.config_file is None: SCREAMING_SNAKE_CASE : int = script_name else: SCREAMING_SNAKE_CASE : str = F"""--config_file={args.config_file} {script_name}""" SCREAMING_SNAKE_CASE : Dict = ['''accelerate-launch'''] + test_args.split() SCREAMING_SNAKE_CASE : str = execute_subprocess_async(a__ , env=os.environ.copy() ) if result.returncode == 0: print('''Test is a success! You are ready for your distributed training!''' ) def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = test_command_parser() SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args() test_command(a__ ) if __name__ == "__main__": main()
19
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Optional[Any] = {'''vocab_file''': '''vocab.json'''} a__ : str = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } a__ : Tuple = {'''mgp-str''': 27} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _lowerCamelCase , _lowerCamelCase="[GO]" , _lowerCamelCase="[GO]" , _lowerCamelCase="[s]" , _lowerCamelCase="[GO]" , **_lowerCamelCase ) ->Dict: super().__init__( unk_token=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , pad_token=_lowerCamelCase , **_lowerCamelCase , ) with open(_lowerCamelCase , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE : List[Any] = json.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.vocab.items()} @property def __lowerCAmelCase ( self ) ->List[Any]: return len(self.vocab ) def __lowerCAmelCase ( self ) ->Union[str, Any]: return dict(self.vocab , **self.added_tokens_encoder ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Union[str, Any] = [] for s in text: char_tokens.extend(_lowerCamelCase ) return char_tokens def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: return self.vocab.get(_lowerCamelCase , self.vocab.get(self.unk_token ) ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: return self.decoder.get(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(_lowerCamelCase ) ) return SCREAMING_SNAKE_CASE : str = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=_lowerCamelCase , ensure_ascii=_lowerCamelCase ) + '''\n''' ) return (vocab_file,)
19
1
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = TextToVideoSDPipeline __SCREAMING_SNAKE_CASE : str = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. __SCREAMING_SNAKE_CASE : Union[str, Any] = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'return_dict', 'callback', 'callback_steps', ] ) def __lowerCAmelCase ( self ) ->int: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') , up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') , cross_attention_dim=32 , attention_head_dim=4 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , ) SCREAMING_SNAKE_CASE : List[str] = CLIPTextModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE : Optional[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->Union[str, Any]: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : int = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : str = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = TextToVideoSDPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = '''np''' SCREAMING_SNAKE_CASE : Dict = sd_pipe(**_lowerCamelCase ).frames SCREAMING_SNAKE_CASE : str = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) SCREAMING_SNAKE_CASE : List[str] = np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Optional[Any]: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=_lowerCamelCase , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __lowerCAmelCase ( self ) ->Dict: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_lowerCamelCase , expected_max_diff=1e-2 ) @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def __lowerCAmelCase ( self ) ->Optional[int]: pass @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def __lowerCAmelCase ( self ) ->Optional[Any]: pass @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' ) def __lowerCAmelCase ( self ) ->List[str]: pass def __lowerCAmelCase ( self ) ->List[Any]: return super().test_progress_bar() @slow @skip_mps class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy''' ) SCREAMING_SNAKE_CASE : Tuple = TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''' ) SCREAMING_SNAKE_CASE : Any = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) SCREAMING_SNAKE_CASE : List[Any] = pipe.to('''cuda''' ) SCREAMING_SNAKE_CASE : List[str] = '''Spiderman is surfing''' SCREAMING_SNAKE_CASE : str = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe(_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=25 , output_type='''pt''' ).frames SCREAMING_SNAKE_CASE : Optional[int] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy''' ) SCREAMING_SNAKE_CASE : Any = TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''' ) SCREAMING_SNAKE_CASE : List[str] = pipe.to('''cuda''' ) SCREAMING_SNAKE_CASE : int = '''Spiderman is surfing''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe(_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=2 , output_type='''pt''' ).frames SCREAMING_SNAKE_CASE : Any = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a__ : Optional[Any] = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['''DeiTFeatureExtractor'''] a__ : Any = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ '''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 a__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = StableDiffusionSAGPipeline __SCREAMING_SNAKE_CASE : Dict = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : int = False def __lowerCAmelCase ( self ) ->Optional[int]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = 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 , ) SCREAMING_SNAKE_CASE : int = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = 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 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->str: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''prompt''': '''.''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 1.0, '''sag_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) SCREAMING_SNAKE_CASE : Tuple = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = '''.''' SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : int = output.images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : int = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = '''.''' SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : List[str] = output.images SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : str = np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : int = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : Optional[int] = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = '''.''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , width=768 , height=512 , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : List[Any] = output.images assert image.shape == (1, 512, 768, 3)
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''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 a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
19
1
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class a_ : """simple docstring""" @staticmethod def __lowerCAmelCase ( *_lowerCamelCase , **_lowerCamelCase ) ->Optional[Any]: pass def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class a_ ( unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Union[str, Any] = DepthEstimationPipeline(model=_lowerCamelCase , image_processor=_lowerCamelCase ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Union[str, Any] = depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) self.assertEqual({'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )} , _lowerCamelCase ) import datasets SCREAMING_SNAKE_CASE : Any = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) SCREAMING_SNAKE_CASE : Optional[Any] = depth_estimator( [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] ) self.assertEqual( [ {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, ] , _lowerCamelCase , ) @require_tf @unittest.skip('''Depth estimation is not implemented in TF''' ) def __lowerCAmelCase ( self ) ->Any: pass @slow @require_torch def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Union[str, Any] = '''Intel/dpt-large''' SCREAMING_SNAKE_CASE : List[str] = pipeline('''depth-estimation''' , model=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) SCREAMING_SNAKE_CASE : List[str] = hashimage(outputs['''depth'''] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item() ) , 2_9.3_0_4 ) self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item() ) , 2.6_6_2 ) @require_torch def __lowerCAmelCase ( self ) ->str: # This is highly irregular to have no small tests. self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''' )
19
import math from collections.abc import Iterator from itertools import takewhile def UpperCAmelCase_( a__ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = 2 while True: if is_prime(a__ ): yield num num += 1 def UpperCAmelCase_( a__ = 2_000_000 ): """simple docstring""" return sum(takewhile(lambda a__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"{solution() = }")
19
1
import argparse import struct import unittest class a_ : """simple docstring""" def __init__( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Tuple = data # Initialize hash values SCREAMING_SNAKE_CASE : Tuple = [ 0x6a_09e_667, 0xbb_67a_e85, 0x3c_6ef_372, 0xa5_4ff_53a, 0x51_0e5_27f, 0x9b_056_88c, 0x1f_83d_9ab, 0x5b_e0c_d19, ] # Initialize round constants SCREAMING_SNAKE_CASE : Any = [ 0x42_8a2_f98, 0x71_374_491, 0xb5_c0f_bcf, 0xe9_b5d_ba5, 0x39_56c_25b, 0x59_f11_1f1, 0x92_3f8_2a4, 0xab_1c5_ed5, 0xd8_07a_a98, 0x12_835_b01, 0x24_318_5be, 0x55_0c7_dc3, 0x72_be5_d74, 0x80_deb_1fe, 0x9b_dc0_6a7, 0xc1_9bf_174, 0xe4_9b6_9c1, 0xef_be4_786, 0x0f_c19_dc6, 0x24_0ca_1cc, 0x2d_e92_c6f, 0x4a_748_4aa, 0x5c_b0a_9dc, 0x76_f98_8da, 0x98_3e5_152, 0xa8_31c_66d, 0xb0_032_7c8, 0xbf_597_fc7, 0xc6_e00_bf3, 0xd5_a79_147, 0x06_ca6_351, 0x14_292_967, 0x27_b70_a85, 0x2e_1b2_138, 0x4d_2c6_dfc, 0x53_380_d13, 0x65_0a7_354, 0x76_6a0_abb, 0x81_c2c_92e, 0x92_722_c85, 0xa2_bfe_8a1, 0xa8_1a6_64b, 0xc2_4b8_b70, 0xc7_6c5_1a3, 0xd1_92e_819, 0xd6_990_624, 0xf4_0e3_585, 0x10_6aa_070, 0x19_a4c_116, 0x1e_376_c08, 0x27_487_74c, 0x34_b0b_cb5, 0x39_1c0_cb3, 0x4e_d8a_a4a, 0x5b_9cc_a4f, 0x68_2e6_ff3, 0x74_8f8_2ee, 0x78_a56_36f, 0x84_c87_814, 0x8c_c70_208, 0x90_bef_ffa, 0xa4_506_ceb, 0xbe_f9a_3f7, 0xc6_717_8f2, ] SCREAMING_SNAKE_CASE : Union[str, Any] = self.preprocessing(self.data ) self.final_hash() @staticmethod def __lowerCAmelCase ( _lowerCamelCase ) ->bytes: SCREAMING_SNAKE_CASE : Optional[int] = B'''\x80''' + (B'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) SCREAMING_SNAKE_CASE : str = struct.pack('''>Q''' , (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def __lowerCAmelCase ( self ) ->None: # Convert into blocks of 64 bytes SCREAMING_SNAKE_CASE : Optional[int] = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers SCREAMING_SNAKE_CASE : int = list(struct.unpack('''>16L''' , _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array SCREAMING_SNAKE_CASE : List[Any] = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) SCREAMING_SNAKE_CASE : Optional[int] = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) SCREAMING_SNAKE_CASE : Dict = ( words[index - 16] + sa + words[index - 7] + sa ) % 0x100_000_000 # Compression SCREAMING_SNAKE_CASE : List[str] = self.ror(_lowerCamelCase , 6 ) ^ self.ror(_lowerCamelCase , 11 ) ^ self.ror(_lowerCamelCase , 25 ) SCREAMING_SNAKE_CASE : int = (e & f) ^ ((~e & 0xff_fff_fff) & g) SCREAMING_SNAKE_CASE : Union[str, Any] = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0x100_000_000 SCREAMING_SNAKE_CASE : Any = self.ror(_lowerCamelCase , 2 ) ^ self.ror(_lowerCamelCase , 13 ) ^ self.ror(_lowerCamelCase , 22 ) SCREAMING_SNAKE_CASE : Optional[int] = (a & b) ^ (a & c) ^ (b & c) SCREAMING_SNAKE_CASE : Union[str, Any] = (sa + maj) % 0x100_000_000 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = ( g, f, e, ((d + tempa) % 0x100_000_000), c, b, a, ((tempa + tempa) % 0x100_000_000), ) SCREAMING_SNAKE_CASE : str = [a, b, c, d, e, f, g, h] # Modify final values SCREAMING_SNAKE_CASE : Dict = [ ((element + mutated_hash_values[index]) % 0x100_000_000) for index, element in enumerate(self.hashes ) ] SCREAMING_SNAKE_CASE : Optional[Any] = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->int: return 0xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->None: import hashlib SCREAMING_SNAKE_CASE : Any = bytes('''Test String''' , '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash , hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def UpperCAmelCase_( ): """simple docstring""" import doctest doctest.testmod() SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) SCREAMING_SNAKE_CASE : Any = parser.parse_args() SCREAMING_SNAKE_CASE : str = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: SCREAMING_SNAKE_CASE : Optional[Any] = f.read() else: SCREAMING_SNAKE_CASE : Tuple = bytes(a__ , '''utf-8''' ) print(SHAaaa(a__ ).hash ) if __name__ == "__main__": main()
19
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a_ ( a__ ): """simple docstring""" def __init__( self , *_lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase ) ->int: super().__init__(*_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = eval_examples SCREAMING_SNAKE_CASE : Optional[int] = post_process_function def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase=None , _lowerCamelCase = None , _lowerCamelCase = "eval" , **_lowerCamelCase , ) ->Dict[str, float]: SCREAMING_SNAKE_CASE : Any = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) SCREAMING_SNAKE_CASE : Dict = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) SCREAMING_SNAKE_CASE : Any = gen_kwargs SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : str = self.get_eval_dataloader(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Optional[Any] = self.compute_metrics SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : Optional[Any] = time.time() SCREAMING_SNAKE_CASE : List[str] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Tuple = eval_loop( _lowerCamelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Dict = compute_metrics SCREAMING_SNAKE_CASE : Tuple = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : Optional[int] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_lowerCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : int = self.callback_handler.on_evaluate(self.args , self.state , self.control , _lowerCamelCase ) return metrics def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase = "test" , **_lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : str = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(_lowerCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[str] = time.time() SCREAMING_SNAKE_CASE : Optional[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Any = eval_loop( _lowerCamelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Optional[int] = compute_metrics SCREAMING_SNAKE_CASE : List[Any] = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , '''predict''' ) SCREAMING_SNAKE_CASE : Dict = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : List[Any] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_lowerCamelCase )
19
1
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) SCREAMING_SNAKE_CASE : int = DatasetInfosDict.from_directory(a__ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = str(a__ ) dataset_info.write_to_directory(a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfo.from_directory(a__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(a__ , '''dataset_info.json''' ) ) def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1_337 , post_processing_size=442 , dataset_size=1_234 , size_in_bytes=1_337 + 442 + 1_234 , ) SCREAMING_SNAKE_CASE : int = dataset_info._to_yaml_dict() assert sorted(a__ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) SCREAMING_SNAKE_CASE : Optional[Any] = yaml.safe_dump(a__ ) SCREAMING_SNAKE_CASE : List[Any] = yaml.safe_load(a__ ) assert dataset_info_yaml_dict == reloaded def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = DatasetInfo() SCREAMING_SNAKE_CASE : List[str] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1_337 ), } ), ] , ) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = str(a__ ) dataset_infos_dict.write_to_directory(a__ ) SCREAMING_SNAKE_CASE : str = DatasetInfosDict.from_directory(a__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): SCREAMING_SNAKE_CASE : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml SCREAMING_SNAKE_CASE : str = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(a__ , '''README.md''' ) )
19
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = DDIMPipeline __SCREAMING_SNAKE_CASE : Tuple = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __SCREAMING_SNAKE_CASE : Tuple = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } __SCREAMING_SNAKE_CASE : str = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = False def __lowerCAmelCase ( self ) ->int: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler() SCREAMING_SNAKE_CASE : Dict = {'''unet''': unet, '''scheduler''': scheduler} return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->int: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : int = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Optional[int] = '''cpu''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[Any] = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) SCREAMING_SNAKE_CASE : int = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) SCREAMING_SNAKE_CASE : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def __lowerCAmelCase ( self ) ->Optional[int]: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_save_load_local(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Union[str, Any]: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[int] = '''google/ddpm-cifar10-32''' SCREAMING_SNAKE_CASE : Dict = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler() SCREAMING_SNAKE_CASE : Optional[int] = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddim.to(_lowerCamelCase ) ddim.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = ddim(generator=_lowerCamelCase , eta=0.0 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[Any] = '''google/ddpm-ema-bedroom-256''' SCREAMING_SNAKE_CASE : List[str] = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = DDIMScheduler.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddpm.to(_lowerCamelCase ) ddpm.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = ddpm(generator=_lowerCamelCase , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
19
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging a__ : int = logging.get_logger(__name__) class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = ['pixel_values'] def __init__( self , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = True , _lowerCamelCase = 1 / 255 , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = None , **_lowerCamelCase , ) ->None: super().__init__(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE : Any = get_size_dict(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = size SCREAMING_SNAKE_CASE : List[str] = resample SCREAMING_SNAKE_CASE : Dict = do_center_crop SCREAMING_SNAKE_CASE : List[str] = crop_size SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor SCREAMING_SNAKE_CASE : Any = do_normalize SCREAMING_SNAKE_CASE : List[str] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = PILImageResampling.BICUBIC , _lowerCamelCase = None , **_lowerCamelCase , ) ->np.ndarray: SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) SCREAMING_SNAKE_CASE : List[str] = get_resize_output_image_size(_lowerCamelCase , size=size['''shortest_edge'''] , default_to_square=_lowerCamelCase ) return resize(_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , **_lowerCamelCase , ) ->np.ndarray: SCREAMING_SNAKE_CASE : List[str] = get_size_dict(_lowerCamelCase ) return center_crop(_lowerCamelCase , size=(size['''height'''], size['''width''']) , data_format=_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , **_lowerCamelCase ) ->np.ndarray: return rescale(_lowerCamelCase , scale=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , **_lowerCamelCase , ) ->np.ndarray: return normalize(_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = ChannelDimension.FIRST , **_lowerCamelCase , ) ->str: SCREAMING_SNAKE_CASE : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : List[str] = size if size is not None else self.size SCREAMING_SNAKE_CASE : int = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : int = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : Union[str, Any] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : str = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Dict = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : int = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Any = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : str = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE : List[Any] = [self.center_crop(image=_lowerCamelCase , size=_lowerCamelCase ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Optional[Any] = [self.rescale(image=_lowerCamelCase , scale=_lowerCamelCase ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase ) for image in images] SCREAMING_SNAKE_CASE : Tuple = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] SCREAMING_SNAKE_CASE : List[Any] = {'''pixel_values''': images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase )
19
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = XLMProphetNetTokenizer __SCREAMING_SNAKE_CASE : List[str] = False __SCREAMING_SNAKE_CASE : Dict = True def __lowerCAmelCase ( self ) ->Dict: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE : Optional[Any] = XLMProphetNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : List[str] = '''[PAD]''' SCREAMING_SNAKE_CASE : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''[PAD]''' ) self.assertEqual(vocab_keys[1] , '''[CLS]''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(_lowerCamelCase ) , 1012 ) def __lowerCAmelCase ( self ) ->List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = XLMProphetNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''[UNK]''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''[UNK]''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self ) ->List[str]: return XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased''' ) @slow def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Union[str, Any] = '''Hello World!''' SCREAMING_SNAKE_CASE : int = [3_5389, 6672, 49, 2] self.assertListEqual(_lowerCamelCase , self.big_tokenizer.encode(_lowerCamelCase ) ) @slow def __lowerCAmelCase ( self ) ->int: # fmt: off SCREAMING_SNAKE_CASE : str = {'''input_ids''': [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''microsoft/xprophetnet-large-wiki100-cased''' , revision='''1acad1643ddd54a44df6a1b797ada8373685d90e''' , )
19
1
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Optional[Any] = {'''vocab_file''': '''vocab.json'''} a__ : str = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } a__ : Tuple = {'''mgp-str''': 27} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _lowerCamelCase , _lowerCamelCase="[GO]" , _lowerCamelCase="[GO]" , _lowerCamelCase="[s]" , _lowerCamelCase="[GO]" , **_lowerCamelCase ) ->Dict: super().__init__( unk_token=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , pad_token=_lowerCamelCase , **_lowerCamelCase , ) with open(_lowerCamelCase , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE : List[Any] = json.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.vocab.items()} @property def __lowerCAmelCase ( self ) ->List[Any]: return len(self.vocab ) def __lowerCAmelCase ( self ) ->Union[str, Any]: return dict(self.vocab , **self.added_tokens_encoder ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Union[str, Any] = [] for s in text: char_tokens.extend(_lowerCamelCase ) return char_tokens def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: return self.vocab.get(_lowerCamelCase , self.vocab.get(self.unk_token ) ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: return self.decoder.get(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(_lowerCamelCase ) ) return SCREAMING_SNAKE_CASE : str = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=_lowerCamelCase , ensure_ascii=_lowerCamelCase ) + '''\n''' ) return (vocab_file,)
19
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = StableDiffusionSAGPipeline __SCREAMING_SNAKE_CASE : Dict = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : int = False def __lowerCAmelCase ( self ) ->Optional[int]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = 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 , ) SCREAMING_SNAKE_CASE : int = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = 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 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->str: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''prompt''': '''.''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 1.0, '''sag_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) SCREAMING_SNAKE_CASE : Tuple = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = '''.''' SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : int = output.images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : int = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = '''.''' SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : List[str] = output.images SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : str = np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : int = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : Optional[int] = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = '''.''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , width=768 , height=512 , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : List[Any] = output.images assert image.shape == (1, 512, 768, 3)
19
1
from collections import deque def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = len(a__ ) SCREAMING_SNAKE_CASE : Tuple = deque() SCREAMING_SNAKE_CASE : Union[str, Any] = [False for _ in range(a__ )] SCREAMING_SNAKE_CASE : Optional[Any] = [-1 for _ in range(a__ )] SCREAMING_SNAKE_CASE : Dict = index_of[:] def strong_connect(a__ , a__ , a__ ): SCREAMING_SNAKE_CASE : str = index # the number when this node is seen SCREAMING_SNAKE_CASE : List[str] = index # lowest rank node reachable from here index += 1 stack.append(a__ ) SCREAMING_SNAKE_CASE : Any = True for w in g[v]: if index_of[w] == -1: SCREAMING_SNAKE_CASE : int = strong_connect(a__ , a__ , a__ ) SCREAMING_SNAKE_CASE : int = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: SCREAMING_SNAKE_CASE : Any = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : int = stack.pop() SCREAMING_SNAKE_CASE : Dict = False component.append(a__ ) while w != v: SCREAMING_SNAKE_CASE : List[Any] = stack.pop() SCREAMING_SNAKE_CASE : Any = False component.append(a__ ) components.append(a__ ) return index SCREAMING_SNAKE_CASE : int = [] for v in range(a__ ): if index_of[v] == -1: strong_connect(a__ , 0 , a__ ) return components def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [[] for _ in range(a__ )] for u, v in edges: g[u].append(a__ ) return g if __name__ == "__main__": # Test a__ : str = 7 a__ : List[str] = [0, 0, 1, 2, 3, 3, 4, 4, 6] a__ : List[Any] = [1, 3, 2, 0, 1, 4, 5, 6, 5] a__ : int = [(u, v) for u, v in zip(source, target)] a__ : Optional[Any] = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
19
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Tuple = { '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } a__ : Optional[Any] = {'''mobilebert-uncased''': 512} a__ : List[Any] = {} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : int = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_INIT_CONFIGURATION __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Optional[int] = MobileBertTokenizer def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase="[UNK]" , _lowerCamelCase="[SEP]" , _lowerCamelCase="[PAD]" , _lowerCamelCase="[CLS]" , _lowerCamelCase="[MASK]" , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ) ->Optional[int]: super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE : Optional[int] = strip_accents SCREAMING_SNAKE_CASE : Union[str, Any] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = do_lower_case def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->Any: SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: SCREAMING_SNAKE_CASE : Any = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
19
1
from collections.abc import Callable def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : float = a SCREAMING_SNAKE_CASE : float = b if function(a__ ) == 0: # one of the a or b is a root for the function return a elif function(a__ ) == 0: return b elif ( function(a__ ) * function(a__ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError('''could not find root in given interval.''' ) else: SCREAMING_SNAKE_CASE : float = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(a__ ) == 0: return mid elif function(a__ ) * function(a__ ) < 0: SCREAMING_SNAKE_CASE : List[str] = mid else: SCREAMING_SNAKE_CASE : Optional[int] = mid SCREAMING_SNAKE_CASE : Union[str, Any] = start + (end - start) / 2.0 return mid def UpperCAmelCase_( a__ ): """simple docstring""" return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1_000)) import doctest doctest.testmod()
19
import math a__ : List[str] = 10 a__ : Optional[int] = 7 a__ : int = BALLS_PER_COLOUR * NUM_COLOURS def UpperCAmelCase_( a__ = 20 ): """simple docstring""" SCREAMING_SNAKE_CASE : str = math.comb(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) SCREAMING_SNAKE_CASE : Any = NUM_COLOURS * (1 - missing_colour / total) return F"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
19
1
import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = 'MCTCTFeatureExtractor' __SCREAMING_SNAKE_CASE : Tuple = 'AutoTokenizer' def __init__( self , _lowerCamelCase , _lowerCamelCase ) ->List[str]: super().__init__(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = self.feature_extractor SCREAMING_SNAKE_CASE : Optional[int] = False def __call__( self , *_lowerCamelCase , **_lowerCamelCase ) ->Optional[int]: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_lowerCamelCase , **_lowerCamelCase ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs.pop('''raw_speech''' ) else: SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop('''audio''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = kwargs.pop('''sampling_rate''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = kwargs.pop('''text''' , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: SCREAMING_SNAKE_CASE : Optional[int] = args[0] SCREAMING_SNAKE_CASE : Optional[Any] = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: SCREAMING_SNAKE_CASE : int = self.feature_extractor(_lowerCamelCase , *_lowerCamelCase , sampling_rate=_lowerCamelCase , **_lowerCamelCase ) if text is not None: SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer(_lowerCamelCase , **_lowerCamelCase ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE : List[str] = encodings['''input_ids'''] return inputs def __lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ) ->Dict: return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ) ->List[Any]: # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop('''input_features''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = kwargs.pop('''labels''' , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: SCREAMING_SNAKE_CASE : Optional[Any] = args[0] SCREAMING_SNAKE_CASE : List[Any] = args[1:] if input_features is not None: SCREAMING_SNAKE_CASE : Dict = self.feature_extractor.pad(_lowerCamelCase , *_lowerCamelCase , **_lowerCamelCase ) if labels is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer.pad(_lowerCamelCase , **_lowerCamelCase ) if labels is None: return input_features elif input_features is None: return labels else: SCREAMING_SNAKE_CASE : Any = labels['''input_ids'''] return input_features def __lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ) ->Optional[int]: return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @contextmanager def __lowerCAmelCase ( self ) ->Any: warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = True SCREAMING_SNAKE_CASE : List[str] = self.tokenizer yield SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extractor SCREAMING_SNAKE_CASE : Tuple = False
19
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a__ : List[str] = logging.get_logger(__name__) # General docstring a__ : Tuple = '''MobileNetV1Config''' # Base docstring a__ : Optional[Any] = '''google/mobilenet_v1_1.0_224''' a__ : Tuple = [1, 1_024, 7, 7] # Image classification docstring a__ : Optional[int] = '''google/mobilenet_v1_1.0_224''' a__ : int = '''tabby, tabby cat''' a__ : List[Any] = [ '''google/mobilenet_v1_1.0_224''', '''google/mobilenet_v1_0.75_192''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def UpperCAmelCase_( a__ , a__ , a__=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = {} if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[str] = model.mobilenet_va else: SCREAMING_SNAKE_CASE : Union[str, Any] = model SCREAMING_SNAKE_CASE : Optional[int] = '''MobilenetV1/Conv2d_0/''' SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.convolution.weight SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = backbone.conv_stem.normalization.weight SCREAMING_SNAKE_CASE : Union[str, Any] = backbone.conv_stem.normalization.running_mean SCREAMING_SNAKE_CASE : Any = backbone.conv_stem.normalization.running_var for i in range(13 ): SCREAMING_SNAKE_CASE : Dict = i + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = i * 2 SCREAMING_SNAKE_CASE : Any = backbone.layer[pt_index] SCREAMING_SNAKE_CASE : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" SCREAMING_SNAKE_CASE : Any = pointer.convolution.weight SCREAMING_SNAKE_CASE : Tuple = pointer.normalization.bias SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.running_var SCREAMING_SNAKE_CASE : List[Any] = backbone.layer[pt_index + 1] SCREAMING_SNAKE_CASE : Any = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" SCREAMING_SNAKE_CASE : Dict = pointer.convolution.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : int = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : str = pointer.normalization.running_var if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[Any] = '''MobilenetV1/Logits/Conv2d_1c_1x1/''' SCREAMING_SNAKE_CASE : List[str] = model.classifier.weight SCREAMING_SNAKE_CASE : List[str] = model.classifier.bias return tf_to_pt_map def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ''' '''https://www.tensorflow.org/install/ for installation instructions.''' ) raise # Load weights from TF model SCREAMING_SNAKE_CASE : Optional[Any] = tf.train.list_variables(a__ ) SCREAMING_SNAKE_CASE : List[Any] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) SCREAMING_SNAKE_CASE : Tuple = tf.train.load_variable(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = array # Build TF to PyTorch weights loading map SCREAMING_SNAKE_CASE : int = _build_tf_to_pytorch_map(a__ , a__ , a__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue SCREAMING_SNAKE_CASE : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('''Transposing depthwise''' ) SCREAMING_SNAKE_CASE : Tuple = np.transpose(a__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('''Transposing''' ) if len(pointer.shape ) == 2: # copying into linear layer SCREAMING_SNAKE_CASE : Union[str, Any] = array.squeeze().transpose() else: SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(a__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(a__ ) tf_weights.pop(a__ , a__ ) tf_weights.pop(name + '''/RMSProp''' , a__ ) tf_weights.pop(name + '''/RMSProp_1''' , a__ ) tf_weights.pop(name + '''/ExponentialMovingAverage''' , a__ ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = features.shape[-2:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = conv_layer.stride SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = conv_layer.kernel_size if in_height % stride_height == 0: SCREAMING_SNAKE_CASE : List[str] = max(kernel_height - stride_height , 0 ) else: SCREAMING_SNAKE_CASE : str = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: SCREAMING_SNAKE_CASE : int = max(kernel_width - stride_width , 0 ) else: SCREAMING_SNAKE_CASE : Tuple = max(kernel_width - (in_width % stride_width) , 0 ) SCREAMING_SNAKE_CASE : List[str] = pad_along_width // 2 SCREAMING_SNAKE_CASE : Any = pad_along_width - pad_left SCREAMING_SNAKE_CASE : str = pad_along_height // 2 SCREAMING_SNAKE_CASE : Optional[int] = pad_along_height - pad_top SCREAMING_SNAKE_CASE : List[Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(a__ , a__ , '''constant''' , 0.0 ) class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 1 , _lowerCamelCase = 1 , _lowerCamelCase = False , _lowerCamelCase = True , _lowerCamelCase = True , ) ->None: super().__init__() SCREAMING_SNAKE_CASE : Any = config if in_channels % groups != 0: raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) SCREAMING_SNAKE_CASE : Any = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) SCREAMING_SNAKE_CASE : List[str] = nn.Convad( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=_lowerCamelCase , stride=_lowerCamelCase , padding=_lowerCamelCase , groups=_lowerCamelCase , bias=_lowerCamelCase , padding_mode='''zeros''' , ) if use_normalization: SCREAMING_SNAKE_CASE : List[Any] = nn.BatchNormad( num_features=_lowerCamelCase , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=_lowerCamelCase , track_running_stats=_lowerCamelCase , ) else: SCREAMING_SNAKE_CASE : Dict = None if use_activation: if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Any = ACTaFN[use_activation] elif isinstance(config.hidden_act , _lowerCamelCase ): SCREAMING_SNAKE_CASE : List[str] = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : List[Any] = config.hidden_act else: SCREAMING_SNAKE_CASE : Optional[Any] = None def __lowerCAmelCase ( self , _lowerCamelCase ) ->torch.Tensor: if self.config.tf_padding: SCREAMING_SNAKE_CASE : List[Any] = apply_tf_padding(_lowerCamelCase , self.convolution ) SCREAMING_SNAKE_CASE : Dict = self.convolution(_lowerCamelCase ) if self.normalization is not None: SCREAMING_SNAKE_CASE : int = self.normalization(_lowerCamelCase ) if self.activation is not None: SCREAMING_SNAKE_CASE : List[Any] = self.activation(_lowerCamelCase ) return features class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = MobileNetVaConfig __SCREAMING_SNAKE_CASE : List[Any] = load_tf_weights_in_mobilenet_va __SCREAMING_SNAKE_CASE : int = 'mobilenet_v1' __SCREAMING_SNAKE_CASE : int = 'pixel_values' __SCREAMING_SNAKE_CASE : List[str] = False def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: if isinstance(_lowerCamelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_lowerCamelCase , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) a__ : str = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Union[str, Any] = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase = True ) ->Dict: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = config SCREAMING_SNAKE_CASE : Dict = 32 SCREAMING_SNAKE_CASE : Optional[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) SCREAMING_SNAKE_CASE : str = MobileNetVaConvLayer( _lowerCamelCase , in_channels=config.num_channels , out_channels=_lowerCamelCase , kernel_size=3 , stride=2 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] SCREAMING_SNAKE_CASE : Any = nn.ModuleList() for i in range(13 ): SCREAMING_SNAKE_CASE : int = out_channels if strides[i] == 2 or i == 0: depth *= 2 SCREAMING_SNAKE_CASE : Tuple = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=3 , stride=strides[i] , groups=_lowerCamelCase , ) ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=1 , ) ) SCREAMING_SNAKE_CASE : int = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: raise NotImplementedError @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.conv_stem(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): SCREAMING_SNAKE_CASE : Optional[int] = layer_module(_lowerCamelCase ) if output_hidden_states: SCREAMING_SNAKE_CASE : List[str] = all_hidden_states + (hidden_states,) SCREAMING_SNAKE_CASE : List[str] = hidden_states if self.pooler is not None: SCREAMING_SNAKE_CASE : Tuple = torch.flatten(self.pooler(_lowerCamelCase ) , start_dim=1 ) else: SCREAMING_SNAKE_CASE : List[Any] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_lowerCamelCase , pooler_output=_lowerCamelCase , hidden_states=_lowerCamelCase , ) @add_start_docstrings( '\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->None: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = config.num_labels SCREAMING_SNAKE_CASE : str = MobileNetVaModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head SCREAMING_SNAKE_CASE : Optional[int] = nn.Dropout(config.classifier_dropout_prob , inplace=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = nn.Linear(_lowerCamelCase , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, ImageClassifierOutputWithNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va(_lowerCamelCase , output_hidden_states=_lowerCamelCase , return_dict=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE : Tuple = self.classifier(self.dropout(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : int = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : Any = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : Optional[int] = '''single_label_classification''' else: SCREAMING_SNAKE_CASE : Dict = '''multi_label_classification''' if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Any = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : Dict = loss_fct(_lowerCamelCase , _lowerCamelCase ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : List[Any] = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : List[Any] = loss_fct(_lowerCamelCase , _lowerCamelCase ) if not return_dict: SCREAMING_SNAKE_CASE : Optional[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_lowerCamelCase , logits=_lowerCamelCase , hidden_states=outputs.hidden_states , )
19
1
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask a__ : List[str] = logging.getLogger(__name__) class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = 'token-classification' def __init__( self , _lowerCamelCase ) ->str: if type(_lowerCamelCase ) == dict: SCREAMING_SNAKE_CASE : Union[str, Any] = Namespace(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = import_module('''tasks''' ) try: SCREAMING_SNAKE_CASE : List[str] = getattr(_lowerCamelCase , hparams.task_type ) SCREAMING_SNAKE_CASE : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F"""Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) SCREAMING_SNAKE_CASE : str = self.token_classification_task.get_labels(hparams.labels ) SCREAMING_SNAKE_CASE : Optional[Any] = CrossEntropyLoss().ignore_index super().__init__(_lowerCamelCase , len(self.labels ) , self.mode ) def __lowerCAmelCase ( self , **_lowerCamelCase ) ->List[Any]: return self.model(**_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]} if self.config.model_type != "distilbert": SCREAMING_SNAKE_CASE : Union[str, Any] = ( batch[2] if self.config.model_type in ['''bert''', '''xlnet'''] else None ) # XLM and RoBERTa don"t use token_type_ids SCREAMING_SNAKE_CASE : int = self(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[str] = self.hparams for mode in ["train", "dev", "test"]: SCREAMING_SNAKE_CASE : Any = self._feature_file(_lowerCamelCase ) if os.path.exists(_lowerCamelCase ) and not args.overwrite_cache: logger.info('''Loading features from cached file %s''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(_lowerCamelCase ) else: logger.info('''Creating features from dataset file at %s''' , args.data_dir ) SCREAMING_SNAKE_CASE : Dict = self.token_classification_task.read_examples_from_file(args.data_dir , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = self.token_classification_task.convert_examples_to_features( _lowerCamelCase , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ['''xlnet'''] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ['''xlnet'''] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=_lowerCamelCase , pad_on_left=bool(self.config.model_type in ['''xlnet'''] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info('''Saving features into cached file %s''' , _lowerCamelCase ) torch.save(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = False ) ->DataLoader: SCREAMING_SNAKE_CASE : Optional[Any] = self._feature_file(_lowerCamelCase ) logger.info('''Loading features from cached file %s''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = torch.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: SCREAMING_SNAKE_CASE : Dict = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) , batch_size=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Optional[int]: """Compute validation""" "" SCREAMING_SNAKE_CASE : List[Any] = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]} if self.config.model_type != "distilbert": SCREAMING_SNAKE_CASE : Optional[Any] = ( batch[2] if self.config.model_type in ['''bert''', '''xlnet'''] else None ) # XLM and RoBERTa don"t use token_type_ids SCREAMING_SNAKE_CASE : Optional[int] = self(**_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = outputs[:2] SCREAMING_SNAKE_CASE : Optional[Any] = logits.detach().cpu().numpy() SCREAMING_SNAKE_CASE : Optional[int] = inputs['''labels'''].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: SCREAMING_SNAKE_CASE : Optional[int] = torch.stack([x['''val_loss'''] for x in outputs] ).mean() SCREAMING_SNAKE_CASE : Union[str, Any] = np.concatenate([x['''pred'''] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE : str = np.argmax(_lowerCamelCase , axis=2 ) SCREAMING_SNAKE_CASE : Tuple = np.concatenate([x['''target'''] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE : Any = dict(enumerate(self.labels ) ) SCREAMING_SNAKE_CASE : int = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE : Optional[Any] = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) SCREAMING_SNAKE_CASE : List[Any] = { '''val_loss''': val_loss_mean, '''accuracy_score''': accuracy_score(_lowerCamelCase , _lowerCamelCase ), '''precision''': precision_score(_lowerCamelCase , _lowerCamelCase ), '''recall''': recall_score(_lowerCamelCase , _lowerCamelCase ), '''f1''': fa_score(_lowerCamelCase , _lowerCamelCase ), } SCREAMING_SNAKE_CASE : Optional[int] = dict(results.items() ) SCREAMING_SNAKE_CASE : Optional[int] = results return ret, preds_list, out_label_list def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: # when stable SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self._eval_end(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = ret['''log'''] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: # updating to test_epoch_end instead of deprecated test_end SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self._eval_end(_lowerCamelCase ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 SCREAMING_SNAKE_CASE : Any = ret['''log'''] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def __lowerCAmelCase ( _lowerCamelCase , _lowerCamelCase ) ->Dict: # Add NER specific options BaseTransformer.add_model_specific_args(_lowerCamelCase , _lowerCamelCase ) parser.add_argument( '''--task_type''' , default='''NER''' , type=_lowerCamelCase , help='''Task type to fine tune in training (e.g. NER, POS, etc)''' ) parser.add_argument( '''--max_seq_length''' , default=128 , type=_lowerCamelCase , help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) , ) parser.add_argument( '''--labels''' , default='''''' , type=_lowerCamelCase , help='''Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.''' , ) parser.add_argument( '''--gpus''' , default=0 , type=_lowerCamelCase , help='''The number of GPUs allocated for this, it is by default 0 meaning none''' , ) parser.add_argument( '''--overwrite_cache''' , action='''store_true''' , help='''Overwrite the cached training and evaluation sets''' ) return parser if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) a__ : Optional[int] = NERTransformer.add_model_specific_args(parser, os.getcwd()) a__ : int = parser.parse_args() a__ : Any = NERTransformer(args) a__ : Any = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 a__ : Union[str, Any] = sorted(glob.glob(os.path.join(args.output_dir, '''checkpoint-epoch=*.ckpt'''), recursive=True)) a__ : Optional[Any] = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
19
import math def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(a__ ) def UpperCAmelCase_( a__ = 1 / 12_345 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : int = 3 while True: SCREAMING_SNAKE_CASE : Union[str, Any] = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(a__ ): SCREAMING_SNAKE_CASE : List[str] = int(a__ ) total_partitions += 1 if check_partition_perfect(a__ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(a__ ) integer += 1 if __name__ == "__main__": print(F"{solution() = }")
19
1
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = 'Speech2TextFeatureExtractor' __SCREAMING_SNAKE_CASE : List[str] = 'Speech2TextTokenizer' def __init__( self , _lowerCamelCase , _lowerCamelCase ) ->str: super().__init__(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = self.feature_extractor SCREAMING_SNAKE_CASE : List[Any] = False def __call__( self , *_lowerCamelCase , **_lowerCamelCase ) ->Optional[int]: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*_lowerCamelCase , **_lowerCamelCase ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) SCREAMING_SNAKE_CASE : List[Any] = kwargs.pop('''raw_speech''' ) else: SCREAMING_SNAKE_CASE : str = kwargs.pop('''audio''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : int = kwargs.pop('''sampling_rate''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = kwargs.pop('''text''' , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: SCREAMING_SNAKE_CASE : Dict = args[0] SCREAMING_SNAKE_CASE : Dict = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: SCREAMING_SNAKE_CASE : int = self.feature_extractor(_lowerCamelCase , *_lowerCamelCase , sampling_rate=_lowerCamelCase , **_lowerCamelCase ) if text is not None: SCREAMING_SNAKE_CASE : Any = self.tokenizer(_lowerCamelCase , **_lowerCamelCase ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE : List[Any] = encodings['''input_ids'''] return inputs def __lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ) ->List[str]: return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ) ->Dict: return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @contextmanager def __lowerCAmelCase ( self ) ->Optional[Any]: warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) SCREAMING_SNAKE_CASE : Any = True SCREAMING_SNAKE_CASE : str = self.tokenizer yield SCREAMING_SNAKE_CASE : int = self.feature_extractor SCREAMING_SNAKE_CASE : Union[str, Any] = False
19
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar a__ : Any = TypeVar('''T''') def UpperCAmelCase_( a__ ): """simple docstring""" return (position - 1) // 2 def UpperCAmelCase_( a__ ): """simple docstring""" return (2 * position) + 1 def UpperCAmelCase_( a__ ): """simple docstring""" return (2 * position) + 2 class a_ ( Generic[T] ): """simple docstring""" def __init__( self ) ->None: SCREAMING_SNAKE_CASE : list[tuple[T, int]] = [] SCREAMING_SNAKE_CASE : dict[T, int] = {} SCREAMING_SNAKE_CASE : int = 0 def __len__( self ) ->int: return self.elements def __repr__( self ) ->str: return str(self.heap ) def __lowerCAmelCase ( self ) ->bool: # Check if the priority queue is empty return self.elements == 0 def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) SCREAMING_SNAKE_CASE : Tuple = self.elements self.elements += 1 self._bubble_up(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.heap[0] self._bubble_down(_lowerCamelCase ) return elem def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Update the weight of the given key SCREAMING_SNAKE_CASE : List[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE : Any = (elem, weight) if position > 0: SCREAMING_SNAKE_CASE : List[Any] = get_parent_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._bubble_up(_lowerCamelCase ) else: self._bubble_down(_lowerCamelCase ) else: self._bubble_down(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Place a node at the proper position (upward movement) [to be used internally # only] SCREAMING_SNAKE_CASE : Optional[Any] = self.position_map[elem] if curr_pos == 0: return None SCREAMING_SNAKE_CASE : str = get_parent_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.heap[curr_pos] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_up(_lowerCamelCase ) return None def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Place a node at the proper position (downward movement) [to be used # internally only] SCREAMING_SNAKE_CASE : Optional[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.heap[curr_pos] SCREAMING_SNAKE_CASE : List[str] = get_child_left_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = get_child_right_position(_lowerCamelCase ) if child_left_position < self.elements and child_right_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.heap[child_left_position] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) if child_left_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) else: return None if child_right_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) return None def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Swap the nodes at the given positions SCREAMING_SNAKE_CASE : Optional[int] = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE : Any = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) SCREAMING_SNAKE_CASE : Optional[int] = nodea_pos SCREAMING_SNAKE_CASE : List[str] = nodea_pos class a_ ( Generic[T] ): """simple docstring""" def __init__( self ) ->None: SCREAMING_SNAKE_CASE : dict[T, dict[T, int]] = {} SCREAMING_SNAKE_CASE : int = 0 def __repr__( self ) ->str: return str(self.connections ) def __len__( self ) ->int: return self.nodes def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Add a node in the graph if it is not in the graph if node not in self.connections: SCREAMING_SNAKE_CASE : Any = {} self.nodes += 1 def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->None: # Add an edge between 2 nodes in the graph self.add_node(_lowerCamelCase ) self.add_node(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = weight SCREAMING_SNAKE_CASE : str = weight def UpperCAmelCase_( a__ , ): """simple docstring""" SCREAMING_SNAKE_CASE : dict[T, int] = {node: maxsize for node in graph.connections} SCREAMING_SNAKE_CASE : dict[T, T | None] = {node: None for node in graph.connections} SCREAMING_SNAKE_CASE : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(a__ , a__ ) if priority_queue.is_empty(): return dist, parent # initialization SCREAMING_SNAKE_CASE : List[Any] = priority_queue.extract_min() SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE : Any = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) SCREAMING_SNAKE_CASE : str = node # running prim's algorithm while not priority_queue.is_empty(): SCREAMING_SNAKE_CASE : List[str] = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE : List[Any] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) SCREAMING_SNAKE_CASE : str = node return dist, parent
19
1
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu a__ : str = get_tests_dir() + '''/test_data/fsmt/fsmt_val_data.json''' with io.open(filename, '''r''', encoding='''utf-8''') as f: a__ : Optional[Any] = json.load(f) @require_torch class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: return FSMTTokenizer.from_pretrained(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Dict = FSMTForConditionalGeneration.from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['''en-ru''', 2_6.0], ['''ru-en''', 2_2.0], ['''en-de''', 2_2.0], ['''de-en''', 2_9.0], ] ) @slow def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->str: # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE : List[str] = F"""facebook/wmt19-{pair}""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_tokenizer(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.get_model(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = bleu_data[pair]['''src'''] SCREAMING_SNAKE_CASE : Dict = bleu_data[pair]['''tgt'''] SCREAMING_SNAKE_CASE : Tuple = tokenizer(_lowerCamelCase , return_tensors='''pt''' , truncation=_lowerCamelCase , padding='''longest''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.batch_decode( _lowerCamelCase , skip_special_tokens=_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = calculate_bleu(_lowerCamelCase , _lowerCamelCase ) print(_lowerCamelCase ) self.assertGreaterEqual(scores['''bleu'''] , _lowerCamelCase )
19
from math import pi, sqrt, tan def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''surface_area_cube() only accepts non-negative values''' ) return 6 * side_length**2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if length < 0 or breadth < 0 or height < 0: raise ValueError('''surface_area_cuboid() only accepts non-negative values''' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_sphere() only accepts non-negative values''' ) return 4 * pi * radius**2 def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' ) return 3 * pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cone() only accepts non-negative values''' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( '''surface_area_conical_frustum() only accepts non-negative values''' ) SCREAMING_SNAKE_CASE : Optional[Any] = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cylinder() only accepts non-negative values''' ) return 2 * pi * radius * (height + radius) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if torus_radius < 0 or tube_radius < 0: raise ValueError('''surface_area_torus() only accepts non-negative values''' ) if torus_radius < tube_radius: raise ValueError( '''surface_area_torus() does not support spindle or self intersecting tori''' ) return 4 * pow(a__ , 2 ) * torus_radius * tube_radius def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if length < 0 or width < 0: raise ValueError('''area_rectangle() only accepts non-negative values''' ) return length * width def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''area_square() only accepts non-negative values''' ) return side_length**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_triangle() only accepts non-negative values''' ) return (base * height) / 2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('''Given three sides do not form a triangle''' ) SCREAMING_SNAKE_CASE : int = (sidea + sidea + sidea) / 2 SCREAMING_SNAKE_CASE : List[str] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_parallelogram() only accepts non-negative values''' ) return base * height def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if basea < 0 or basea < 0 or height < 0: raise ValueError('''area_trapezium() only accepts non-negative values''' ) return 1 / 2 * (basea + basea) * height def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''area_circle() only accepts non-negative values''' ) return pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius_x < 0 or radius_y < 0: raise ValueError('''area_ellipse() only accepts non-negative values''' ) return pi * radius_x * radius_y def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if diagonal_a < 0 or diagonal_a < 0: raise ValueError('''area_rhombus() only accepts non-negative values''' ) return 1 / 2 * diagonal_a * diagonal_a def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if not isinstance(a__ , a__ ) or sides < 3: raise ValueError( '''area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides''' ) elif length < 0: raise ValueError( '''area_reg_polygon() only accepts non-negative values as \ length of a side''' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('''[DEMO] Areas of various geometric shapes: \n''') print(F"Rectangle: {area_rectangle(10, 20) = }") print(F"Square: {area_square(10) = }") print(F"Triangle: {area_triangle(10, 10) = }") print(F"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(F"Parallelogram: {area_parallelogram(10, 20) = }") print(F"Rhombus: {area_rhombus(10, 20) = }") print(F"Trapezium: {area_trapezium(10, 20, 30) = }") print(F"Circle: {area_circle(20) = }") print(F"Ellipse: {area_ellipse(10, 20) = }") print('''\nSurface Areas of various geometric shapes: \n''') print(F"Cube: {surface_area_cube(20) = }") print(F"Cuboid: {surface_area_cuboid(10, 20, 30) = }") print(F"Sphere: {surface_area_sphere(20) = }") print(F"Hemisphere: {surface_area_hemisphere(20) = }") print(F"Cone: {surface_area_cone(10, 20) = }") print(F"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") print(F"Cylinder: {surface_area_cylinder(10, 20) = }") print(F"Torus: {surface_area_torus(20, 10) = }") print(F"Equilateral Triangle: {area_reg_polygon(3, 10) = }") print(F"Square: {area_reg_polygon(4, 10) = }") print(F"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
19
1
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Dict = 16 a__ : str = 32 def UpperCAmelCase_( a__ , a__ = 16 ): """simple docstring""" SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained('''bert-base-cased''' ) SCREAMING_SNAKE_CASE : Optional[int] = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(a__ ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=a__ , max_length=a__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE : Union[str, Any] = datasets.map( a__ , batched=a__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE : Union[str, Any] = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(a__ ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE : List[str] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE : List[Any] = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE : Optional[int] = 8 else: SCREAMING_SNAKE_CASE : Optional[Any] = None return tokenizer.pad( a__ , padding='''longest''' , max_length=a__ , pad_to_multiple_of=a__ , return_tensors='''pt''' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE : List[str] = DataLoader( tokenized_datasets['''train'''] , shuffle=a__ , collate_fn=a__ , batch_size=a__ ) SCREAMING_SNAKE_CASE : Tuple = DataLoader( tokenized_datasets['''validation'''] , shuffle=a__ , collate_fn=a__ , batch_size=a__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a__ : List[str] = mocked_dataloaders # noqa: F811 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , a__ ) == "1": SCREAMING_SNAKE_CASE : List[Any] = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: SCREAMING_SNAKE_CASE : Dict = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir ) else: SCREAMING_SNAKE_CASE : Tuple = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE : str = config['''lr'''] SCREAMING_SNAKE_CASE : Optional[int] = int(config['''num_epochs'''] ) SCREAMING_SNAKE_CASE : Union[str, Any] = int(config['''seed'''] ) SCREAMING_SNAKE_CASE : int = int(config['''batch_size'''] ) set_seed(a__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = get_dataloaders(a__ , a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = evaluate.load('''glue''' , '''mrpc''' ) # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE : List[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE : Tuple = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE : Dict = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE : Dict = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=a__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE : List[str] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE : Any = AdamW(params=model.parameters() , lr=a__ ) # Instantiate scheduler SCREAMING_SNAKE_CASE : Any = get_linear_schedule_with_warmup( optimizer=a__ , num_warmup_steps=100 , num_training_steps=(len(a__ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = accelerator.prepare( a__ , a__ , a__ , a__ , a__ ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: SCREAMING_SNAKE_CASE : str = os.path.split(a__ )[-1].split('''.''' )[0] accelerator.init_trackers(a__ , a__ ) # Now we train the model for epoch in range(a__ ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: SCREAMING_SNAKE_CASE : Dict = 0 for step, batch in enumerate(a__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE : Any = model(**a__ ) SCREAMING_SNAKE_CASE : int = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() SCREAMING_SNAKE_CASE : Any = loss / gradient_accumulation_steps accelerator.backward(a__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(a__ ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**a__ ) SCREAMING_SNAKE_CASE : Dict = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=a__ , references=a__ , ) SCREAMING_SNAKE_CASE : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , a__ ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { '''accuracy''': eval_metric['''accuracy'''], '''f1''': eval_metric['''f1'''], '''train_loss''': total_loss.item() / len(a__ ), '''epoch''': epoch, } , step=a__ , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=a__ , default=a__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) parser.add_argument( '''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , ) parser.add_argument( '''--project_dir''' , type=a__ , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , ) SCREAMING_SNAKE_CASE : Any = parser.parse_args() SCREAMING_SNAKE_CASE : Union[str, Any] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(a__ , a__ ) if __name__ == "__main__": main()
19
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: a__ : List[str] = None a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Dict = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/mbart-large-en-ro''': '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json''', '''facebook/mbart-large-cc25''': '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json''', }, } a__ : str = { '''facebook/mbart-large-en-ro''': 1_024, '''facebook/mbart-large-cc25''': 1_024, } # fmt: off a__ : List[str] = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = ['input_ids', 'attention_mask'] __SCREAMING_SNAKE_CASE : Tuple = MBartTokenizer __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase , ) ->List[Any]: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : List[str] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token super().__init__( vocab_file=_lowerCamelCase , tokenizer_file=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , src_lang=_lowerCamelCase , tgt_lang=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Any = vocab_file SCREAMING_SNAKE_CASE : List[Any] = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : Any = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) SCREAMING_SNAKE_CASE : int = { lang_code: self.convert_tokens_to_ids(_lowerCamelCase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE : List[str] = src_lang if src_lang is not None else '''en_XX''' SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __lowerCAmelCase ( self ) ->str: return self._src_lang @src_lang.setter def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[int] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : str = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) ->Optional[Any]: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[str] = self(_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang_id return inputs def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = "en_XX" , _lowerCamelCase = None , _lowerCamelCase = "ro_RO" , **_lowerCamelCase , ) ->BatchEncoding: SCREAMING_SNAKE_CASE : List[str] = src_lang SCREAMING_SNAKE_CASE : List[str] = tgt_lang return super().prepare_seqaseq_batch(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Dict: return self.set_src_lang_special_tokens(self.src_lang ) def __lowerCAmelCase ( self ) ->List[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : str = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Any = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file , _lowerCamelCase ) return (out_vocab_file,)
19
1
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): a__ : Optional[Any] = { '''linear''': PIL.Image.Resampling.BILINEAR, '''bilinear''': PIL.Image.Resampling.BILINEAR, '''bicubic''': PIL.Image.Resampling.BICUBIC, '''lanczos''': PIL.Image.Resampling.LANCZOS, '''nearest''': PIL.Image.Resampling.NEAREST, } else: a__ : List[Any] = { '''linear''': PIL.Image.LINEAR, '''bilinear''': PIL.Image.BILINEAR, '''bicubic''': PIL.Image.BICUBIC, '''lanczos''': PIL.Image.LANCZOS, '''nearest''': PIL.Image.NEAREST, } def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = (images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE : Tuple = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE : List[str] = numpy_to_pil(a__ ) return images def UpperCAmelCase_( a__ ): """simple docstring""" if images.ndim == 3: SCREAMING_SNAKE_CASE : str = images[None, ...] SCREAMING_SNAKE_CASE : List[Any] = (images * 255).round().astype('''uint8''' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images SCREAMING_SNAKE_CASE : List[Any] = [Image.fromarray(image.squeeze() , mode='''L''' ) for image in images] else: SCREAMING_SNAKE_CASE : Dict = [Image.fromarray(a__ ) for image in images] return pil_images
19
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging a__ : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=768 ) ->List[Any]: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = proj_size SCREAMING_SNAKE_CASE : Any = CLIPVisionModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = PaintByExampleMapper(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = nn.LayerNorm(config.hidden_size ) SCREAMING_SNAKE_CASE : int = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=False ) ->int: SCREAMING_SNAKE_CASE : Optional[Any] = self.model(pixel_values=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = clip_output.pooler_output SCREAMING_SNAKE_CASE : Optional[Any] = self.mapper(latent_states[:, None] ) SCREAMING_SNAKE_CASE : Tuple = self.final_layer_norm(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.proj_out(_lowerCamelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->List[str]: super().__init__() SCREAMING_SNAKE_CASE : str = (config.num_hidden_layers + 1) // 5 SCREAMING_SNAKE_CASE : List[Any] = config.hidden_size SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : Optional[Any] = nn.ModuleList( [ BasicTransformerBlock(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , activation_fn='''gelu''' , attention_bias=_lowerCamelCase ) for _ in range(_lowerCamelCase ) ] ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: for block in self.blocks: SCREAMING_SNAKE_CASE : Optional[int] = block(_lowerCamelCase ) return hidden_states
19
1
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
19
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 a__ : Tuple = '''▁''' a__ : List[Any] = {'''vocab_file''': '''spiece.model'''} a__ : Optional[Any] = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } a__ : str = { '''google/pegasus-xsum''': 512, } a__ : str = logging.get_logger(__name__) class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : str = ['input_ids', 'attention_mask'] def __init__( self , _lowerCamelCase , _lowerCamelCase="<pad>" , _lowerCamelCase="</s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<mask_2>" , _lowerCamelCase="<mask_1>" , _lowerCamelCase=None , _lowerCamelCase=103 , _lowerCamelCase = None , **_lowerCamelCase , ) ->None: SCREAMING_SNAKE_CASE : Dict = offset if additional_special_tokens is not None: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError( F"""additional_special_tokens should be of type {type(_lowerCamelCase )}, but is""" F""" {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : List[Any] = ( ([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(_lowerCamelCase ) , self.offset - 1 ) ] if len(set(_lowerCamelCase ) ) != len(_lowerCamelCase ): 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}.""" ) SCREAMING_SNAKE_CASE : Dict = additional_special_tokens_extended else: SCREAMING_SNAKE_CASE : str = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F"""<unk_{i}>""" for i in range(2 , self.offset )] SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , mask_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token_sent=_lowerCamelCase , offset=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[str] = mask_token_sent SCREAMING_SNAKE_CASE : Optional[int] = vocab_file SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) # add special tokens to encoder dict SCREAMING_SNAKE_CASE : Dict[int, str] = { 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 )} ) SCREAMING_SNAKE_CASE : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def __lowerCAmelCase ( self ) ->int: return len(self.sp_model ) + self.offset def __lowerCAmelCase ( self ) ->Dict[str, int]: SCREAMING_SNAKE_CASE : Union[str, Any] = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = self.__dict__.copy() SCREAMING_SNAKE_CASE : str = None return state def __setstate__( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : List[str] = {} SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.piece_to_id(_lowerCamelCase ) return sp_id + self.offset def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: SCREAMING_SNAKE_CASE : Dict = self.sp_model.IdToPiece(index - self.offset ) return token def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : int = '''''' 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(_lowerCamelCase ) + token SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(_lowerCamelCase ) out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def __lowerCAmelCase ( self , _lowerCamelCase=False ) ->str: return 1 def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Dict = 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ) ->List[int]: if already_has_special_tokens: return self._special_token_mask(_lowerCamelCase ) elif token_ids_a is None: return self._special_token_mask(_lowerCamelCase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->List[int]: 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : int = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE : Tuple = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
19
1
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem a__ : Optional[int] = importlib.util.find_spec('''s3fs''') is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 a__ : List[compression.BaseCompressedFileFileSystem] = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F"A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.") fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def UpperCAmelCase_( a__ ): """simple docstring""" if "://" in dataset_path: SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_path.split('''://''' )[1] return dataset_path def UpperCAmelCase_( a__ ): """simple docstring""" if fs is not None and fs.protocol != "file": return True else: return False def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = not is_remote_filesystem(a__ ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(a__ ) , fs._strip_protocol(a__ ) ) else: fs.mv(a__ , a__ , recursive=a__ ) def UpperCAmelCase_( ): """simple docstring""" if hasattr(fsspec.asyn , '''reset_lock''' ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : int = threading.Lock()
19
def UpperCAmelCase_( a__ ): """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Tuple = 1 while repunit: SCREAMING_SNAKE_CASE : Dict = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def UpperCAmelCase_( a__ = 1_000_000 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(a__ ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F"{solution() = }")
19
1
import qiskit def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = qiskit.Aer.get_backend('''aer_simulator''' ) # Create a Quantum Circuit acting on the q register SCREAMING_SNAKE_CASE : str = qiskit.QuantumCircuit(a__ , a__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator SCREAMING_SNAKE_CASE : Any = qiskit.execute(a__ , a__ , shots=1_000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(a__ ) if __name__ == "__main__": print(F"Total count for various states are: {single_qubit_measure(1, 1)}")
19
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=32 , _lowerCamelCase=3 , _lowerCamelCase=4 , _lowerCamelCase=[10, 20, 30, 40] , _lowerCamelCase=[2, 2, 3, 2] , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=10 , _lowerCamelCase=0.0_2 , _lowerCamelCase=["stage2", "stage3", "stage4"] , _lowerCamelCase=3 , _lowerCamelCase=None , ) ->Dict: SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Optional[Any] = batch_size SCREAMING_SNAKE_CASE : Optional[Any] = image_size SCREAMING_SNAKE_CASE : str = num_channels SCREAMING_SNAKE_CASE : Any = num_stages SCREAMING_SNAKE_CASE : List[str] = hidden_sizes SCREAMING_SNAKE_CASE : Optional[Any] = depths SCREAMING_SNAKE_CASE : Any = is_training SCREAMING_SNAKE_CASE : Tuple = use_labels SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : int = out_features SCREAMING_SNAKE_CASE : List[str] = num_labels SCREAMING_SNAKE_CASE : int = scope SCREAMING_SNAKE_CASE : Optional[Any] = num_stages def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : str = None if self.use_labels: SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) ->List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def __lowerCAmelCase ( self ) ->Any: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_lowerCamelCase , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_lowerCamelCase , loss_ignore_index=255 , num_labels=self.num_labels , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : List[Any] = UperNetForSemanticSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = (UperNetForSemanticSegmentation,) if is_torch_available() else () __SCREAMING_SNAKE_CASE : List[str] = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {} __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Union[str, Any] = False __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : Any = False def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[Any] = UperNetModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def __lowerCAmelCase ( self ) ->str: 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 __lowerCAmelCase ( self ) ->str: return def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Optional[int] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase ) @unittest.skip(reason='''UperNet does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) ->Union[str, Any]: pass @unittest.skip(reason='''UperNet does not support input and output embeddings''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->str: pass @require_torch_multi_gpu @unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def __lowerCAmelCase ( self ) ->str: pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowerCAmelCase ( self ) ->Tuple: pass def __lowerCAmelCase ( self ) ->int: def check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) SCREAMING_SNAKE_CASE : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # ConvNext'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] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Union[str, Any] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : str = _config_zero_init(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip(reason='''UperNet does not have tied weights''' ) def __lowerCAmelCase ( self ) ->List[Any]: pass @slow def __lowerCAmelCase ( self ) ->List[Any]: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Any = UperNetForSemanticSegmentation.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = hf_hub_download( repo_id='''hf-internal-testing/fixtures_ade20k''' , repo_type='''dataset''' , filename='''ADE_val_00000001.jpg''' ) SCREAMING_SNAKE_CASE : Any = Image.open(a__ ).convert('''RGB''' ) return image @require_torch @require_vision @slow class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny''' ) SCREAMING_SNAKE_CASE : Tuple = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny''' ) SCREAMING_SNAKE_CASE : str = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) )
19
1
import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder def UpperCAmelCase_( a__ , a__ , a__ , a__=None , a__=None , a__=None , a__=None , a__=None , ): """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE : Dict = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE : List[Any] = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE : int = torch.ones(config.encoder_layers , config.encoder_attention_heads , device=a__ ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE : Dict = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=a__ ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE : Optional[int] = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=a__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=99 , _lowerCamelCase=16 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=4 , _lowerCamelCase="relu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=20 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[str] = parent SCREAMING_SNAKE_CASE : Optional[int] = batch_size SCREAMING_SNAKE_CASE : Optional[int] = seq_length SCREAMING_SNAKE_CASE : Tuple = is_training SCREAMING_SNAKE_CASE : List[Any] = use_labels SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : int = hidden_size SCREAMING_SNAKE_CASE : str = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = encoder_layerdrop SCREAMING_SNAKE_CASE : Any = decoder_layerdrop SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Any = eos_token_id SCREAMING_SNAKE_CASE : int = pad_token_id SCREAMING_SNAKE_CASE : str = bos_token_id def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : int = self.eos_token_id # Eos Token SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for M2M100 the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input SCREAMING_SNAKE_CASE : List[str] = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE : int = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE : Tuple = self.get_config() SCREAMING_SNAKE_CASE : str = prepare_mam_aaa_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def __lowerCAmelCase ( self ) ->Union[str, Any]: return MaMaaaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , encoder_layerdrop=self.encoder_layerdrop , decoder_layerdrop=self.decoder_layerdrop , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , ) def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() return config, inputs_dict def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Dict: SCREAMING_SNAKE_CASE : Optional[Any] = MaMaaaModel(config=_lowerCamelCase ).get_decoder().to(_lowerCamelCase ).eval() SCREAMING_SNAKE_CASE : int = inputs_dict['''input_ids'''] SCREAMING_SNAKE_CASE : str = inputs_dict['''attention_mask'''] SCREAMING_SNAKE_CASE : int = inputs_dict['''head_mask'''] # first forward pass SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , head_mask=_lowerCamelCase , use_cache=_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE : str = model(_lowerCamelCase , attention_mask=_lowerCamelCase )['''last_hidden_state'''] SCREAMING_SNAKE_CASE : Dict = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[ '''last_hidden_state''' ] # select random slice SCREAMING_SNAKE_CASE : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE : Optional[int] = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_lowerCamelCase , _lowerCamelCase , atol=1e-2 ) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[Any] = MaMaaaModel(config=_lowerCamelCase ).to(_lowerCamelCase ).eval() SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = outputs.encoder_last_hidden_state SCREAMING_SNAKE_CASE : Optional[int] = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : str = model.get_encoder() encoder.save_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = MaMaaaEncoder.from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = encoder(inputs_dict['''input_ids'''] , attention_mask=inputs_dict['''attention_mask'''] )[ 0 ] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : List[Any] = model.get_decoder() decoder.save_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = MaMaaaDecoder.from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = decoder( input_ids=inputs_dict['''decoder_input_ids'''] , attention_mask=inputs_dict['''decoder_attention_mask'''] , encoder_hidden_states=_lowerCamelCase , encoder_attention_mask=inputs_dict['''attention_mask'''] , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class a_ ( a__ , a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = ( ( MaMaaaModel, MaMaaaForConditionalGeneration, ) if is_torch_available() else () ) __SCREAMING_SNAKE_CASE : Any = (MaMaaaForConditionalGeneration,) if is_torch_available() else () __SCREAMING_SNAKE_CASE : Optional[int] = ( { 'conversational': MaMaaaForConditionalGeneration, 'feature-extraction': MaMaaaModel, 'summarization': MaMaaaForConditionalGeneration, 'text2text-generation': MaMaaaForConditionalGeneration, 'translation': MaMaaaForConditionalGeneration, } if is_torch_available() else {} ) __SCREAMING_SNAKE_CASE : str = True __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : int = False def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->str: if pipeline_test_casse_name == "TranslationPipelineTests": # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`. # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer. return True return False def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Dict = MaMaaaModelTester(self ) SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Tuple: self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = model_class.from_pretrained(_lowerCamelCase , output_loading_info=_lowerCamelCase ) self.assertEqual(info['''missing_keys'''] , [] ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration): SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = copy.deepcopy(self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) if not self.is_encoder_decoder: SCREAMING_SNAKE_CASE : int = inputs['''input_ids'''] del inputs["input_ids"] else: SCREAMING_SNAKE_CASE : int = inputs['''input_ids'''] SCREAMING_SNAKE_CASE : int = inputs.get('''decoder_input_ids''' , _lowerCamelCase ) del inputs["input_ids"] inputs.pop('''decoder_input_ids''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = model.get_input_embeddings() if not self.is_encoder_decoder: SCREAMING_SNAKE_CASE : Optional[Any] = wte(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : List[str] = wte(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = wte(_lowerCamelCase ) with torch.no_grad(): model(**_lowerCamelCase )[0] def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Optional[int] = input_dict['''input_ids'''] SCREAMING_SNAKE_CASE : Tuple = input_ids.ne(1 ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = MaMaaaForConditionalGeneration(_lowerCamelCase ).eval().to(_lowerCamelCase ) if torch_device == "cuda": model.half() model.generate(_lowerCamelCase , attention_mask=_lowerCamelCase ) model.generate(num_beams=4 , do_sample=_lowerCamelCase , early_stopping=_lowerCamelCase , num_return_sequences=3 ) def UpperCAmelCase_( a__ ): """simple docstring""" return torch.tensor(a__ , dtype=torch.long , device=a__ ) a__ : Optional[int] = 1E-4 @require_torch @require_sentencepiece @require_tokenizers @slow class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowerCAmelCase ( self ) ->Any: return MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M''' ) def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : List[str] = MaMaaaModel.from_pretrained('''facebook/m2m100_418M''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = _long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]] ) SCREAMING_SNAKE_CASE : Any = _long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]] ) SCREAMING_SNAKE_CASE : int = prepare_mam_aaa_inputs_dict(model.config , _lowerCamelCase , _lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase )[0] SCREAMING_SNAKE_CASE : Tuple = torch.Size((1, 11, 1024) ) self.assertEqual(output.shape , _lowerCamelCase ) # change to expected output here SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]] , device=_lowerCamelCase ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Tuple = MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M''' ).to(_lowerCamelCase ) # change to intended input SCREAMING_SNAKE_CASE : List[Any] = _long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]] ) SCREAMING_SNAKE_CASE : Optional[int] = _long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]] ) SCREAMING_SNAKE_CASE : Any = prepare_mam_aaa_inputs_dict(model.config , _lowerCamelCase , _lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase )[0] SCREAMING_SNAKE_CASE : Tuple = torch.Size((1, 11, model.config.vocab_size) ) self.assertEqual(output.shape , _lowerCamelCase ) # change to expected output here SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]] , device=_lowerCamelCase ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : List[str] = MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M''' , src_lang='''fr''' , tgt_lang='''en''' ) SCREAMING_SNAKE_CASE : str = [ '''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''', '''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''', '''Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent''' ''' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de''' ''' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.''', ] # The below article tests that we don't add any hypotheses outside of the top n_beams SCREAMING_SNAKE_CASE : List[str] = tokenizer(_lowerCamelCase , padding=_lowerCamelCase , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE : str = model.generate( input_ids=dct['''input_ids'''].to(_lowerCamelCase ) , attention_mask=dct['''attention_mask'''].to(_lowerCamelCase ) , num_beams=5 , forced_bos_token_id=tokenizer.get_lang_id('''en''' ) , ) SCREAMING_SNAKE_CASE : Dict = [ '''The NSA case highlights the total absence of intelligence debate''', '''I think there are two levels of response from the French government.''', '''When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.''' ''' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all''' ''' communications in France.''', ] SCREAMING_SNAKE_CASE : int = tokenizer.batch_decode( hypotheses_batch.tolist() , clean_up_tokenization_spaces=_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) assert generated == expected_en
19
import datasets from .evaluate import evaluate a__ : Dict = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' a__ : List[str] = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' a__ : List[Any] = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric("cuad") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': { '''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.features.Sequence(datasets.Value('''string''' ) ), }, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://www.atticusprojectai.org/cuad'''] , reference_urls=['''https://www.atticusprojectai.org/cuad'''] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Any = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} SCREAMING_SNAKE_CASE : int = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] SCREAMING_SNAKE_CASE : Dict = evaluate(dataset=_lowerCamelCase , predictions=_lowerCamelCase ) return score
19
1
import random def UpperCAmelCase_( a__ , a__ , a__ = False ): """simple docstring""" SCREAMING_SNAKE_CASE : dict = {i: [] for i in range(a__ )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(a__ ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(a__ ): for j in range(i + 1 , a__ ): if random.random() < probability: graph[i].append(a__ ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(a__ ) return graph def UpperCAmelCase_( a__ ): """simple docstring""" return { i: [j for j in range(a__ ) if i != j] for i in range(a__ ) } if __name__ == "__main__": import doctest doctest.testmod()
19
from sklearn.metrics import matthews_corrcoef import datasets a__ : Optional[Any] = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' a__ : str = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' a__ : Union[str, Any] = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ) ->List[str]: return { "matthews_correlation": float(matthews_corrcoef(_lowerCamelCase , _lowerCamelCase , sample_weight=_lowerCamelCase ) ), }
19
1
from __future__ import annotations import math def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = u for i in range(1 , a__ ): SCREAMING_SNAKE_CASE : int = temp * (u - i) return temp def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = int(input('''enter the numbers of values: ''' ) ) SCREAMING_SNAKE_CASE : list[list[float]] = [] for _ in range(a__ ): y.append([] ) for i in range(a__ ): for j in range(a__ ): y[i].append(a__ ) SCREAMING_SNAKE_CASE : str = 0 print('''enter the values of parameters in a list: ''' ) SCREAMING_SNAKE_CASE : Any = list(map(a__ , input().split() ) ) print('''enter the values of corresponding parameters: ''' ) for i in range(a__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = float(input() ) SCREAMING_SNAKE_CASE : List[str] = int(input('''enter the value to interpolate: ''' ) ) SCREAMING_SNAKE_CASE : Tuple = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , a__ ): for j in range(n - i ): SCREAMING_SNAKE_CASE : Optional[Any] = y[j + 1][i - 1] - y[j][i - 1] SCREAMING_SNAKE_CASE : Dict = y[0][0] for i in range(1 , a__ ): summ += (ucal(a__ , a__ ) * y[0][i]) / math.factorial(a__ ) print(F"""the value at {value} is {summ}""" ) if __name__ == "__main__": main()
19
# Copyright 2021 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 argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=a__ ) SCREAMING_SNAKE_CASE : int = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=a__ ) env_command_parser(subparsers=a__ ) launch_command_parser(subparsers=a__ ) tpu_command_parser(subparsers=a__ ) test_command_parser(subparsers=a__ ) # Let's go SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() if not hasattr(a__ , '''func''' ): parser.print_help() exit(1 ) # Run args.func(a__ ) if __name__ == "__main__": main()
19
1
from __future__ import annotations from typing import TypedDict class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : str __SCREAMING_SNAKE_CASE : int def UpperCAmelCase_( a__ ): """simple docstring""" if not isinstance(a__ , a__ ): raise TypeError('''The parameter s type must be str.''' ) return [s[i:] + s[:i] for i in range(len(a__ ) )] def UpperCAmelCase_( a__ ): """simple docstring""" if not isinstance(a__ , a__ ): raise TypeError('''The parameter s type must be str.''' ) if not s: raise ValueError('''The parameter s must not be empty.''' ) SCREAMING_SNAKE_CASE : List[Any] = all_rotations(a__ ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation SCREAMING_SNAKE_CASE : BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(a__ ), } return response def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if not isinstance(a__ , a__ ): raise TypeError('''The parameter bwt_string type must be str.''' ) if not bwt_string: raise ValueError('''The parameter bwt_string must not be empty.''' ) try: SCREAMING_SNAKE_CASE : List[Any] = int(a__ ) except ValueError: raise TypeError( '''The parameter idx_original_string type must be int or passive''' ''' of cast to int.''' ) if idx_original_string < 0: raise ValueError('''The parameter idx_original_string must not be lower than 0.''' ) if idx_original_string >= len(a__ ): raise ValueError( '''The parameter idx_original_string must be lower than''' ''' len(bwt_string).''' ) SCREAMING_SNAKE_CASE : Optional[int] = [''''''] * len(a__ ) for _ in range(len(a__ ) ): for i in range(len(a__ ) ): SCREAMING_SNAKE_CASE : Any = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": a__ : Optional[int] = '''Provide a string that I will generate its BWT transform: ''' a__ : Dict = input(entry_msg).strip() a__ : Optional[Any] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) a__ : Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
19
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Optional[Any] = {'''vocab_file''': '''vocab.json'''} a__ : str = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } a__ : Tuple = {'''mgp-str''': 27} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _lowerCamelCase , _lowerCamelCase="[GO]" , _lowerCamelCase="[GO]" , _lowerCamelCase="[s]" , _lowerCamelCase="[GO]" , **_lowerCamelCase ) ->Dict: super().__init__( unk_token=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , pad_token=_lowerCamelCase , **_lowerCamelCase , ) with open(_lowerCamelCase , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE : List[Any] = json.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.vocab.items()} @property def __lowerCAmelCase ( self ) ->List[Any]: return len(self.vocab ) def __lowerCAmelCase ( self ) ->Union[str, Any]: return dict(self.vocab , **self.added_tokens_encoder ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Union[str, Any] = [] for s in text: char_tokens.extend(_lowerCamelCase ) return char_tokens def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: return self.vocab.get(_lowerCamelCase , self.vocab.get(self.unk_token ) ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: return self.decoder.get(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(_lowerCamelCase ) ) return SCREAMING_SNAKE_CASE : str = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=_lowerCamelCase , ensure_ascii=_lowerCamelCase ) + '''\n''' ) return (vocab_file,)
19
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a__ : Tuple = logging.get_logger(__name__) a__ : Optional[Any] = { '''SenseTime/deformable-detr''': '''https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json''', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = 'deformable_detr' __SCREAMING_SNAKE_CASE : List[str] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=3 , _lowerCamelCase=300 , _lowerCamelCase=1024 , _lowerCamelCase=6 , _lowerCamelCase=1024 , _lowerCamelCase=8 , _lowerCamelCase=6 , _lowerCamelCase=1024 , _lowerCamelCase=8 , _lowerCamelCase=0.0 , _lowerCamelCase=True , _lowerCamelCase="relu" , _lowerCamelCase=256 , _lowerCamelCase=0.1 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1.0 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase="sine" , _lowerCamelCase="resnet50" , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=4 , _lowerCamelCase=4 , _lowerCamelCase=4 , _lowerCamelCase=False , _lowerCamelCase=300 , _lowerCamelCase=False , _lowerCamelCase=1 , _lowerCamelCase=5 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=1 , _lowerCamelCase=5 , _lowerCamelCase=2 , _lowerCamelCase=0.1 , _lowerCamelCase=0.2_5 , _lowerCamelCase=False , **_lowerCamelCase , ) ->List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Union[str, Any] = backbone_config.get('''model_type''' ) SCREAMING_SNAKE_CASE : Optional[Any] = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE : Tuple = config_class.from_dict(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = use_timm_backbone SCREAMING_SNAKE_CASE : Tuple = backbone_config SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : Optional[int] = num_queries SCREAMING_SNAKE_CASE : Any = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[Any] = d_model SCREAMING_SNAKE_CASE : List[str] = encoder_ffn_dim SCREAMING_SNAKE_CASE : int = encoder_layers SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_attention_heads SCREAMING_SNAKE_CASE : int = decoder_ffn_dim SCREAMING_SNAKE_CASE : Tuple = decoder_layers SCREAMING_SNAKE_CASE : Union[str, Any] = decoder_attention_heads SCREAMING_SNAKE_CASE : int = dropout SCREAMING_SNAKE_CASE : List[str] = attention_dropout SCREAMING_SNAKE_CASE : Dict = activation_dropout SCREAMING_SNAKE_CASE : Union[str, Any] = activation_function SCREAMING_SNAKE_CASE : Tuple = init_std SCREAMING_SNAKE_CASE : Dict = init_xavier_std SCREAMING_SNAKE_CASE : str = encoder_layerdrop SCREAMING_SNAKE_CASE : List[str] = auxiliary_loss SCREAMING_SNAKE_CASE : List[str] = position_embedding_type SCREAMING_SNAKE_CASE : Tuple = backbone SCREAMING_SNAKE_CASE : Optional[int] = use_pretrained_backbone SCREAMING_SNAKE_CASE : List[Any] = dilation # deformable attributes SCREAMING_SNAKE_CASE : Union[str, Any] = num_feature_levels SCREAMING_SNAKE_CASE : Any = encoder_n_points SCREAMING_SNAKE_CASE : List[Any] = decoder_n_points SCREAMING_SNAKE_CASE : List[Any] = two_stage SCREAMING_SNAKE_CASE : str = two_stage_num_proposals SCREAMING_SNAKE_CASE : str = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError('''If two_stage is True, with_box_refine must be True.''' ) # Hungarian matcher SCREAMING_SNAKE_CASE : List[str] = class_cost SCREAMING_SNAKE_CASE : Dict = bbox_cost SCREAMING_SNAKE_CASE : Optional[Any] = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE : List[str] = mask_loss_coefficient SCREAMING_SNAKE_CASE : List[Any] = dice_loss_coefficient SCREAMING_SNAKE_CASE : Optional[Any] = bbox_loss_coefficient SCREAMING_SNAKE_CASE : List[str] = giou_loss_coefficient SCREAMING_SNAKE_CASE : str = eos_coefficient SCREAMING_SNAKE_CASE : Dict = focal_alpha SCREAMING_SNAKE_CASE : str = disable_custom_kernels super().__init__(is_encoder_decoder=_lowerCamelCase , **_lowerCamelCase ) @property def __lowerCAmelCase ( self ) ->int: return self.encoder_attention_heads @property def __lowerCAmelCase ( self ) ->int: return self.d_model def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Optional[int] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: SCREAMING_SNAKE_CASE : Optional[Any] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE : List[Any] = self.__class__.model_type return output
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a__ : Optional[Any] = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['''DeiTFeatureExtractor'''] a__ : Any = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ '''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 a__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=99 , _lowerCamelCase=32 , _lowerCamelCase=5 , _lowerCamelCase=4 , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=512 , _lowerCamelCase=16 , _lowerCamelCase=2 , _lowerCamelCase=0.0_2 , _lowerCamelCase=3 , _lowerCamelCase=4 , _lowerCamelCase=None , ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[str] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Optional[Any] = seq_length SCREAMING_SNAKE_CASE : Dict = is_training SCREAMING_SNAKE_CASE : Any = use_token_type_ids SCREAMING_SNAKE_CASE : Tuple = use_labels SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : str = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : Tuple = type_sequence_label_size SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : List[str] = num_labels SCREAMING_SNAKE_CASE : str = num_choices SCREAMING_SNAKE_CASE : List[Any] = scope SCREAMING_SNAKE_CASE : Any = self.vocab_size - 1 def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : List[Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , *_lowerCamelCase ) ->List[Any]: SCREAMING_SNAKE_CASE : Union[str, Any] = OpenAIGPTModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Dict = model(_lowerCamelCase , token_type_ids=_lowerCamelCase , head_mask=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = model(_lowerCamelCase , token_type_ids=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , *_lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : Any = OpenAIGPTLMHeadModel(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Dict = model(_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , *_lowerCamelCase ) ->List[str]: SCREAMING_SNAKE_CASE : Tuple = OpenAIGPTDoubleHeadsModel(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Dict = model(_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , *_lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : Tuple = self.num_labels SCREAMING_SNAKE_CASE : List[str] = OpenAIGPTForSequenceClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Dict = model(_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE : List[str] = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class a_ ( a__ , a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) __SCREAMING_SNAKE_CASE : Optional[Any] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly __SCREAMING_SNAKE_CASE : List[Any] = ( { 'feature-extraction': OpenAIGPTModel, 'text-classification': OpenAIGPTForSequenceClassification, 'text-generation': OpenAIGPTLMHeadModel, 'zero-shot': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Optional[Any]: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=False ) ->int: SCREAMING_SNAKE_CASE : Optional[int] = super()._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": SCREAMING_SNAKE_CASE : int = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Dict = inputs_dict['''labels'''] SCREAMING_SNAKE_CASE : Dict = inputs_dict['''labels'''] SCREAMING_SNAKE_CASE : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_lowerCamelCase ) return inputs_dict def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Any = OpenAIGPTModelTester(self ) SCREAMING_SNAKE_CASE : Any = ConfigTester(self , config_class=_lowerCamelCase , n_embd=37 ) def __lowerCAmelCase ( self ) ->Union[str, Any]: self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_lowerCamelCase ) @slow def __lowerCAmelCase ( self ) ->Optional[int]: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Optional[int] = OpenAIGPTModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[str] = OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt''' ) model.to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=_lowerCamelCase ) # the president is SCREAMING_SNAKE_CASE : int = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 4_0477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the SCREAMING_SNAKE_CASE : Optional[int] = model.generate(_lowerCamelCase , do_sample=_lowerCamelCase ) self.assertListEqual(output_ids[0].tolist() , _lowerCamelCase )
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''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 a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
19
1
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline a__ : str = datasets.utils.logging.get_logger(__name__) @dataclass class a_ ( datasets.BuilderConfig ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[datasets.Features] = None __SCREAMING_SNAKE_CASE : str = "utf-8" __SCREAMING_SNAKE_CASE : Optional[str] = None __SCREAMING_SNAKE_CASE : Optional[str] = None __SCREAMING_SNAKE_CASE : bool = True # deprecated __SCREAMING_SNAKE_CASE : Optional[int] = None # deprecated __SCREAMING_SNAKE_CASE : int = 10 << 20 # 10MB __SCREAMING_SNAKE_CASE : Optional[bool] = None class a_ ( datasets.ArrowBasedBuilder ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = JsonConfig def __lowerCAmelCase ( self ) ->Dict: if self.config.block_size is not None: logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''' ) SCREAMING_SNAKE_CASE : List[str] = self.config.block_size if self.config.use_threads is not True: logger.warning( '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.''' ) if self.config.newlines_in_values is not None: raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported''' ) return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCamelCase , (str, list, tuple) ): SCREAMING_SNAKE_CASE : Dict = data_files if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : List[str] = [files] SCREAMING_SNAKE_CASE : Tuple = [dl_manager.iter_files(_lowerCamelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] SCREAMING_SNAKE_CASE : Any = [] for split_name, files in data_files.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Optional[int] = [files] SCREAMING_SNAKE_CASE : List[Any] = [dl_manager.iter_files(_lowerCamelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , _lowerCamelCase ) ->pa.Table: if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): SCREAMING_SNAKE_CASE : int = self.config.features.arrow_schema.field(_lowerCamelCase ).type SCREAMING_SNAKE_CASE : Any = pa_table.append_column(_lowerCamelCase , pa.array([None] * len(_lowerCamelCase ) , type=_lowerCamelCase ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example SCREAMING_SNAKE_CASE : str = table_cast(_lowerCamelCase , self.config.features.arrow_schema ) return pa_table def __lowerCAmelCase ( self , _lowerCamelCase ) ->Optional[Any]: for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(_lowerCamelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: SCREAMING_SNAKE_CASE : List[str] = json.load(_lowerCamelCase ) # We keep only the field we are interested in SCREAMING_SNAKE_CASE : Optional[int] = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(_lowerCamelCase , (list, tuple) ): SCREAMING_SNAKE_CASE : List[Any] = set().union(*[row.keys() for row in dataset] ) SCREAMING_SNAKE_CASE : int = {col: [row.get(_lowerCamelCase ) for row in dataset] for col in keys} else: SCREAMING_SNAKE_CASE : int = dataset SCREAMING_SNAKE_CASE : str = pa.Table.from_pydict(_lowerCamelCase ) yield file_idx, self._cast_table(_lowerCamelCase ) # If the file has one json object per line else: with open(_lowerCamelCase , '''rb''' ) as f: SCREAMING_SNAKE_CASE : int = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small SCREAMING_SNAKE_CASE : int = max(self.config.chunksize // 32 , 16 << 10 ) SCREAMING_SNAKE_CASE : Optional[int] = ( self.config.encoding_errors if self.config.encoding_errors is not None else '''strict''' ) while True: SCREAMING_SNAKE_CASE : str = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(_lowerCamelCase ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": SCREAMING_SNAKE_CASE : Optional[Any] = batch.decode(self.config.encoding , errors=_lowerCamelCase ).encode('''utf-8''' ) try: while True: try: SCREAMING_SNAKE_CASE : str = paj.read_json( io.BytesIO(_lowerCamelCase ) , read_options=paj.ReadOptions(block_size=_lowerCamelCase ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(_lowerCamelCase , pa.ArrowInvalid ) and "straddling" not in str(_lowerCamelCase ) or block_size > len(_lowerCamelCase ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(_lowerCamelCase )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( _lowerCamelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(_lowerCamelCase ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(_lowerCamelCase )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(_lowerCamelCase , _lowerCamelCase ): # list is the only sequence type supported in JSON try: SCREAMING_SNAKE_CASE : Tuple = set().union(*[row.keys() for row in dataset] ) SCREAMING_SNAKE_CASE : Optional[Any] = {col: [row.get(_lowerCamelCase ) for row in dataset] for col in keys} SCREAMING_SNAKE_CASE : str = pa.Table.from_pydict(_lowerCamelCase ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(_lowerCamelCase )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(_lowerCamelCase ) break else: logger.error(F"""Failed to read file '{file}' with error {type(_lowerCamelCase )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase ) batch_idx += 1
19
import math from collections.abc import Iterator from itertools import takewhile def UpperCAmelCase_( a__ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = 2 while True: if is_prime(a__ ): yield num num += 1 def UpperCAmelCase_( a__ = 2_000_000 ): """simple docstring""" return sum(takewhile(lambda a__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"{solution() = }")
19
1
# Copyright 2021 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 argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=a__ ) SCREAMING_SNAKE_CASE : int = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=a__ ) env_command_parser(subparsers=a__ ) launch_command_parser(subparsers=a__ ) tpu_command_parser(subparsers=a__ ) test_command_parser(subparsers=a__ ) # Let's go SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() if not hasattr(a__ , '''func''' ): parser.print_help() exit(1 ) # Run args.func(a__ ) if __name__ == "__main__": main()
19
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a_ ( a__ ): """simple docstring""" def __init__( self , *_lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase ) ->int: super().__init__(*_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = eval_examples SCREAMING_SNAKE_CASE : Optional[int] = post_process_function def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase=None , _lowerCamelCase = None , _lowerCamelCase = "eval" , **_lowerCamelCase , ) ->Dict[str, float]: SCREAMING_SNAKE_CASE : Any = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) SCREAMING_SNAKE_CASE : Dict = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) SCREAMING_SNAKE_CASE : Any = gen_kwargs SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : str = self.get_eval_dataloader(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Optional[Any] = self.compute_metrics SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : Optional[Any] = time.time() SCREAMING_SNAKE_CASE : List[str] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Tuple = eval_loop( _lowerCamelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Dict = compute_metrics SCREAMING_SNAKE_CASE : Tuple = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : Optional[int] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_lowerCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : int = self.callback_handler.on_evaluate(self.args , self.state , self.control , _lowerCamelCase ) return metrics def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase = "test" , **_lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : str = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(_lowerCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[str] = time.time() SCREAMING_SNAKE_CASE : Optional[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Any = eval_loop( _lowerCamelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Optional[int] = compute_metrics SCREAMING_SNAKE_CASE : List[Any] = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , '''predict''' ) SCREAMING_SNAKE_CASE : Dict = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : List[Any] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_lowerCamelCase )
19
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : Union[str, Any] = { '''configuration_swinv2''': ['''SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Swinv2Config'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Swinv2ForImageClassification''', '''Swinv2ForMaskedImageModeling''', '''Swinv2Model''', '''Swinv2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys a__ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = DDIMPipeline __SCREAMING_SNAKE_CASE : Tuple = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __SCREAMING_SNAKE_CASE : Tuple = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } __SCREAMING_SNAKE_CASE : str = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = False def __lowerCAmelCase ( self ) ->int: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler() SCREAMING_SNAKE_CASE : Dict = {'''unet''': unet, '''scheduler''': scheduler} return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->int: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : int = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Optional[int] = '''cpu''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[Any] = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) SCREAMING_SNAKE_CASE : int = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) SCREAMING_SNAKE_CASE : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def __lowerCAmelCase ( self ) ->Optional[int]: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_save_load_local(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Union[str, Any]: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[int] = '''google/ddpm-cifar10-32''' SCREAMING_SNAKE_CASE : Dict = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler() SCREAMING_SNAKE_CASE : Optional[int] = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddim.to(_lowerCamelCase ) ddim.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = ddim(generator=_lowerCamelCase , eta=0.0 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[Any] = '''google/ddpm-ema-bedroom-256''' SCREAMING_SNAKE_CASE : List[str] = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = DDIMScheduler.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddpm.to(_lowerCamelCase ) ddpm.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = ddpm(generator=_lowerCamelCase , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
19
1
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 a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Any = '''▁''' a__ : int = {'''vocab_file''': '''sentencepiece.bpe.model'''} a__ : Optional[Any] = { '''vocab_file''': { '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''', } } a__ : Any = { '''facebook/xglm-564M''': 2_048, } class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : List[Any] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self , _lowerCamelCase , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase = None , **_lowerCamelCase , ) ->None: SCREAMING_SNAKE_CASE : str = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE : str = 7 SCREAMING_SNAKE_CASE : Dict = [F"""<madeupword{i}>""" for i in range(self.num_madeup_words )] SCREAMING_SNAKE_CASE : Dict = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , pad_token=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : Optional[Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE : int = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE : Union[str, Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE : Tuple = len(self.sp_model ) SCREAMING_SNAKE_CASE : Tuple = {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) ->List[str]: SCREAMING_SNAKE_CASE : List[str] = self.__dict__.copy() SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : int = self.sp_model.serialized_model_proto() return state def __setstate__( self , _lowerCamelCase ) ->Dict: SCREAMING_SNAKE_CASE : List[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : Tuple = {} SCREAMING_SNAKE_CASE : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ) ->List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def __lowerCAmelCase ( self ) ->List[str]: return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[str] = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : Optional[Any] = self.sp_model.PieceToId(_lowerCamelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: SCREAMING_SNAKE_CASE : List[str] = ''''''.join(_lowerCamelCase ).replace(_lowerCamelCase , ''' ''' ).strip() return out_string def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : Optional[int] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE : str = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
19
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = XLMProphetNetTokenizer __SCREAMING_SNAKE_CASE : List[str] = False __SCREAMING_SNAKE_CASE : Dict = True def __lowerCAmelCase ( self ) ->Dict: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE : Optional[Any] = XLMProphetNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : List[str] = '''[PAD]''' SCREAMING_SNAKE_CASE : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''[PAD]''' ) self.assertEqual(vocab_keys[1] , '''[CLS]''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(_lowerCamelCase ) , 1012 ) def __lowerCAmelCase ( self ) ->List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = XLMProphetNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''[UNK]''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''[UNK]''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self ) ->List[str]: return XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased''' ) @slow def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Union[str, Any] = '''Hello World!''' SCREAMING_SNAKE_CASE : int = [3_5389, 6672, 49, 2] self.assertListEqual(_lowerCamelCase , self.big_tokenizer.encode(_lowerCamelCase ) ) @slow def __lowerCAmelCase ( self ) ->int: # fmt: off SCREAMING_SNAKE_CASE : str = {'''input_ids''': [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''microsoft/xprophetnet-large-wiki100-cased''' , revision='''1acad1643ddd54a44df6a1b797ada8373685d90e''' , )
19
1
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if isinstance(a__ , torch.Tensor ): return image elif isinstance(a__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE : Dict = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE : List[Any] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE : Union[str, Any] = np.concatenate(a__ , axis=0 ) SCREAMING_SNAKE_CASE : Dict = np.array(a__ ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE : Dict = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE : Any = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE : str = torch.from_numpy(a__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE : int = torch.cat(a__ , dim=0 ) return image def UpperCAmelCase_( a__ , a__ , a__ , a__=0.9_995 ): """simple docstring""" if not isinstance(a__ , np.ndarray ): SCREAMING_SNAKE_CASE : int = True SCREAMING_SNAKE_CASE : List[Any] = va.device SCREAMING_SNAKE_CASE : str = va.cpu().numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = va.cpu().numpy() SCREAMING_SNAKE_CASE : str = np.sum(va * va / (np.linalg.norm(a__ ) * np.linalg.norm(a__ )) ) if np.abs(a__ ) > DOT_THRESHOLD: SCREAMING_SNAKE_CASE : str = (1 - t) * va + t * va else: SCREAMING_SNAKE_CASE : List[Any] = np.arccos(a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = np.sin(a__ ) SCREAMING_SNAKE_CASE : List[Any] = theta_a * t SCREAMING_SNAKE_CASE : str = np.sin(a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = np.sin(theta_a - theta_t ) / sin_theta_a SCREAMING_SNAKE_CASE : Tuple = sin_theta_t / sin_theta_a SCREAMING_SNAKE_CASE : List[Any] = sa * va + sa * va if inputs_are_torch: SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(a__ ).to(a__ ) return va def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = F.normalize(a__ , dim=-1 ) SCREAMING_SNAKE_CASE : Any = F.normalize(a__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" for param in model.parameters(): SCREAMING_SNAKE_CASE : Union[str, Any] = value class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , ) ->List[str]: super().__init__() self.register_modules( vae=_lowerCamelCase , text_encoder=_lowerCamelCase , clip_model=_lowerCamelCase , tokenizer=_lowerCamelCase , unet=_lowerCamelCase , scheduler=_lowerCamelCase , feature_extractor=_lowerCamelCase , coca_model=_lowerCamelCase , coca_tokenizer=_lowerCamelCase , coca_transform=_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[str] = ( feature_extractor.size if isinstance(feature_extractor.size , _lowerCamelCase ) else feature_extractor.size['''shortest_edge'''] ) SCREAMING_SNAKE_CASE : Tuple = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , _lowerCamelCase ) set_requires_grad(self.clip_model , _lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase = "auto" ) ->Optional[int]: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->str: self.enable_attention_slicing(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->int: set_requires_grad(self.vae , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Dict: set_requires_grad(self.vae , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[int]: set_requires_grad(self.unet , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->int: set_requires_grad(self.unet , _lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Dict: # get the original timestep using init_timestep SCREAMING_SNAKE_CASE : str = min(int(num_inference_steps * strength ) , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = max(num_inference_steps - init_timestep , 0 ) SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ) ->str: if not isinstance(_lowerCamelCase , torch.Tensor ): raise ValueError(F"""`image` has to be of type `torch.Tensor` but is {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : List[Any] = image.to(device=_lowerCamelCase , dtype=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Union[str, Any] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_lowerCamelCase ) ] SCREAMING_SNAKE_CASE : Tuple = torch.cat(_lowerCamelCase , dim=0 ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = self.vae.encode(_lowerCamelCase ).latent_dist.sample(_lowerCamelCase ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor SCREAMING_SNAKE_CASE : Union[str, Any] = 0.1_8_2_1_5 * init_latents SCREAMING_SNAKE_CASE : Tuple = init_latents.repeat_interleave(_lowerCamelCase , dim=0 ) SCREAMING_SNAKE_CASE : Tuple = randn_tensor(init_latents.shape , generator=_lowerCamelCase , device=_lowerCamelCase , dtype=_lowerCamelCase ) # get latents SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.add_noise(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : str = init_latents return latents def __lowerCAmelCase ( self , _lowerCamelCase ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Tuple = self.coca_transform(_lowerCamelCase ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE : int = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) SCREAMING_SNAKE_CASE : List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Dict: SCREAMING_SNAKE_CASE : List[str] = self.feature_extractor.preprocess(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() SCREAMING_SNAKE_CASE : Optional[Any] = self.clip_model.get_image_features(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_embeddings_clip.repeat_interleave(_lowerCamelCase , dim=0 ) return image_embeddings_clip @torch.enable_grad() def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) ->int: SCREAMING_SNAKE_CASE : List[Any] = latents.detach().requires_grad_() SCREAMING_SNAKE_CASE : List[str] = self.scheduler.scale_model_input(_lowerCamelCase , _lowerCamelCase ) # predict the noise residual SCREAMING_SNAKE_CASE : Optional[Any] = self.unet(_lowerCamelCase , _lowerCamelCase , encoder_hidden_states=_lowerCamelCase ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): SCREAMING_SNAKE_CASE : Any = self.scheduler.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE : int = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE : Optional[int] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE : Dict = torch.sqrt(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , _lowerCamelCase ): SCREAMING_SNAKE_CASE : int = self.scheduler.sigmas[index] SCREAMING_SNAKE_CASE : int = latents - sigma * noise_pred else: raise ValueError(F"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor SCREAMING_SNAKE_CASE : str = 1 / 0.1_8_2_1_5 * sample SCREAMING_SNAKE_CASE : List[Any] = self.vae.decode(_lowerCamelCase ).sample SCREAMING_SNAKE_CASE : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE : Tuple = transforms.Resize(self.feature_extractor_size )(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = self.normalize(_lowerCamelCase ).to(latents.dtype ) SCREAMING_SNAKE_CASE : Any = self.clip_model.get_image_features(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = spherical_dist_loss(_lowerCamelCase , _lowerCamelCase ).mean() * clip_guidance_scale SCREAMING_SNAKE_CASE : List[str] = -torch.autograd.grad(_lowerCamelCase , _lowerCamelCase )[0] if isinstance(self.scheduler , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Tuple = latents.detach() + grads * (sigma**2) SCREAMING_SNAKE_CASE : Dict = noise_pred_original else: SCREAMING_SNAKE_CASE : int = noise_pred_original - torch.sqrt(_lowerCamelCase ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = 512 , _lowerCamelCase = 512 , _lowerCamelCase = 0.6 , _lowerCamelCase = 50 , _lowerCamelCase = 7.5 , _lowerCamelCase = 1 , _lowerCamelCase = 0.0 , _lowerCamelCase = 100 , _lowerCamelCase = None , _lowerCamelCase = "pil" , _lowerCamelCase = True , _lowerCamelCase = 0.8 , _lowerCamelCase = 0.1 , _lowerCamelCase = 0.1 , ) ->Dict: if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) != batch_size: raise ValueError(F"""You have passed {batch_size} batch_size, but only {len(_lowerCamelCase )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(_lowerCamelCase , torch.Generator ) and batch_size > 1: SCREAMING_SNAKE_CASE : Any = [generator] + [None] * (batch_size - 1) SCREAMING_SNAKE_CASE : Optional[Any] = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] SCREAMING_SNAKE_CASE : List[Any] = [x[0] for x in coca_is_none if x[1]] SCREAMING_SNAKE_CASE : Tuple = ''', '''.join(_lowerCamelCase ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(_lowerCamelCase ): raise ValueError( F"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" F"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) SCREAMING_SNAKE_CASE : Any = self.get_image_description(_lowerCamelCase ) if style_prompt is None: if len(_lowerCamelCase ): raise ValueError( F"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" F""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) SCREAMING_SNAKE_CASE : int = self.get_image_description(_lowerCamelCase ) # get prompt text embeddings for content and style SCREAMING_SNAKE_CASE : int = self.tokenizer( _lowerCamelCase , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_lowerCamelCase , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer( _lowerCamelCase , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_lowerCamelCase , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE : str = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] SCREAMING_SNAKE_CASE : Dict = slerp(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # duplicate text embeddings for each generation per prompt SCREAMING_SNAKE_CASE : int = text_embeddings.repeat_interleave(_lowerCamelCase , dim=0 ) # set timesteps SCREAMING_SNAKE_CASE : Optional[int] = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) SCREAMING_SNAKE_CASE : int = {} if accepts_offset: SCREAMING_SNAKE_CASE : List[str] = 1 self.scheduler.set_timesteps(_lowerCamelCase , **_lowerCamelCase ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.get_timesteps(_lowerCamelCase , _lowerCamelCase , self.device ) SCREAMING_SNAKE_CASE : Union[str, Any] = timesteps[:1].repeat(_lowerCamelCase ) # Preprocess image SCREAMING_SNAKE_CASE : int = preprocess(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : int = self.prepare_latents( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , text_embeddings.dtype , self.device , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = preprocess(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : str = self.prepare_latents( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , text_embeddings.dtype , self.device , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = slerp(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if clip_guidance_scale > 0: SCREAMING_SNAKE_CASE : str = self.get_clip_image_embeddings(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = self.get_clip_image_embeddings(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = slerp( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. SCREAMING_SNAKE_CASE : Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE : Optional[Any] = content_text_input.input_ids.shape[-1] SCREAMING_SNAKE_CASE : Dict = self.tokenizer([''''''] , padding='''max_length''' , max_length=_lowerCamelCase , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE : List[str] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt SCREAMING_SNAKE_CASE : str = uncond_embeddings.repeat_interleave(_lowerCamelCase , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes SCREAMING_SNAKE_CASE : List[str] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. SCREAMING_SNAKE_CASE : Tuple = (batch_size, self.unet.config.in_channels, height // 8, width // 8) SCREAMING_SNAKE_CASE : Dict = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps SCREAMING_SNAKE_CASE : Tuple = torch.randn(_lowerCamelCase , generator=_lowerCamelCase , device='''cpu''' , dtype=_lowerCamelCase ).to( self.device ) else: SCREAMING_SNAKE_CASE : str = torch.randn(_lowerCamelCase , generator=_lowerCamelCase , device=self.device , dtype=_lowerCamelCase ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) SCREAMING_SNAKE_CASE : Tuple = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE : List[str] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] SCREAMING_SNAKE_CASE : Optional[Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) SCREAMING_SNAKE_CASE : Any = {} if accepts_eta: SCREAMING_SNAKE_CASE : Optional[int] = eta # check if the scheduler accepts generator SCREAMING_SNAKE_CASE : int = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: SCREAMING_SNAKE_CASE : int = generator with self.progress_bar(total=_lowerCamelCase ): for i, t in enumerate(_lowerCamelCase ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE : Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE : Tuple = self.scheduler.scale_model_input(_lowerCamelCase , _lowerCamelCase ) # predict the noise residual SCREAMING_SNAKE_CASE : List[Any] = self.unet(_lowerCamelCase , _lowerCamelCase , encoder_hidden_states=_lowerCamelCase ).sample # perform classifier free guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: SCREAMING_SNAKE_CASE : List[Any] = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.cond_fn( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : int = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor SCREAMING_SNAKE_CASE : List[str] = 1 / 0.1_8_2_1_5 * latents SCREAMING_SNAKE_CASE : Optional[int] = self.vae.decode(_lowerCamelCase ).sample SCREAMING_SNAKE_CASE : Union[str, Any] = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : str = self.numpy_to_pil(_lowerCamelCase ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=_lowerCamelCase , nsfw_content_detected=_lowerCamelCase )
19
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = StableDiffusionSAGPipeline __SCREAMING_SNAKE_CASE : Dict = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : int = False def __lowerCAmelCase ( self ) ->Optional[int]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = 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 , ) SCREAMING_SNAKE_CASE : int = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = 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 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->str: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''prompt''': '''.''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 1.0, '''sag_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) SCREAMING_SNAKE_CASE : Tuple = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = '''.''' SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : int = output.images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : int = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = '''.''' SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : List[str] = output.images SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : str = np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : int = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : Optional[int] = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = '''.''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , width=768 , height=512 , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : List[Any] = output.images assert image.shape == (1, 512, 768, 3)
19
1
import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: SCREAMING_SNAKE_CASE : int = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: SCREAMING_SNAKE_CASE : Union[str, Any] = 4 SCREAMING_SNAKE_CASE : Tuple = 48 SCREAMING_SNAKE_CASE : Any = '''pixelshuffle_aux''' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE : int = [6, 6, 6, 6] SCREAMING_SNAKE_CASE : List[Any] = 60 SCREAMING_SNAKE_CASE : Optional[int] = [6, 6, 6, 6] SCREAMING_SNAKE_CASE : str = '''pixelshuffledirect''' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: SCREAMING_SNAKE_CASE : List[str] = 4 SCREAMING_SNAKE_CASE : Dict = '''nearest+conv''' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: SCREAMING_SNAKE_CASE : Optional[Any] = 1 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : str = 126 SCREAMING_SNAKE_CASE : str = 7 SCREAMING_SNAKE_CASE : List[str] = 255.0 SCREAMING_SNAKE_CASE : List[str] = '''''' return config def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if "patch_embed.proj" in name and "layers" not in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE : str = name.replace('''patch_embed.norm''' , '''embeddings.patch_embeddings.layernorm''' ) if "layers" in name: SCREAMING_SNAKE_CASE : Dict = name.replace('''layers''' , '''encoder.stages''' ) if "residual_group.blocks" in name: SCREAMING_SNAKE_CASE : int = name.replace('''residual_group.blocks''' , '''layers''' ) if "attn.proj" in name: SCREAMING_SNAKE_CASE : str = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: SCREAMING_SNAKE_CASE : Dict = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: SCREAMING_SNAKE_CASE : Dict = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE : str = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: SCREAMING_SNAKE_CASE : Any = name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: SCREAMING_SNAKE_CASE : Dict = name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: SCREAMING_SNAKE_CASE : int = name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''patch_embed.proj''' , '''patch_embed.projection''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE : str = '''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE : str = '''layernorm.bias''' if "conv_first" in name: SCREAMING_SNAKE_CASE : str = name.replace('''conv_first''' , '''first_convolution''' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace('''conv_last''' , '''final_convolution''' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: SCREAMING_SNAKE_CASE : Dict = name.replace('''conv_before_upsample.0''' , '''conv_before_upsample''' ) if "upsample.0" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace('''upsample.0''' , '''upsample.convolution_0''' ) if "upsample.2" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''upsample.2''' , '''upsample.convolution_1''' ) SCREAMING_SNAKE_CASE : Optional[Any] = '''upsample.''' + name elif config.upsampler == "pixelshuffledirect": SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''upsample.0.weight''' , '''upsample.conv.weight''' ) SCREAMING_SNAKE_CASE : Tuple = name.replace('''upsample.0.bias''' , '''upsample.conv.bias''' ) else: pass else: SCREAMING_SNAKE_CASE : str = '''swin2sr.''' + name return name def UpperCAmelCase_( a__ , a__ ): """simple docstring""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Tuple = orig_state_dict.pop(a__ ) if "qkv" in key: SCREAMING_SNAKE_CASE : Dict = key.split('''.''' ) SCREAMING_SNAKE_CASE : Optional[int] = int(key_split[1] ) SCREAMING_SNAKE_CASE : Optional[int] = int(key_split[4] ) SCREAMING_SNAKE_CASE : Optional[Any] = config.embed_dim if "weight" in key: SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] SCREAMING_SNAKE_CASE : List[Any] = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : Any = val[-dim:, :] else: SCREAMING_SNAKE_CASE : Any = val[:dim] SCREAMING_SNAKE_CASE : List[str] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : Union[str, Any] = val[-dim:] pass else: SCREAMING_SNAKE_CASE : int = val return orig_state_dict def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = get_config(a__ ) SCREAMING_SNAKE_CASE : List[Any] = SwinaSRForImageSuperResolution(a__ ) model.eval() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.hub.load_state_dict_from_url(a__ , map_location='''cpu''' ) SCREAMING_SNAKE_CASE : Optional[Any] = convert_state_dict(a__ , a__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = model.load_state_dict(a__ , strict=a__ ) if len(a__ ) > 0: raise ValueError('''Missing keys when converting: {}'''.format(a__ ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(F"""Unexpected key {key} in state_dict""" ) # verify values SCREAMING_SNAKE_CASE : List[str] = '''https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true''' SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(a__ , stream=a__ ).raw ).convert('''RGB''' ) SCREAMING_SNAKE_CASE : List[Any] = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values SCREAMING_SNAKE_CASE : Any = 126 if '''Jpeg''' in checkpoint_url else 256 SCREAMING_SNAKE_CASE : List[Any] = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) SCREAMING_SNAKE_CASE : Dict = transforms(a__ ).unsqueeze(0 ) if config.num_channels == 1: SCREAMING_SNAKE_CASE : Optional[Any] = pixel_values[:, 0, :, :].unsqueeze(1 ) SCREAMING_SNAKE_CASE : Optional[int] = model(a__ ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size([1, 3, 512, 512] ) SCREAMING_SNAKE_CASE : int = torch.tensor( [[-0.7_087, -0.7_138, -0.6_721], [-0.8_340, -0.8_095, -0.7_298], [-0.9_149, -0.8_414, -0.7_940]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 1_024, 1_024] ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [[-0.7_775, -0.8_105, -0.8_933], [-0.7_764, -0.8_356, -0.9_225], [-0.7_976, -0.8_686, -0.9_579]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size([1, 3, 1_024, 1_024] ) SCREAMING_SNAKE_CASE : int = torch.tensor( [[-0.8_035, -0.7_504, -0.7_491], [-0.8_538, -0.8_124, -0.7_782], [-0.8_804, -0.8_651, -0.8_493]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size([1, 3, 512, 512] ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.7_669, -0.8_662, -0.8_767], [-0.8_810, -0.9_962, -0.9_820], [-0.9_340, -1.0_322, -1.1_149]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size([1, 3, 1_024, 1_024] ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [[-0.5_238, -0.5_557, -0.6_321], [-0.6_016, -0.5_903, -0.6_391], [-0.6_244, -0.6_334, -0.6_889]] ) assert ( outputs.reconstruction.shape == expected_shape ), F"""Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}""" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , a__ , atol=1e-3 ) print('''Looks ok!''' ) SCREAMING_SNAKE_CASE : Optional[int] = { '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''': ( '''swin2SR-classical-sr-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth''': ( '''swin2SR-classical-sr-x4-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth''': ( '''swin2SR-compressed-sr-x4-48''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth''': ( '''swin2SR-lightweight-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth''': ( '''swin2SR-realworld-sr-x4-64-bsrgan-psnr''' ), } SCREAMING_SNAKE_CASE : Optional[Any] = url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(a__ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(a__ ) if push_to_hub: model.push_to_hub(F"""caidas/{model_name}""" ) processor.push_to_hub(F"""caidas/{model_name}""" ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''', type=str, help='''URL of the original Swin2SR checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the converted model to the hub.''') a__ : int = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
19
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Tuple = { '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } a__ : Optional[Any] = {'''mobilebert-uncased''': 512} a__ : List[Any] = {} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : int = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_INIT_CONFIGURATION __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Optional[int] = MobileBertTokenizer def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase="[UNK]" , _lowerCamelCase="[SEP]" , _lowerCamelCase="[PAD]" , _lowerCamelCase="[CLS]" , _lowerCamelCase="[MASK]" , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ) ->Optional[int]: super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE : Optional[int] = strip_accents SCREAMING_SNAKE_CASE : Union[str, Any] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = do_lower_case def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->Any: SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: SCREAMING_SNAKE_CASE : Any = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
19
1
from math import factorial def UpperCAmelCase_( a__ = 100 ): """simple docstring""" return sum(map(a__ , str(factorial(a__ ) ) ) ) if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
19
import math a__ : List[str] = 10 a__ : Optional[int] = 7 a__ : int = BALLS_PER_COLOUR * NUM_COLOURS def UpperCAmelCase_( a__ = 20 ): """simple docstring""" SCREAMING_SNAKE_CASE : str = math.comb(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) SCREAMING_SNAKE_CASE : Any = NUM_COLOURS * (1 - missing_colour / total) return F"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
19
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Tuple: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. SCREAMING_SNAKE_CASE : List[str] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE : str = DisjunctiveConstraint(_lowerCamelCase ) self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCAmelCase ( self ) ->int: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). SCREAMING_SNAKE_CASE : Any = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(_lowerCamelCase ) # fails here def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : str = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE : int = DisjunctiveConstraint(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = dc.update(1 ) SCREAMING_SNAKE_CASE : List[Any] = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = dc.update(2 ) SCREAMING_SNAKE_CASE : List[Any] = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = dc.update(3 ) SCREAMING_SNAKE_CASE : Union[str, Any] = stepped is True and completed is True and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE : Any = DisjunctiveConstraint(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
19
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a__ : List[str] = logging.get_logger(__name__) # General docstring a__ : Tuple = '''MobileNetV1Config''' # Base docstring a__ : Optional[Any] = '''google/mobilenet_v1_1.0_224''' a__ : Tuple = [1, 1_024, 7, 7] # Image classification docstring a__ : Optional[int] = '''google/mobilenet_v1_1.0_224''' a__ : int = '''tabby, tabby cat''' a__ : List[Any] = [ '''google/mobilenet_v1_1.0_224''', '''google/mobilenet_v1_0.75_192''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def UpperCAmelCase_( a__ , a__ , a__=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = {} if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[str] = model.mobilenet_va else: SCREAMING_SNAKE_CASE : Union[str, Any] = model SCREAMING_SNAKE_CASE : Optional[int] = '''MobilenetV1/Conv2d_0/''' SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.convolution.weight SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = backbone.conv_stem.normalization.weight SCREAMING_SNAKE_CASE : Union[str, Any] = backbone.conv_stem.normalization.running_mean SCREAMING_SNAKE_CASE : Any = backbone.conv_stem.normalization.running_var for i in range(13 ): SCREAMING_SNAKE_CASE : Dict = i + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = i * 2 SCREAMING_SNAKE_CASE : Any = backbone.layer[pt_index] SCREAMING_SNAKE_CASE : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" SCREAMING_SNAKE_CASE : Any = pointer.convolution.weight SCREAMING_SNAKE_CASE : Tuple = pointer.normalization.bias SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.running_var SCREAMING_SNAKE_CASE : List[Any] = backbone.layer[pt_index + 1] SCREAMING_SNAKE_CASE : Any = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" SCREAMING_SNAKE_CASE : Dict = pointer.convolution.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : int = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : str = pointer.normalization.running_var if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[Any] = '''MobilenetV1/Logits/Conv2d_1c_1x1/''' SCREAMING_SNAKE_CASE : List[str] = model.classifier.weight SCREAMING_SNAKE_CASE : List[str] = model.classifier.bias return tf_to_pt_map def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ''' '''https://www.tensorflow.org/install/ for installation instructions.''' ) raise # Load weights from TF model SCREAMING_SNAKE_CASE : Optional[Any] = tf.train.list_variables(a__ ) SCREAMING_SNAKE_CASE : List[Any] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) SCREAMING_SNAKE_CASE : Tuple = tf.train.load_variable(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = array # Build TF to PyTorch weights loading map SCREAMING_SNAKE_CASE : int = _build_tf_to_pytorch_map(a__ , a__ , a__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue SCREAMING_SNAKE_CASE : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('''Transposing depthwise''' ) SCREAMING_SNAKE_CASE : Tuple = np.transpose(a__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('''Transposing''' ) if len(pointer.shape ) == 2: # copying into linear layer SCREAMING_SNAKE_CASE : Union[str, Any] = array.squeeze().transpose() else: SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(a__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(a__ ) tf_weights.pop(a__ , a__ ) tf_weights.pop(name + '''/RMSProp''' , a__ ) tf_weights.pop(name + '''/RMSProp_1''' , a__ ) tf_weights.pop(name + '''/ExponentialMovingAverage''' , a__ ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = features.shape[-2:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = conv_layer.stride SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = conv_layer.kernel_size if in_height % stride_height == 0: SCREAMING_SNAKE_CASE : List[str] = max(kernel_height - stride_height , 0 ) else: SCREAMING_SNAKE_CASE : str = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: SCREAMING_SNAKE_CASE : int = max(kernel_width - stride_width , 0 ) else: SCREAMING_SNAKE_CASE : Tuple = max(kernel_width - (in_width % stride_width) , 0 ) SCREAMING_SNAKE_CASE : List[str] = pad_along_width // 2 SCREAMING_SNAKE_CASE : Any = pad_along_width - pad_left SCREAMING_SNAKE_CASE : str = pad_along_height // 2 SCREAMING_SNAKE_CASE : Optional[int] = pad_along_height - pad_top SCREAMING_SNAKE_CASE : List[Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(a__ , a__ , '''constant''' , 0.0 ) class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 1 , _lowerCamelCase = 1 , _lowerCamelCase = False , _lowerCamelCase = True , _lowerCamelCase = True , ) ->None: super().__init__() SCREAMING_SNAKE_CASE : Any = config if in_channels % groups != 0: raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) SCREAMING_SNAKE_CASE : Any = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) SCREAMING_SNAKE_CASE : List[str] = nn.Convad( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=_lowerCamelCase , stride=_lowerCamelCase , padding=_lowerCamelCase , groups=_lowerCamelCase , bias=_lowerCamelCase , padding_mode='''zeros''' , ) if use_normalization: SCREAMING_SNAKE_CASE : List[Any] = nn.BatchNormad( num_features=_lowerCamelCase , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=_lowerCamelCase , track_running_stats=_lowerCamelCase , ) else: SCREAMING_SNAKE_CASE : Dict = None if use_activation: if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Any = ACTaFN[use_activation] elif isinstance(config.hidden_act , _lowerCamelCase ): SCREAMING_SNAKE_CASE : List[str] = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : List[Any] = config.hidden_act else: SCREAMING_SNAKE_CASE : Optional[Any] = None def __lowerCAmelCase ( self , _lowerCamelCase ) ->torch.Tensor: if self.config.tf_padding: SCREAMING_SNAKE_CASE : List[Any] = apply_tf_padding(_lowerCamelCase , self.convolution ) SCREAMING_SNAKE_CASE : Dict = self.convolution(_lowerCamelCase ) if self.normalization is not None: SCREAMING_SNAKE_CASE : int = self.normalization(_lowerCamelCase ) if self.activation is not None: SCREAMING_SNAKE_CASE : List[Any] = self.activation(_lowerCamelCase ) return features class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = MobileNetVaConfig __SCREAMING_SNAKE_CASE : List[Any] = load_tf_weights_in_mobilenet_va __SCREAMING_SNAKE_CASE : int = 'mobilenet_v1' __SCREAMING_SNAKE_CASE : int = 'pixel_values' __SCREAMING_SNAKE_CASE : List[str] = False def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: if isinstance(_lowerCamelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_lowerCamelCase , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) a__ : str = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Union[str, Any] = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase = True ) ->Dict: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = config SCREAMING_SNAKE_CASE : Dict = 32 SCREAMING_SNAKE_CASE : Optional[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) SCREAMING_SNAKE_CASE : str = MobileNetVaConvLayer( _lowerCamelCase , in_channels=config.num_channels , out_channels=_lowerCamelCase , kernel_size=3 , stride=2 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] SCREAMING_SNAKE_CASE : Any = nn.ModuleList() for i in range(13 ): SCREAMING_SNAKE_CASE : int = out_channels if strides[i] == 2 or i == 0: depth *= 2 SCREAMING_SNAKE_CASE : Tuple = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=3 , stride=strides[i] , groups=_lowerCamelCase , ) ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=1 , ) ) SCREAMING_SNAKE_CASE : int = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: raise NotImplementedError @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.conv_stem(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): SCREAMING_SNAKE_CASE : Optional[int] = layer_module(_lowerCamelCase ) if output_hidden_states: SCREAMING_SNAKE_CASE : List[str] = all_hidden_states + (hidden_states,) SCREAMING_SNAKE_CASE : List[str] = hidden_states if self.pooler is not None: SCREAMING_SNAKE_CASE : Tuple = torch.flatten(self.pooler(_lowerCamelCase ) , start_dim=1 ) else: SCREAMING_SNAKE_CASE : List[Any] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_lowerCamelCase , pooler_output=_lowerCamelCase , hidden_states=_lowerCamelCase , ) @add_start_docstrings( '\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->None: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = config.num_labels SCREAMING_SNAKE_CASE : str = MobileNetVaModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head SCREAMING_SNAKE_CASE : Optional[int] = nn.Dropout(config.classifier_dropout_prob , inplace=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = nn.Linear(_lowerCamelCase , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, ImageClassifierOutputWithNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va(_lowerCamelCase , output_hidden_states=_lowerCamelCase , return_dict=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE : Tuple = self.classifier(self.dropout(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : int = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : Any = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : Optional[int] = '''single_label_classification''' else: SCREAMING_SNAKE_CASE : Dict = '''multi_label_classification''' if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Any = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : Dict = loss_fct(_lowerCamelCase , _lowerCamelCase ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : List[Any] = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : List[Any] = loss_fct(_lowerCamelCase , _lowerCamelCase ) if not return_dict: SCREAMING_SNAKE_CASE : Optional[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_lowerCamelCase , logits=_lowerCamelCase , hidden_states=outputs.hidden_states , )
19
1
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm a__ : Optional[Any] = re.compile('''[^A-Za-z_0-9]''') # parameters used in DuplicationIndex a__ : Optional[int] = 10 a__ : Dict = 256 def UpperCAmelCase_( a__ ): """simple docstring""" if len(a__ ) < MIN_NUM_TOKENS: return None SCREAMING_SNAKE_CASE : Optional[int] = MinHash(num_perm=a__ ) for token in set(a__ ): min_hash.update(token.encode() ) return min_hash def UpperCAmelCase_( a__ ): """simple docstring""" return {t for t in NON_ALPHA.split(a__ ) if len(t.strip() ) > 0} class a_ : """simple docstring""" def __init__( self , *, _lowerCamelCase = 0.8_5 , ) ->Dict: SCREAMING_SNAKE_CASE : Dict = duplication_jaccard_threshold SCREAMING_SNAKE_CASE : Union[str, Any] = NUM_PERM SCREAMING_SNAKE_CASE : Optional[Any] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) SCREAMING_SNAKE_CASE : int = defaultdict(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Dict = self._index.query(_lowerCamelCase ) if code_key in self._index.keys: print(F"""Duplicate key {code_key}""" ) return self._index.insert(_lowerCamelCase , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_lowerCamelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[List[Dict]]: SCREAMING_SNAKE_CASE : Tuple = [] for base, duplicates in self._duplicate_clusters.items(): SCREAMING_SNAKE_CASE : Optional[Any] = [base] + list(_lowerCamelCase ) # reformat the cluster to be a list of dict SCREAMING_SNAKE_CASE : Optional[Any] = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_lowerCamelCase ) return duplicate_clusters def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : List[Any] = self.get_duplicate_clusters() with open(_lowerCamelCase , '''w''' ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = element SCREAMING_SNAKE_CASE : Dict = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def UpperCAmelCase_( a__ ): """simple docstring""" with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(a__ , max_queue_size=10_000 ) , chunksize=100 , ): if data is not None: yield data def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = DuplicationIndex(duplication_jaccard_threshold=a__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a__ ) ) , max_queue_size=100 ) ): di.add(a__ , a__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = get_tokens(a__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = get_tokens(a__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) a__ : List[str] = None def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [] for elementa in cluster: SCREAMING_SNAKE_CASE : List[Any] = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: SCREAMING_SNAKE_CASE : str = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(a__ , a__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: SCREAMING_SNAKE_CASE : Optional[Any] = 1 extremes.append(a__ ) return extremes def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" global _shared_dataset SCREAMING_SNAKE_CASE : Any = dataset SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : str = partial(_find_cluster_extremes_shared , jaccard_threshold=a__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( a__ , a__ , ) , total=len(a__ ) , ): extremes_list.append(a__ ) return extremes_list def UpperCAmelCase_( a__ , a__ = 0.85 ): """simple docstring""" SCREAMING_SNAKE_CASE : str = make_duplicate_clusters(a__ , a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} SCREAMING_SNAKE_CASE : List[Any] = {} SCREAMING_SNAKE_CASE : Tuple = find_extremes(a__ , a__ , a__ ) for extremes in extremes_clusters: for element in extremes: SCREAMING_SNAKE_CASE : Optional[int] = element SCREAMING_SNAKE_CASE : int = duplicate_indices - set(extreme_dict.keys() ) SCREAMING_SNAKE_CASE : Dict = dataset.filter(lambda a__ , a__ : idx not in remove_indices , with_indices=a__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: SCREAMING_SNAKE_CASE : Optional[Any] = element['''base_index'''] in extreme_dict if element["is_extreme"]: SCREAMING_SNAKE_CASE : Union[str, Any] = extreme_dict[element['''base_index''']]['''copies'''] print(F"""Original dataset size: {len(a__ )}""" ) print(F"""Number of duplicate clusters: {len(a__ )}""" ) print(F"""Files in duplicate cluster: {len(a__ )}""" ) print(F"""Unique files in duplicate cluster: {len(a__ )}""" ) print(F"""Filtered dataset size: {len(a__ )}""" ) return ds_filter, duplicate_clusters
19
import math def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(a__ ) def UpperCAmelCase_( a__ = 1 / 12_345 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : int = 3 while True: SCREAMING_SNAKE_CASE : Union[str, Any] = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(a__ ): SCREAMING_SNAKE_CASE : List[str] = int(a__ ) total_partitions += 1 if check_partition_perfect(a__ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(a__ ) integer += 1 if __name__ == "__main__": print(F"{solution() = }")
19
1
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Tuple = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) a__ : List[Any] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class a_ : """simple docstring""" __SCREAMING_SNAKE_CASE : str = field( default=a__ , metadata={'help': 'Model type selected in the list: ' + ', '.join(a__ )} ) __SCREAMING_SNAKE_CASE : str = field( default=a__ , metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} ) __SCREAMING_SNAKE_CASE : int = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __SCREAMING_SNAKE_CASE : int = field( default=128 , metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'} , ) __SCREAMING_SNAKE_CASE : int = field( default=64 , metadata={ 'help': ( 'The maximum number of tokens for the question. Questions longer than this will ' 'be truncated to this length.' ) } , ) __SCREAMING_SNAKE_CASE : int = field( default=30 , metadata={ 'help': ( 'The maximum length of an answer that can be generated. This is needed because the start ' 'and end predictions are not conditioned on one another.' ) } , ) __SCREAMING_SNAKE_CASE : bool = field( default=a__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) __SCREAMING_SNAKE_CASE : bool = field( default=a__ , metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} ) __SCREAMING_SNAKE_CASE : float = field( default=0.0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} ) __SCREAMING_SNAKE_CASE : int = field( default=20 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} ) __SCREAMING_SNAKE_CASE : int = field( default=0 , metadata={ 'help': ( 'language id of input for language-specific xlm models (see' ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)' ) } , ) __SCREAMING_SNAKE_CASE : int = field(default=1 , metadata={'help': 'multiple threads for converting example to features'} ) class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = 'train' __SCREAMING_SNAKE_CASE : List[Any] = 'dev' class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : SquadDataTrainingArguments __SCREAMING_SNAKE_CASE : List[SquadFeatures] __SCREAMING_SNAKE_CASE : Split __SCREAMING_SNAKE_CASE : bool def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = Split.train , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = "pt" , ) ->Optional[int]: SCREAMING_SNAKE_CASE : Any = args SCREAMING_SNAKE_CASE : Tuple = is_language_sensitive SCREAMING_SNAKE_CASE : List[str] = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(_lowerCamelCase , _lowerCamelCase ): try: SCREAMING_SNAKE_CASE : Tuple = Split[mode] except KeyError: raise KeyError('''mode is not a valid split name''' ) SCREAMING_SNAKE_CASE : List[str] = mode # Load data features from cache or dataset file SCREAMING_SNAKE_CASE : int = '''v2''' if args.version_2_with_negative else '''v1''' SCREAMING_SNAKE_CASE : str = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}""" , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. SCREAMING_SNAKE_CASE : Tuple = cached_features_file + '''.lock''' with FileLock(_lowerCamelCase ): if os.path.exists(_lowerCamelCase ) and not args.overwrite_cache: SCREAMING_SNAKE_CASE : List[Any] = time.time() SCREAMING_SNAKE_CASE : Tuple = torch.load(_lowerCamelCase ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. SCREAMING_SNAKE_CASE : Union[str, Any] = self.old_features['''features'''] SCREAMING_SNAKE_CASE : Optional[int] = self.old_features.get('''dataset''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.old_features.get('''examples''' , _lowerCamelCase ) logger.info( F"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( F"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in""" ''' future run''' ) else: if mode == Split.dev: SCREAMING_SNAKE_CASE : int = self.processor.get_dev_examples(args.data_dir ) else: SCREAMING_SNAKE_CASE : int = self.processor.get_train_examples(args.data_dir ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = squad_convert_examples_to_features( examples=self.examples , tokenizer=_lowerCamelCase , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=_lowerCamelCase , ) SCREAMING_SNAKE_CASE : str = time.time() torch.save( {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples} , _lowerCamelCase , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" ) def __len__( self ) ->Dict: return len(self.features ) def __getitem__( self , _lowerCamelCase ) ->Dict[str, torch.Tensor]: # Convert to Tensors and build dataset SCREAMING_SNAKE_CASE : List[Any] = self.features[i] SCREAMING_SNAKE_CASE : List[str] = torch.tensor(feature.input_ids , dtype=torch.long ) SCREAMING_SNAKE_CASE : str = torch.tensor(feature.attention_mask , dtype=torch.long ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor(feature.token_type_ids , dtype=torch.long ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(feature.cls_index , dtype=torch.long ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor(feature.p_mask , dtype=torch.float ) SCREAMING_SNAKE_CASE : Dict = torch.tensor(feature.is_impossible , dtype=torch.float ) SCREAMING_SNAKE_CASE : Any = { '''input_ids''': input_ids, '''attention_mask''': attention_mask, '''token_type_ids''': token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask} ) if self.args.version_2_with_negative: inputs.update({'''is_impossible''': is_impossible} ) if self.is_language_sensitive: inputs.update({'''langs''': (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: SCREAMING_SNAKE_CASE : List[str] = torch.tensor(feature.start_position , dtype=torch.long ) SCREAMING_SNAKE_CASE : str = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions} ) return inputs
19
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar a__ : Any = TypeVar('''T''') def UpperCAmelCase_( a__ ): """simple docstring""" return (position - 1) // 2 def UpperCAmelCase_( a__ ): """simple docstring""" return (2 * position) + 1 def UpperCAmelCase_( a__ ): """simple docstring""" return (2 * position) + 2 class a_ ( Generic[T] ): """simple docstring""" def __init__( self ) ->None: SCREAMING_SNAKE_CASE : list[tuple[T, int]] = [] SCREAMING_SNAKE_CASE : dict[T, int] = {} SCREAMING_SNAKE_CASE : int = 0 def __len__( self ) ->int: return self.elements def __repr__( self ) ->str: return str(self.heap ) def __lowerCAmelCase ( self ) ->bool: # Check if the priority queue is empty return self.elements == 0 def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) SCREAMING_SNAKE_CASE : Tuple = self.elements self.elements += 1 self._bubble_up(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.heap[0] self._bubble_down(_lowerCamelCase ) return elem def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Update the weight of the given key SCREAMING_SNAKE_CASE : List[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE : Any = (elem, weight) if position > 0: SCREAMING_SNAKE_CASE : List[Any] = get_parent_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._bubble_up(_lowerCamelCase ) else: self._bubble_down(_lowerCamelCase ) else: self._bubble_down(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Place a node at the proper position (upward movement) [to be used internally # only] SCREAMING_SNAKE_CASE : Optional[Any] = self.position_map[elem] if curr_pos == 0: return None SCREAMING_SNAKE_CASE : str = get_parent_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.heap[curr_pos] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_up(_lowerCamelCase ) return None def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Place a node at the proper position (downward movement) [to be used # internally only] SCREAMING_SNAKE_CASE : Optional[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.heap[curr_pos] SCREAMING_SNAKE_CASE : List[str] = get_child_left_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = get_child_right_position(_lowerCamelCase ) if child_left_position < self.elements and child_right_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.heap[child_left_position] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) if child_left_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) else: return None if child_right_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) return None def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Swap the nodes at the given positions SCREAMING_SNAKE_CASE : Optional[int] = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE : Any = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) SCREAMING_SNAKE_CASE : Optional[int] = nodea_pos SCREAMING_SNAKE_CASE : List[str] = nodea_pos class a_ ( Generic[T] ): """simple docstring""" def __init__( self ) ->None: SCREAMING_SNAKE_CASE : dict[T, dict[T, int]] = {} SCREAMING_SNAKE_CASE : int = 0 def __repr__( self ) ->str: return str(self.connections ) def __len__( self ) ->int: return self.nodes def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Add a node in the graph if it is not in the graph if node not in self.connections: SCREAMING_SNAKE_CASE : Any = {} self.nodes += 1 def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->None: # Add an edge between 2 nodes in the graph self.add_node(_lowerCamelCase ) self.add_node(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = weight SCREAMING_SNAKE_CASE : str = weight def UpperCAmelCase_( a__ , ): """simple docstring""" SCREAMING_SNAKE_CASE : dict[T, int] = {node: maxsize for node in graph.connections} SCREAMING_SNAKE_CASE : dict[T, T | None] = {node: None for node in graph.connections} SCREAMING_SNAKE_CASE : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(a__ , a__ ) if priority_queue.is_empty(): return dist, parent # initialization SCREAMING_SNAKE_CASE : List[Any] = priority_queue.extract_min() SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE : Any = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) SCREAMING_SNAKE_CASE : str = node # running prim's algorithm while not priority_queue.is_empty(): SCREAMING_SNAKE_CASE : List[str] = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE : List[Any] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) SCREAMING_SNAKE_CASE : str = node return dist, parent
19
1
from cva import destroyAllWindows, imread, imshow, waitKey def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(a__ ): for j in range(a__ ): SCREAMING_SNAKE_CASE : Any = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image a__ : Tuple = imread('''image_data/lena.jpg''', 1) # convert to its negative a__ : Any = convert_to_negative(img) # show result image imshow('''negative of original image''', img) waitKey(0) destroyAllWindows()
19
from math import pi, sqrt, tan def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''surface_area_cube() only accepts non-negative values''' ) return 6 * side_length**2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if length < 0 or breadth < 0 or height < 0: raise ValueError('''surface_area_cuboid() only accepts non-negative values''' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_sphere() only accepts non-negative values''' ) return 4 * pi * radius**2 def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' ) return 3 * pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cone() only accepts non-negative values''' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( '''surface_area_conical_frustum() only accepts non-negative values''' ) SCREAMING_SNAKE_CASE : Optional[Any] = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cylinder() only accepts non-negative values''' ) return 2 * pi * radius * (height + radius) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if torus_radius < 0 or tube_radius < 0: raise ValueError('''surface_area_torus() only accepts non-negative values''' ) if torus_radius < tube_radius: raise ValueError( '''surface_area_torus() does not support spindle or self intersecting tori''' ) return 4 * pow(a__ , 2 ) * torus_radius * tube_radius def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if length < 0 or width < 0: raise ValueError('''area_rectangle() only accepts non-negative values''' ) return length * width def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''area_square() only accepts non-negative values''' ) return side_length**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_triangle() only accepts non-negative values''' ) return (base * height) / 2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('''Given three sides do not form a triangle''' ) SCREAMING_SNAKE_CASE : int = (sidea + sidea + sidea) / 2 SCREAMING_SNAKE_CASE : List[str] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_parallelogram() only accepts non-negative values''' ) return base * height def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if basea < 0 or basea < 0 or height < 0: raise ValueError('''area_trapezium() only accepts non-negative values''' ) return 1 / 2 * (basea + basea) * height def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''area_circle() only accepts non-negative values''' ) return pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius_x < 0 or radius_y < 0: raise ValueError('''area_ellipse() only accepts non-negative values''' ) return pi * radius_x * radius_y def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if diagonal_a < 0 or diagonal_a < 0: raise ValueError('''area_rhombus() only accepts non-negative values''' ) return 1 / 2 * diagonal_a * diagonal_a def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if not isinstance(a__ , a__ ) or sides < 3: raise ValueError( '''area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides''' ) elif length < 0: raise ValueError( '''area_reg_polygon() only accepts non-negative values as \ length of a side''' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('''[DEMO] Areas of various geometric shapes: \n''') print(F"Rectangle: {area_rectangle(10, 20) = }") print(F"Square: {area_square(10) = }") print(F"Triangle: {area_triangle(10, 10) = }") print(F"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(F"Parallelogram: {area_parallelogram(10, 20) = }") print(F"Rhombus: {area_rhombus(10, 20) = }") print(F"Trapezium: {area_trapezium(10, 20, 30) = }") print(F"Circle: {area_circle(20) = }") print(F"Ellipse: {area_ellipse(10, 20) = }") print('''\nSurface Areas of various geometric shapes: \n''') print(F"Cube: {surface_area_cube(20) = }") print(F"Cuboid: {surface_area_cuboid(10, 20, 30) = }") print(F"Sphere: {surface_area_sphere(20) = }") print(F"Hemisphere: {surface_area_hemisphere(20) = }") print(F"Cone: {surface_area_cone(10, 20) = }") print(F"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") print(F"Cylinder: {surface_area_cylinder(10, 20) = }") print(F"Torus: {surface_area_torus(20, 10) = }") print(F"Equilateral Triangle: {area_reg_polygon(3, 10) = }") print(F"Square: {area_reg_polygon(4, 10) = }") print(F"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
19
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Optional[Any] = { '''configuration_blenderbot''': [ '''BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlenderbotConfig''', '''BlenderbotOnnxConfig''', ], '''tokenization_blenderbot''': ['''BlenderbotTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = ['''BlenderbotTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = [ '''BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlenderbotForCausalLM''', '''BlenderbotForConditionalGeneration''', '''BlenderbotModel''', '''BlenderbotPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = [ '''TFBlenderbotForConditionalGeneration''', '''TFBlenderbotModel''', '''TFBlenderbotPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = [ '''FlaxBlenderbotForConditionalGeneration''', '''FlaxBlenderbotModel''', '''FlaxBlenderbotPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys a__ : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: a__ : List[str] = None a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Dict = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/mbart-large-en-ro''': '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json''', '''facebook/mbart-large-cc25''': '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json''', }, } a__ : str = { '''facebook/mbart-large-en-ro''': 1_024, '''facebook/mbart-large-cc25''': 1_024, } # fmt: off a__ : List[str] = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = ['input_ids', 'attention_mask'] __SCREAMING_SNAKE_CASE : Tuple = MBartTokenizer __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase , ) ->List[Any]: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : List[str] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token super().__init__( vocab_file=_lowerCamelCase , tokenizer_file=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , src_lang=_lowerCamelCase , tgt_lang=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Any = vocab_file SCREAMING_SNAKE_CASE : List[Any] = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : Any = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) SCREAMING_SNAKE_CASE : int = { lang_code: self.convert_tokens_to_ids(_lowerCamelCase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE : List[str] = src_lang if src_lang is not None else '''en_XX''' SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __lowerCAmelCase ( self ) ->str: return self._src_lang @src_lang.setter def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[int] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : str = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) ->Optional[Any]: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[str] = self(_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang_id return inputs def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = "en_XX" , _lowerCamelCase = None , _lowerCamelCase = "ro_RO" , **_lowerCamelCase , ) ->BatchEncoding: SCREAMING_SNAKE_CASE : List[str] = src_lang SCREAMING_SNAKE_CASE : List[str] = tgt_lang return super().prepare_seqaseq_batch(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Dict: return self.set_src_lang_special_tokens(self.src_lang ) def __lowerCAmelCase ( self ) ->List[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : str = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Any = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file , _lowerCamelCase ) return (out_vocab_file,)
19
1
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 UpperCAmelCase_( a__ ): """simple docstring""" return (data["data"], data["target"]) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = XGBClassifier() classifier.fit(a__ , a__ ) return classifier def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = load_iris() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = data_handling(a__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = train_test_split( a__ , a__ , test_size=0.25 ) SCREAMING_SNAKE_CASE : List[Any] = iris['''target_names'''] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE : List[str] = xgboost(a__ , a__ ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( a__ , a__ , a__ , display_labels=a__ , cmap='''Blues''' , normalize='''true''' , ) plt.title('''Normalized Confusion Matrix - IRIS Dataset''' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
19
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging a__ : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=768 ) ->List[Any]: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = proj_size SCREAMING_SNAKE_CASE : Any = CLIPVisionModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = PaintByExampleMapper(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = nn.LayerNorm(config.hidden_size ) SCREAMING_SNAKE_CASE : int = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=False ) ->int: SCREAMING_SNAKE_CASE : Optional[Any] = self.model(pixel_values=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = clip_output.pooler_output SCREAMING_SNAKE_CASE : Optional[Any] = self.mapper(latent_states[:, None] ) SCREAMING_SNAKE_CASE : Tuple = self.final_layer_norm(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.proj_out(_lowerCamelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->List[str]: super().__init__() SCREAMING_SNAKE_CASE : str = (config.num_hidden_layers + 1) // 5 SCREAMING_SNAKE_CASE : List[Any] = config.hidden_size SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : Optional[Any] = nn.ModuleList( [ BasicTransformerBlock(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , activation_fn='''gelu''' , attention_bias=_lowerCamelCase ) for _ in range(_lowerCamelCase ) ] ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: for block in self.blocks: SCREAMING_SNAKE_CASE : Optional[int] = block(_lowerCamelCase ) return hidden_states
19
1
from PIL import Image def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = image.size SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Optional[Any] = image.load() for i in range(a__ ): for j in range(a__ ): SCREAMING_SNAKE_CASE : str = pixels[j, i] mean += pixel mean //= width * height for j in range(a__ ): for i in range(a__ ): SCREAMING_SNAKE_CASE : Any = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": a__ : List[str] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
19
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 a__ : Tuple = '''▁''' a__ : List[Any] = {'''vocab_file''': '''spiece.model'''} a__ : Optional[Any] = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } a__ : str = { '''google/pegasus-xsum''': 512, } a__ : str = logging.get_logger(__name__) class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : str = ['input_ids', 'attention_mask'] def __init__( self , _lowerCamelCase , _lowerCamelCase="<pad>" , _lowerCamelCase="</s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<mask_2>" , _lowerCamelCase="<mask_1>" , _lowerCamelCase=None , _lowerCamelCase=103 , _lowerCamelCase = None , **_lowerCamelCase , ) ->None: SCREAMING_SNAKE_CASE : Dict = offset if additional_special_tokens is not None: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError( F"""additional_special_tokens should be of type {type(_lowerCamelCase )}, but is""" F""" {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : List[Any] = ( ([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(_lowerCamelCase ) , self.offset - 1 ) ] if len(set(_lowerCamelCase ) ) != len(_lowerCamelCase ): 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}.""" ) SCREAMING_SNAKE_CASE : Dict = additional_special_tokens_extended else: SCREAMING_SNAKE_CASE : str = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F"""<unk_{i}>""" for i in range(2 , self.offset )] SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , mask_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token_sent=_lowerCamelCase , offset=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[str] = mask_token_sent SCREAMING_SNAKE_CASE : Optional[int] = vocab_file SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) # add special tokens to encoder dict SCREAMING_SNAKE_CASE : Dict[int, str] = { 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 )} ) SCREAMING_SNAKE_CASE : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def __lowerCAmelCase ( self ) ->int: return len(self.sp_model ) + self.offset def __lowerCAmelCase ( self ) ->Dict[str, int]: SCREAMING_SNAKE_CASE : Union[str, Any] = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = self.__dict__.copy() SCREAMING_SNAKE_CASE : str = None return state def __setstate__( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : List[str] = {} SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.piece_to_id(_lowerCamelCase ) return sp_id + self.offset def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: SCREAMING_SNAKE_CASE : Dict = self.sp_model.IdToPiece(index - self.offset ) return token def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : int = '''''' 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(_lowerCamelCase ) + token SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(_lowerCamelCase ) out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def __lowerCAmelCase ( self , _lowerCamelCase=False ) ->str: return 1 def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Dict = 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ) ->List[int]: if already_has_special_tokens: return self._special_token_mask(_lowerCamelCase ) elif token_ids_a is None: return self._special_token_mask(_lowerCamelCase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->List[int]: 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : int = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE : Tuple = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
19
1
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def UpperCAmelCase_( a__ ): """simple docstring""" return {key.lstrip('''-''' ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = ArgumentParser( '''HuggingFace Datasets CLI tool''' , usage='''datasets-cli <command> [<args>]''' , allow_abbrev=a__ ) SCREAMING_SNAKE_CASE : Tuple = parser.add_subparsers(help='''datasets-cli command helpers''' ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(a__ ) EnvironmentCommand.register_subcommand(a__ ) TestCommand.register_subcommand(a__ ) RunBeamCommand.register_subcommand(a__ ) DummyDataCommand.register_subcommand(a__ ) # Parse args SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = parser.parse_known_args() if not hasattr(a__ , '''func''' ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE : int = parse_unknown_args(a__ ) # Run SCREAMING_SNAKE_CASE : Optional[Any] = args.func(a__ , **a__ ) service.run() if __name__ == "__main__": main()
19
def UpperCAmelCase_( a__ ): """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Tuple = 1 while repunit: SCREAMING_SNAKE_CASE : Dict = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def UpperCAmelCase_( a__ = 1_000_000 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(a__ ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F"{solution() = }")
19
1
def UpperCAmelCase_( a__ ): """simple docstring""" assert ( isinstance(a__ , a__ ) and number_of_steps > 0 ), F"""number_of_steps needs to be positive integer, your input {number_of_steps}""" if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
19
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=32 , _lowerCamelCase=3 , _lowerCamelCase=4 , _lowerCamelCase=[10, 20, 30, 40] , _lowerCamelCase=[2, 2, 3, 2] , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=10 , _lowerCamelCase=0.0_2 , _lowerCamelCase=["stage2", "stage3", "stage4"] , _lowerCamelCase=3 , _lowerCamelCase=None , ) ->Dict: SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Optional[Any] = batch_size SCREAMING_SNAKE_CASE : Optional[Any] = image_size SCREAMING_SNAKE_CASE : str = num_channels SCREAMING_SNAKE_CASE : Any = num_stages SCREAMING_SNAKE_CASE : List[str] = hidden_sizes SCREAMING_SNAKE_CASE : Optional[Any] = depths SCREAMING_SNAKE_CASE : Any = is_training SCREAMING_SNAKE_CASE : Tuple = use_labels SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : int = out_features SCREAMING_SNAKE_CASE : List[str] = num_labels SCREAMING_SNAKE_CASE : int = scope SCREAMING_SNAKE_CASE : Optional[Any] = num_stages def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : str = None if self.use_labels: SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) ->List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def __lowerCAmelCase ( self ) ->Any: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_lowerCamelCase , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_lowerCamelCase , loss_ignore_index=255 , num_labels=self.num_labels , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : List[Any] = UperNetForSemanticSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = (UperNetForSemanticSegmentation,) if is_torch_available() else () __SCREAMING_SNAKE_CASE : List[str] = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {} __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Union[str, Any] = False __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : Any = False def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[Any] = UperNetModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def __lowerCAmelCase ( self ) ->str: 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 __lowerCAmelCase ( self ) ->str: return def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Optional[int] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase ) @unittest.skip(reason='''UperNet does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) ->Union[str, Any]: pass @unittest.skip(reason='''UperNet does not support input and output embeddings''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->str: pass @require_torch_multi_gpu @unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def __lowerCAmelCase ( self ) ->str: pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowerCAmelCase ( self ) ->Tuple: pass def __lowerCAmelCase ( self ) ->int: def check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) SCREAMING_SNAKE_CASE : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # ConvNext'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] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Union[str, Any] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : str = _config_zero_init(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip(reason='''UperNet does not have tied weights''' ) def __lowerCAmelCase ( self ) ->List[Any]: pass @slow def __lowerCAmelCase ( self ) ->List[Any]: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Any = UperNetForSemanticSegmentation.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = hf_hub_download( repo_id='''hf-internal-testing/fixtures_ade20k''' , repo_type='''dataset''' , filename='''ADE_val_00000001.jpg''' ) SCREAMING_SNAKE_CASE : Any = Image.open(a__ ).convert('''RGB''' ) return image @require_torch @require_vision @slow class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny''' ) SCREAMING_SNAKE_CASE : Tuple = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny''' ) SCREAMING_SNAKE_CASE : str = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) )
19
1
import random def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = num - 1 SCREAMING_SNAKE_CASE : Any = 0 while s % 2 == 0: SCREAMING_SNAKE_CASE : Any = s // 2 t += 1 for _ in range(5 ): SCREAMING_SNAKE_CASE : List[str] = random.randrange(2 , num - 1 ) SCREAMING_SNAKE_CASE : Tuple = pow(a__ , a__ , a__ ) if v != 1: SCREAMING_SNAKE_CASE : Optional[Any] = 0 while v != (num - 1): if i == t - 1: return False else: SCREAMING_SNAKE_CASE : Tuple = i + 1 SCREAMING_SNAKE_CASE : Optional[int] = (v**2) % num return True def UpperCAmelCase_( a__ ): """simple docstring""" if num < 2: return False SCREAMING_SNAKE_CASE : Union[str, Any] = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(a__ ) def UpperCAmelCase_( a__ = 1_024 ): """simple docstring""" while True: SCREAMING_SNAKE_CASE : Union[str, Any] = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(a__ ): return num if __name__ == "__main__": a__ : Any = generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
19
import datasets from .evaluate import evaluate a__ : Dict = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' a__ : List[str] = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' a__ : List[Any] = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric("cuad") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': { '''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.features.Sequence(datasets.Value('''string''' ) ), }, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://www.atticusprojectai.org/cuad'''] , reference_urls=['''https://www.atticusprojectai.org/cuad'''] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Any = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} SCREAMING_SNAKE_CASE : int = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] SCREAMING_SNAKE_CASE : Dict = evaluate(dataset=_lowerCamelCase , predictions=_lowerCamelCase ) return score
19
1
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging a__ : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) ->Union[str, Any]: super().__init__() if hasattr(scheduler.config , '''steps_offset''' ) and scheduler.config.steps_offset != 1: SCREAMING_SNAKE_CASE : str = ( F"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" F""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ '''to update the config accordingly as leaving `steps_offset` might led to incorrect results''' ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,''' ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`''' ''' file''' ) deprecate('''steps_offset!=1''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = dict(scheduler.config ) SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : Any = FrozenDict(_lowerCamelCase ) if hasattr(scheduler.config , '''skip_prk_steps''' ) and scheduler.config.skip_prk_steps is False: SCREAMING_SNAKE_CASE : Tuple = ( F"""The configuration file of this scheduler: {scheduler} has not set the configuration""" ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make''' ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to''' ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face''' ''' Hub, it would be very nice if you could open a Pull request for the''' ''' `scheduler/scheduler_config.json` file''' ) deprecate('''skip_prk_steps not set''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = dict(scheduler.config ) SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : str = FrozenDict(_lowerCamelCase ) if safety_checker is None: logger.warning( F"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( segmentation_model=_lowerCamelCase , segmentation_processor=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , unet=_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase , feature_extractor=_lowerCamelCase , ) def __lowerCAmelCase ( self , _lowerCamelCase = "auto" ) ->Dict: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE : List[Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[int]: self.enable_attention_slicing(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[str]: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) SCREAMING_SNAKE_CASE : List[Any] = torch.device('''cuda''' ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(_lowerCamelCase , _lowerCamelCase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self ) ->Union[str, Any]: if self.device != torch.device('''meta''' ) or not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(_lowerCamelCase , '''_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() def __call__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 512 , _lowerCamelCase = 512 , _lowerCamelCase = 50 , _lowerCamelCase = 7.5 , _lowerCamelCase = None , _lowerCamelCase = 1 , _lowerCamelCase = 0.0 , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = "pil" , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = 1 , **_lowerCamelCase , ) ->Optional[int]: SCREAMING_SNAKE_CASE : Dict = self.segmentation_processor( text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''' ).to(self.device ) SCREAMING_SNAKE_CASE : Optional[Any] = self.segmentation_model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() SCREAMING_SNAKE_CASE : List[Any] = self.numpy_to_pil(_lowerCamelCase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=_lowerCamelCase , image=_lowerCamelCase , mask_image=_lowerCamelCase , height=_lowerCamelCase , width=_lowerCamelCase , num_inference_steps=_lowerCamelCase , guidance_scale=_lowerCamelCase , negative_prompt=_lowerCamelCase , num_images_per_prompt=_lowerCamelCase , eta=_lowerCamelCase , generator=_lowerCamelCase , latents=_lowerCamelCase , output_type=_lowerCamelCase , return_dict=_lowerCamelCase , callback=_lowerCamelCase , callback_steps=_lowerCamelCase , )
19
from sklearn.metrics import matthews_corrcoef import datasets a__ : Optional[Any] = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' a__ : str = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' a__ : Union[str, Any] = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ) ->List[str]: return { "matthews_correlation": float(matthews_corrcoef(_lowerCamelCase , _lowerCamelCase , sample_weight=_lowerCamelCase ) ), }
19
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Tuple = { '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } a__ : Optional[Any] = {'''mobilebert-uncased''': 512} a__ : List[Any] = {} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : int = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_INIT_CONFIGURATION __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Optional[int] = MobileBertTokenizer def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase="[UNK]" , _lowerCamelCase="[SEP]" , _lowerCamelCase="[PAD]" , _lowerCamelCase="[CLS]" , _lowerCamelCase="[MASK]" , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ) ->Optional[int]: super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE : Optional[int] = strip_accents SCREAMING_SNAKE_CASE : Union[str, Any] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = do_lower_case def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->Any: SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: SCREAMING_SNAKE_CASE : Any = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
19
# Copyright 2021 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 argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=a__ ) SCREAMING_SNAKE_CASE : int = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=a__ ) env_command_parser(subparsers=a__ ) launch_command_parser(subparsers=a__ ) tpu_command_parser(subparsers=a__ ) test_command_parser(subparsers=a__ ) # Let's go SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() if not hasattr(a__ , '''func''' ): parser.print_help() exit(1 ) # Run args.func(a__ ) if __name__ == "__main__": main()
19
1
a__ : Dict = [ '''Audio''', '''Array2D''', '''Array3D''', '''Array4D''', '''Array5D''', '''ClassLabel''', '''Features''', '''Sequence''', '''Value''', '''Image''', '''Translation''', '''TranslationVariableLanguages''', ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
19
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Optional[Any] = {'''vocab_file''': '''vocab.json'''} a__ : str = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } a__ : Tuple = {'''mgp-str''': 27} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _lowerCamelCase , _lowerCamelCase="[GO]" , _lowerCamelCase="[GO]" , _lowerCamelCase="[s]" , _lowerCamelCase="[GO]" , **_lowerCamelCase ) ->Dict: super().__init__( unk_token=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , pad_token=_lowerCamelCase , **_lowerCamelCase , ) with open(_lowerCamelCase , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE : List[Any] = json.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.vocab.items()} @property def __lowerCAmelCase ( self ) ->List[Any]: return len(self.vocab ) def __lowerCAmelCase ( self ) ->Union[str, Any]: return dict(self.vocab , **self.added_tokens_encoder ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Union[str, Any] = [] for s in text: char_tokens.extend(_lowerCamelCase ) return char_tokens def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: return self.vocab.get(_lowerCamelCase , self.vocab.get(self.unk_token ) ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: return self.decoder.get(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(_lowerCamelCase ) ) return SCREAMING_SNAKE_CASE : str = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=_lowerCamelCase , ensure_ascii=_lowerCamelCase ) + '''\n''' ) return (vocab_file,)
19
1
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast a__ : Optional[int] = datasets.utils.logging.get_logger(__name__) @dataclass class a_ ( datasets.BuilderConfig ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = 1_0000 __SCREAMING_SNAKE_CASE : Optional[List[str]] = None __SCREAMING_SNAKE_CASE : Optional[datasets.Features] = None class a_ ( datasets.ArrowBasedBuilder ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = ParquetConfig def __lowerCAmelCase ( self ) ->Any: return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[Any]: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) SCREAMING_SNAKE_CASE : Tuple = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCamelCase , (str, list, tuple) ): SCREAMING_SNAKE_CASE : str = data_files if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Optional[int] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive SCREAMING_SNAKE_CASE : Optional[int] = [dl_manager.iter_files(_lowerCamelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] SCREAMING_SNAKE_CASE : Dict = [] for split_name, files in data_files.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : str = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive SCREAMING_SNAKE_CASE : Optional[Any] = [dl_manager.iter_files(_lowerCamelCase ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(_lowerCamelCase ): with open(_lowerCamelCase , '''rb''' ) as f: SCREAMING_SNAKE_CASE : int = datasets.Features.from_arrow_schema(pq.read_schema(_lowerCamelCase ) ) break splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , _lowerCamelCase ) ->pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example SCREAMING_SNAKE_CASE : List[str] = table_cast(_lowerCamelCase , self.info.features.arrow_schema ) return pa_table def __lowerCAmelCase ( self , _lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : Dict = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'""" ) for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ): with open(_lowerCamelCase , '''rb''' ) as f: SCREAMING_SNAKE_CASE : Tuple = pq.ParquetFile(_lowerCamelCase ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): SCREAMING_SNAKE_CASE : int = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"""{file_idx}_{batch_idx}""", self._cast_table(_lowerCamelCase ) except ValueError as e: logger.error(F"""Failed to read file '{file}' with error {type(_lowerCamelCase )}: {e}""" ) raise
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a__ : Optional[Any] = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['''DeiTFeatureExtractor'''] a__ : Any = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ '''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 a__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = StableDiffusionPanoramaPipeline __SCREAMING_SNAKE_CASE : List[Any] = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : str = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_IMAGE_PARAMS def __lowerCAmelCase ( self ) ->Dict: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler() torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = 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 , ) SCREAMING_SNAKE_CASE : Tuple = CLIPTextModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE : List[str] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->List[str]: SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, # Setting height and width to None to prevent OOMs on CPU. '''height''': None, '''width''': None, '''num_inference_steps''': 1, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[str] = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = sd_pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Any: super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self ) ->Tuple: super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25e-3 ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = '''french fries''' SCREAMING_SNAKE_CASE : int = sd_pipe(**_lowerCamelCase , negative_prompt=_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : str = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Optional[int] = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe(**_lowerCamelCase , view_batch_size=2 ) SCREAMING_SNAKE_CASE : Optional[int] = output.images SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : int = self.get_dummy_components() SCREAMING_SNAKE_CASE : int = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' ) SCREAMING_SNAKE_CASE : int = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = sd_pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , skip_prk_steps=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self , _lowerCamelCase=0 ) ->Tuple: SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : List[str] = '''stabilityai/stable-diffusion-2-base''' SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder='''scheduler''' ) SCREAMING_SNAKE_CASE : Any = StableDiffusionPanoramaPipeline.from_pretrained(_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : List[str] = self.get_inputs() SCREAMING_SNAKE_CASE : Any = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) SCREAMING_SNAKE_CASE : List[str] = np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[int] = StableDiffusionPanoramaPipeline.from_pretrained( '''stabilityai/stable-diffusion-2-base''' , safety_checker=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : str = self.get_inputs() SCREAMING_SNAKE_CASE : List[Any] = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) SCREAMING_SNAKE_CASE : List[str] = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = 0 def callback_fn(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> None: SCREAMING_SNAKE_CASE : str = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE : Dict = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) SCREAMING_SNAKE_CASE : int = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Optional[int] = np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE : int = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) SCREAMING_SNAKE_CASE : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Union[str, Any] = np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE : Optional[int] = False SCREAMING_SNAKE_CASE : Tuple = '''stabilityai/stable-diffusion-2-base''' SCREAMING_SNAKE_CASE : str = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder='''scheduler''' ) SCREAMING_SNAKE_CASE : List[Any] = StableDiffusionPanoramaPipeline.from_pretrained(_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : int = self.get_inputs() pipe(**_lowerCamelCase , callback=_lowerCamelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowerCAmelCase ( self ) ->Dict: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE : Tuple = '''stabilityai/stable-diffusion-2-base''' SCREAMING_SNAKE_CASE : List[str] = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder='''scheduler''' ) SCREAMING_SNAKE_CASE : int = StableDiffusionPanoramaPipeline.from_pretrained(_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE : int = self.get_inputs() SCREAMING_SNAKE_CASE : Tuple = pipe(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''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 a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
19
1
import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = DanceDiffusionPipeline __SCREAMING_SNAKE_CASE : Optional[int] = UNCONDITIONAL_AUDIO_GENERATION_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = PipelineTesterMixin.required_optional_params - { 'callback', 'latents', 'callback_steps', 'output_type', 'num_images_per_prompt', } __SCREAMING_SNAKE_CASE : Tuple = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : int = False def __lowerCAmelCase ( self ) ->Optional[int]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = UNetaDModel( block_out_channels=(32, 32, 64) , extra_in_channels=16 , sample_size=512 , sample_rate=1_6000 , in_channels=2 , out_channels=2 , flip_sin_to_cos=_lowerCamelCase , use_timestep_embedding=_lowerCamelCase , time_embedding_type='''fourier''' , mid_block_type='''UNetMidBlock1D''' , down_block_types=('''DownBlock1DNoSkip''', '''DownBlock1D''', '''AttnDownBlock1D''') , up_block_types=('''AttnUpBlock1D''', '''UpBlock1D''', '''UpBlock1DNoSkip''') , ) SCREAMING_SNAKE_CASE : Optional[int] = IPNDMScheduler() SCREAMING_SNAKE_CASE : Optional[int] = { '''unet''': unet, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->Optional[int]: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 4, } return inputs def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[Any] = DanceDiffusionPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = pipe(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = output.audios SCREAMING_SNAKE_CASE : Optional[Any] = audio[0, -3:, -3:] assert audio.shape == (1, 2, components["unet"].sample_size) SCREAMING_SNAKE_CASE : Optional[int] = np.array([-0.7_2_6_5, 1.0_0_0_0, -0.8_3_8_8, 0.1_1_7_5, 0.9_4_9_8, -1.0_0_0_0] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def __lowerCAmelCase ( self ) ->List[str]: return super().test_save_load_local() @skip_mps def __lowerCAmelCase ( self ) ->Optional[Any]: return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) @skip_mps def __lowerCAmelCase ( self ) ->Dict: return super().test_save_load_optional_components() @skip_mps def __lowerCAmelCase ( self ) ->Any: return super().test_attention_slicing_forward_pass() def __lowerCAmelCase ( self ) ->List[str]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Tuple = torch_device SCREAMING_SNAKE_CASE : Optional[Any] = DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k''' ) SCREAMING_SNAKE_CASE : int = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = pipe(generator=_lowerCamelCase , num_inference_steps=100 , audio_length_in_s=4.0_9_6 ) SCREAMING_SNAKE_CASE : List[str] = output.audios SCREAMING_SNAKE_CASE : Union[str, Any] = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) SCREAMING_SNAKE_CASE : Optional[int] = np.array([-0.0_1_9_2, -0.0_2_3_1, -0.0_3_1_8, -0.0_0_5_9, 0.0_0_0_2, -0.0_0_2_0] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Tuple = torch_device SCREAMING_SNAKE_CASE : Optional[Any] = DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Tuple = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe(generator=_lowerCamelCase , num_inference_steps=100 , audio_length_in_s=4.0_9_6 ) SCREAMING_SNAKE_CASE : List[Any] = output.audios SCREAMING_SNAKE_CASE : Optional[Any] = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) SCREAMING_SNAKE_CASE : List[Any] = np.array([-0.0_3_6_7, -0.0_4_8_8, -0.0_7_7_1, -0.0_5_2_5, -0.0_4_4_4, -0.0_3_4_1] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2
19
import math from collections.abc import Iterator from itertools import takewhile def UpperCAmelCase_( a__ ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : str = 2 while True: if is_prime(a__ ): yield num num += 1 def UpperCAmelCase_( a__ = 2_000_000 ): """simple docstring""" return sum(takewhile(lambda a__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"{solution() = }")
19
1
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration a__ : Optional[Any] = [ # tf -> hf ('''/''', '''.'''), ('''layer_''', '''layers.'''), ('''kernel''', '''weight'''), ('''beta''', '''bias'''), ('''gamma''', '''weight'''), ('''pegasus''', '''model'''), ] a__ : Union[str, Any] = [ ('''.output.dense''', '''.fc2'''), ('''intermediate.LayerNorm''', '''final_layer_norm'''), ('''intermediate.dense''', '''fc1'''), ] a__ : Optional[int] = ( INIT_COMMON + [ ('''attention.self.LayerNorm''', '''self_attn_layer_norm'''), ('''attention.output.dense''', '''self_attn.out_proj'''), ('''attention.self''', '''self_attn'''), ('''attention.encdec.LayerNorm''', '''encoder_attn_layer_norm'''), ('''attention.encdec_output.dense''', '''encoder_attn.out_proj'''), ('''attention.encdec''', '''encoder_attn'''), ('''key''', '''k_proj'''), ('''value''', '''v_proj'''), ('''query''', '''q_proj'''), ('''decoder.LayerNorm''', '''decoder.layernorm_embedding'''), ] + END_COMMON ) a__ : Any = ( INIT_COMMON + [ ('''embeddings.word_embeddings''', '''shared.weight'''), ('''embeddings.position_embeddings''', '''embed_positions.weight'''), ('''attention.self.LayerNorm''', '''self_attn_layer_norm'''), ('''attention.output.dense''', '''self_attn.output'''), ('''attention.self''', '''self_attn.self'''), ('''encoder.LayerNorm''', '''encoder.layernorm_embedding'''), ] + END_COMMON ) a__ : Union[str, Any] = [ '''encdec/key/bias''', '''encdec/query/bias''', '''encdec/value/bias''', '''self/key/bias''', '''self/query/bias''', '''self/value/bias''', '''encdec_output/dense/bias''', '''attention/output/dense/bias''', ] def UpperCAmelCase_( a__ , a__ ): """simple docstring""" for tf_name, hf_name in patterns: SCREAMING_SNAKE_CASE : List[Any] = k.replace(a__ , a__ ) return k def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = BigBirdPegasusConfig(**a__ ) SCREAMING_SNAKE_CASE : str = BigBirdPegasusForConditionalGeneration(a__ ) SCREAMING_SNAKE_CASE : int = torch_model.state_dict() SCREAMING_SNAKE_CASE : Optional[Any] = {} # separating decoder weights SCREAMING_SNAKE_CASE : Dict = {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder''' )} SCREAMING_SNAKE_CASE : Optional[int] = {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder''' )} for k, v in tqdm(decoder_weights.items() , '''tf -> hf conversion''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = [k.endswith(a__ ) for ending in KEYS_TO_IGNORE] if any(a__ ): continue SCREAMING_SNAKE_CASE : Dict = DECODER_PATTERNS SCREAMING_SNAKE_CASE : Optional[int] = rename_state_dict_key(a__ , a__ ) if new_k not in state_dict: raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): SCREAMING_SNAKE_CASE : Optional[Any] = v.T SCREAMING_SNAKE_CASE : Optional[int] = torch.from_numpy(a__ ) assert v.shape == state_dict[new_k].shape, F"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items() , '''tf -> hf conversion''' ): SCREAMING_SNAKE_CASE : Optional[int] = [k.endswith(a__ ) for ending in KEYS_TO_IGNORE] if any(a__ ): continue SCREAMING_SNAKE_CASE : int = REMAINING_PATTERNS SCREAMING_SNAKE_CASE : List[Any] = rename_state_dict_key(a__ , a__ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): SCREAMING_SNAKE_CASE : Optional[Any] = v.T SCREAMING_SNAKE_CASE : str = torch.from_numpy(a__ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" SCREAMING_SNAKE_CASE : Any = mapping['''model.embed_positions.weight'''] SCREAMING_SNAKE_CASE : Optional[Any] = mapping.pop('''model.embed_positions.weight''' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = torch_model.load_state_dict(a__ , strict=a__ ) SCREAMING_SNAKE_CASE : Any = [ k for k in missing if k not in [ '''final_logits_bias''', '''model.encoder.embed_tokens.weight''', '''model.decoder.embed_tokens.weight''', '''lm_head.weight''', ] ] assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], F"""no matches found for the following tf keys {extra}""" return torch_model def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = tf.train.list_variables(a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = {} SCREAMING_SNAKE_CASE : Optional[int] = ['''global_step'''] for name, shape in tqdm(a__ , desc='''converting tf checkpoint to dict''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = any(pat in name for pat in ignore_name ) if skip_key: continue SCREAMING_SNAKE_CASE : str = tf.train.load_variable(a__ , a__ ) SCREAMING_SNAKE_CASE : List[str] = array return tf_weights def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = get_tf_weights_as_numpy(a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = convert_bigbird_pegasus(a__ , a__ ) torch_model.save_pretrained(a__ ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument('''--tf_ckpt_path''', type=str, help='''passed to tf.train.list_variables''') parser.add_argument('''--save_dir''', default=None, type=str, help='''Path to the output PyTorch model.''') a__ : Dict = parser.parse_args() a__ : List[Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
19
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a_ ( a__ ): """simple docstring""" def __init__( self , *_lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase ) ->int: super().__init__(*_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = eval_examples SCREAMING_SNAKE_CASE : Optional[int] = post_process_function def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase=None , _lowerCamelCase = None , _lowerCamelCase = "eval" , **_lowerCamelCase , ) ->Dict[str, float]: SCREAMING_SNAKE_CASE : Any = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) SCREAMING_SNAKE_CASE : Dict = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) SCREAMING_SNAKE_CASE : Any = gen_kwargs SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : str = self.get_eval_dataloader(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Optional[Any] = self.compute_metrics SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : Optional[Any] = time.time() SCREAMING_SNAKE_CASE : List[str] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Tuple = eval_loop( _lowerCamelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Dict = compute_metrics SCREAMING_SNAKE_CASE : Tuple = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : Optional[int] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_lowerCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : int = self.callback_handler.on_evaluate(self.args , self.state , self.control , _lowerCamelCase ) return metrics def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase = "test" , **_lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : str = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(_lowerCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[str] = time.time() SCREAMING_SNAKE_CASE : Optional[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Any = eval_loop( _lowerCamelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Optional[int] = compute_metrics SCREAMING_SNAKE_CASE : List[Any] = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , '''predict''' ) SCREAMING_SNAKE_CASE : Dict = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : List[Any] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_lowerCamelCase )
19
1
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss a__ : str = pytest.mark.integration @require_faiss class a_ ( a__ ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE : List[str] = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(_lowerCamelCase ) for x in np.arange(30 ).tolist()]} ) return dset def __lowerCAmelCase ( self ) ->Tuple: import faiss SCREAMING_SNAKE_CASE : Dataset = self._create_dummy_dataset() SCREAMING_SNAKE_CASE : Dict = dset.map( lambda _lowerCamelCase , _lowerCamelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=_lowerCamelCase , keep_in_memory=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) dset.drop_index('''vecs''' ) def __lowerCAmelCase ( self ) ->int: import faiss SCREAMING_SNAKE_CASE : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self ) ->Dict: import faiss SCREAMING_SNAKE_CASE : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_lowerCamelCase ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' ) dset.drop_index('''vecs''' ) self.assertRaises(_lowerCamelCase , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def __lowerCAmelCase ( self ) ->Optional[Any]: from elasticsearch import Elasticsearch SCREAMING_SNAKE_CASE : Dataset = self._create_dummy_dataset() with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: SCREAMING_SNAKE_CASE : List[str] = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) SCREAMING_SNAKE_CASE : List[Any] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} SCREAMING_SNAKE_CASE : List[str] = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class a_ ( a__ ): """simple docstring""" def __lowerCAmelCase ( self ) ->Any: import faiss SCREAMING_SNAKE_CASE : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query SCREAMING_SNAKE_CASE : Optional[Any] = np.zeros(5 , dtype=np.floataa ) SCREAMING_SNAKE_CASE : Any = 1 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = index.search(_lowerCamelCase ) self.assertRaises(_lowerCamelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries SCREAMING_SNAKE_CASE : Dict = np.eye(5 , dtype=np.floataa )[::-1] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = index.search_batch(_lowerCamelCase ) self.assertRaises(_lowerCamelCase , index.search_batch , queries[0] ) SCREAMING_SNAKE_CASE : str = [scores[0] for scores in total_scores] SCREAMING_SNAKE_CASE : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_lowerCamelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Dict: import faiss SCREAMING_SNAKE_CASE : str = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) SCREAMING_SNAKE_CASE : Optional[Any] = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(_lowerCamelCase ): SCREAMING_SNAKE_CASE : Optional[Any] = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowerCAmelCase ( self ) ->int: import faiss SCREAMING_SNAKE_CASE : Tuple = faiss.IndexFlat(5 ) SCREAMING_SNAKE_CASE : Union[str, Any] = FaissIndex(custom_index=_lowerCamelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowerCAmelCase ( self ) ->Dict: import faiss SCREAMING_SNAKE_CASE : Tuple = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_lowerCamelCase ) as tmp_file: index.save(tmp_file.name ) SCREAMING_SNAKE_CASE : Union[str, Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) SCREAMING_SNAKE_CASE : Tuple = np.zeros(5 , dtype=np.floataa ) SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = index.search(_lowerCamelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def UpperCAmelCase_( a__ ): """simple docstring""" import faiss SCREAMING_SNAKE_CASE : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) SCREAMING_SNAKE_CASE : str = '''index.faiss''' SCREAMING_SNAKE_CASE : Optional[int] = F"""mock://{index_name}""" index.save(a__ , storage_options=mockfs.storage_options ) SCREAMING_SNAKE_CASE : List[Any] = FaissIndex.load(a__ , storage_options=mockfs.storage_options ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.zeros(5 , dtype=np.floataa ) SCREAMING_SNAKE_CASE : Optional[Any] = 1 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = index.search(a__ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class a_ ( a__ ): """simple docstring""" def __lowerCAmelCase ( self ) ->str: from elasticsearch import Elasticsearch with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: SCREAMING_SNAKE_CASE : Dict = Elasticsearch() SCREAMING_SNAKE_CASE : List[Any] = {'''acknowledged''': True} SCREAMING_SNAKE_CASE : str = ElasticSearchIndex(es_client=_lowerCamelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query SCREAMING_SNAKE_CASE : List[Any] = '''foo''' SCREAMING_SNAKE_CASE : Optional[Any] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = index.search(_lowerCamelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout SCREAMING_SNAKE_CASE : Tuple = '''foo''' SCREAMING_SNAKE_CASE : int = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = index.search(_lowerCamelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries SCREAMING_SNAKE_CASE : List[Any] = ['''foo''', '''bar''', '''foobar'''] SCREAMING_SNAKE_CASE : List[Any] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = index.search_batch(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = [scores[0] for scores in total_scores] SCREAMING_SNAKE_CASE : Any = [indices[0] for indices in total_indices] self.assertGreater(np.min(_lowerCamelCase ) , 0 ) self.assertListEqual([1, 1, 1] , _lowerCamelCase ) # batched queries with timeout SCREAMING_SNAKE_CASE : List[Any] = ['''foo''', '''bar''', '''foobar'''] SCREAMING_SNAKE_CASE : List[Any] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = index.search_batch(_lowerCamelCase , request_timeout=30 ) SCREAMING_SNAKE_CASE : Tuple = [scores[0] for scores in total_scores] SCREAMING_SNAKE_CASE : Any = [indices[0] for indices in total_indices] self.assertGreater(np.min(_lowerCamelCase ) , 0 ) self.assertListEqual([1, 1, 1] , _lowerCamelCase )
19
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = DDIMPipeline __SCREAMING_SNAKE_CASE : Tuple = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __SCREAMING_SNAKE_CASE : Tuple = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } __SCREAMING_SNAKE_CASE : str = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = False def __lowerCAmelCase ( self ) ->int: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler() SCREAMING_SNAKE_CASE : Dict = {'''unet''': unet, '''scheduler''': scheduler} return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->int: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : int = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Optional[int] = '''cpu''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[Any] = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) SCREAMING_SNAKE_CASE : int = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) SCREAMING_SNAKE_CASE : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def __lowerCAmelCase ( self ) ->Optional[int]: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_save_load_local(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Union[str, Any]: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[int] = '''google/ddpm-cifar10-32''' SCREAMING_SNAKE_CASE : Dict = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler() SCREAMING_SNAKE_CASE : Optional[int] = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddim.to(_lowerCamelCase ) ddim.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = ddim(generator=_lowerCamelCase , eta=0.0 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[Any] = '''google/ddpm-ema-bedroom-256''' SCREAMING_SNAKE_CASE : List[str] = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = DDIMScheduler.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddpm.to(_lowerCamelCase ) ddpm.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = ddpm(generator=_lowerCamelCase , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
19
1
import math a__ : List[str] = 10 a__ : Optional[int] = 7 a__ : int = BALLS_PER_COLOUR * NUM_COLOURS def UpperCAmelCase_( a__ = 20 ): """simple docstring""" SCREAMING_SNAKE_CASE : str = math.comb(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) SCREAMING_SNAKE_CASE : Any = NUM_COLOURS * (1 - missing_colour / total) return F"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
19
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = XLMProphetNetTokenizer __SCREAMING_SNAKE_CASE : List[str] = False __SCREAMING_SNAKE_CASE : Dict = True def __lowerCAmelCase ( self ) ->Dict: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE : Optional[Any] = XLMProphetNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : List[str] = '''[PAD]''' SCREAMING_SNAKE_CASE : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''[PAD]''' ) self.assertEqual(vocab_keys[1] , '''[CLS]''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(_lowerCamelCase ) , 1012 ) def __lowerCAmelCase ( self ) ->List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = XLMProphetNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''[UNK]''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''[UNK]''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self ) ->List[str]: return XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased''' ) @slow def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Union[str, Any] = '''Hello World!''' SCREAMING_SNAKE_CASE : int = [3_5389, 6672, 49, 2] self.assertListEqual(_lowerCamelCase , self.big_tokenizer.encode(_lowerCamelCase ) ) @slow def __lowerCAmelCase ( self ) ->int: # fmt: off SCREAMING_SNAKE_CASE : str = {'''input_ids''': [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''microsoft/xprophetnet-large-wiki100-cased''' , revision='''1acad1643ddd54a44df6a1b797ada8373685d90e''' , )
19
1
def UpperCAmelCase_( a__ ): """simple docstring""" return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
19
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = StableDiffusionSAGPipeline __SCREAMING_SNAKE_CASE : Dict = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : int = False def __lowerCAmelCase ( self ) ->Optional[int]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = 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 , ) SCREAMING_SNAKE_CASE : int = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = 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 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->str: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''prompt''': '''.''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 1.0, '''sag_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) SCREAMING_SNAKE_CASE : Tuple = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = '''.''' SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : int = output.images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : int = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = '''.''' SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = sag_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' ) SCREAMING_SNAKE_CASE : List[str] = output.images SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : str = np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : int = StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) SCREAMING_SNAKE_CASE : Optional[int] = sag_pipe.to(_lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = '''.''' SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = sag_pipe( [prompt] , width=768 , height=512 , generator=_lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : List[Any] = output.images assert image.shape == (1, 512, 768, 3)
19
1
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device a__ : Tuple = False class a_ ( unittest.TestCase ): """simple docstring""" pass @nightly @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Optional[int] = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = pipe( prompt=_lowerCamelCase , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = VersatileDiffusionTextToImagePipeline.from_pretrained(_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe( prompt=_lowerCamelCase , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : str = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = pipe( prompt=_lowerCamelCase , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Dict = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
19
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Tuple = { '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } a__ : Optional[Any] = {'''mobilebert-uncased''': 512} a__ : List[Any] = {} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : int = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_INIT_CONFIGURATION __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Optional[int] = MobileBertTokenizer def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase="[UNK]" , _lowerCamelCase="[SEP]" , _lowerCamelCase="[PAD]" , _lowerCamelCase="[CLS]" , _lowerCamelCase="[MASK]" , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ) ->Optional[int]: super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) SCREAMING_SNAKE_CASE : Optional[int] = do_lower_case SCREAMING_SNAKE_CASE : Optional[int] = strip_accents SCREAMING_SNAKE_CASE : Union[str, Any] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = do_lower_case def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->Any: SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: SCREAMING_SNAKE_CASE : Any = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
19
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = 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=a__ , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=a__ , 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=a__ ) return parser.parse_args() def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = parse_args() # Import training_script as a module. SCREAMING_SNAKE_CASE : Optional[Any] = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) SCREAMING_SNAKE_CASE : Optional[int] = script_fpath.stem SCREAMING_SNAKE_CASE : List[Any] = importlib.import_module(a__ ) # Patch sys.argv SCREAMING_SNAKE_CASE : str = [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()
19
import math a__ : List[str] = 10 a__ : Optional[int] = 7 a__ : int = BALLS_PER_COLOUR * NUM_COLOURS def UpperCAmelCase_( a__ = 20 ): """simple docstring""" SCREAMING_SNAKE_CASE : str = math.comb(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) SCREAMING_SNAKE_CASE : Any = NUM_COLOURS * (1 - missing_colour / total) return F"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
19
1
import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = BertJapaneseTokenizer __SCREAMING_SNAKE_CASE : int = False __SCREAMING_SNAKE_CASE : Tuple = True def __lowerCAmelCase ( self ) ->List[str]: super().setUp() SCREAMING_SNAKE_CASE : Optional[int] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは''', '''世界''', '''##世界''', '''、''', '''##、''', '''。''', '''##。''', ] SCREAMING_SNAKE_CASE : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Tuple = '''こんにちは、世界。 \nこんばんは、世界。''' SCREAMING_SNAKE_CASE : str = '''こんにちは 、 世界 。 こんばんは 、 世界 。''' return input_text, output_text def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.get_input_output_texts(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.decode(_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) return text, ids def __lowerCAmelCase ( self ) ->Tuple: pass # TODO add if relevant def __lowerCAmelCase ( self ) ->Optional[int]: pass # TODO add if relevant def __lowerCAmelCase ( self ) ->Optional[Any]: pass # TODO add if relevant def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : str = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize('''こんにちは、世界。\nこんばんは、世界。''' ) self.assertListEqual(_lowerCamelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Dict = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''mecab''' ) self.assertIsNotNone(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = '''こんにちは、世界。\nこんばんは、世界。''' SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Tuple = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(_lowerCamelCase , '''wb''' ) as handle: pickle.dump(_lowerCamelCase , _lowerCamelCase ) with open(_lowerCamelCase , '''rb''' ) as handle: SCREAMING_SNAKE_CASE : Any = pickle.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = tokenizer_new.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Optional[Any] = MecabTokenizer(mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __lowerCAmelCase ( self ) ->str: try: SCREAMING_SNAKE_CASE : Any = MecabTokenizer(mecab_dic='''unidic_lite''' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __lowerCAmelCase ( self ) ->str: try: SCREAMING_SNAKE_CASE : str = MecabTokenizer(mecab_dic='''unidic''' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Union[str, Any] = MecabTokenizer(do_lower_case=_lowerCamelCase , mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iphone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __lowerCAmelCase ( self ) ->Any: try: SCREAMING_SNAKE_CASE : List[str] = MecabTokenizer( do_lower_case=_lowerCamelCase , normalize_text=_lowerCamelCase , mecab_option='''-d /usr/local/lib/mecab/dic/jumandic''' ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Any = MecabTokenizer(normalize_text=_lowerCamelCase , mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。'''] , ) @require_sudachi def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Dict = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''sudachi''' ) self.assertIsNotNone(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = '''こんにちは、世界。\nこんばんは、世界。''' SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(_lowerCamelCase , '''wb''' ) as handle: pickle.dump(_lowerCamelCase , _lowerCamelCase ) with open(_lowerCamelCase , '''rb''' ) as handle: SCREAMING_SNAKE_CASE : int = pickle.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_new.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @require_sudachi def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[Any] = SudachiTokenizer(sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Any = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''A''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国''', '''人''', '''参政''', '''権'''] ) @require_sudachi def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : Dict = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''B''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人''', '''参政権'''] ) @require_sudachi def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : str = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''C''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人参政権'''] ) @require_sudachi def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Dict = SudachiTokenizer(do_lower_case=_lowerCamelCase , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = SudachiTokenizer(normalize_text=_lowerCamelCase , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', '''\u3000''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Any = SudachiTokenizer(trim_whitespace=_lowerCamelCase , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Any = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''jumanpp''' ) self.assertIsNotNone(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = '''こんにちは、世界。\nこんばんは、世界。''' SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(_lowerCamelCase , '''wb''' ) as handle: pickle.dump(_lowerCamelCase , _lowerCamelCase ) with open(_lowerCamelCase , '''rb''' ) as handle: SCREAMING_SNAKE_CASE : Any = pickle.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = tokenizer_new.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @require_jumanpp def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[str] = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Dict = JumanppTokenizer(do_lower_case=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Any = JumanppTokenizer(normalize_text=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''ア''', '''ッ''', '''フ''', '''゚''', '''ル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[int] = JumanppTokenizer(trim_whitespace=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[int] = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize('''ありがとうございますm(_ _)m見つけるのが大変です。''' ) , ['''ありがとう''', '''ございます''', '''m(_ _)m''', '''見つける''', '''の''', '''が''', '''大変です''', '''。'''] , ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : Dict = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは'''] SCREAMING_SNAKE_CASE : List[Any] = {} for i, token in enumerate(_lowerCamelCase ): SCREAMING_SNAKE_CASE : Any = i SCREAMING_SNAKE_CASE : Tuple = WordpieceTokenizer(vocab=_lowerCamelCase , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こんにちは'''] ) self.assertListEqual(tokenizer.tokenize('''こんばんは''' ) , ['''こん''', '''##ばんは'''] ) self.assertListEqual(tokenizer.tokenize('''こんばんは こんばんにちは こんにちは''' ) , ['''こん''', '''##ばんは''', '''[UNK]''', '''こんにちは'''] ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : str = BertJapaneseTokenizer.from_pretrained('''nlp-waseda/roberta-base-japanese-with-auto-jumanpp''' ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.subword_tokenizer SCREAMING_SNAKE_CASE : str = subword_tokenizer.tokenize('''国境 の 長い トンネル を 抜ける と 雪国 であった 。''' ) self.assertListEqual(_lowerCamelCase , ['''▁国境''', '''▁の''', '''▁長い''', '''▁トンネル''', '''▁を''', '''▁抜ける''', '''▁と''', '''▁雪''', '''国''', '''▁であった''', '''▁。'''] ) SCREAMING_SNAKE_CASE : int = subword_tokenizer.tokenize('''こんばんは こんばん にち は こんにちは''' ) self.assertListEqual(_lowerCamelCase , ['''▁こん''', '''ばん''', '''は''', '''▁こん''', '''ばん''', '''▁に''', '''ち''', '''▁は''', '''▁こんにちは'''] ) def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese''' ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode('''ありがとう。''' , add_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode('''どういたしまして。''' , add_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = BertJapaneseTokenizer __SCREAMING_SNAKE_CASE : int = False def __lowerCAmelCase ( self ) ->Union[str, Any]: super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。'''] SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self , **_lowerCamelCase ) ->List[Any]: return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='''character''' , **_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[Any]: SCREAMING_SNAKE_CASE : int = '''こんにちは、世界。 \nこんばんは、世界。''' SCREAMING_SNAKE_CASE : Optional[int] = '''こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。''' return input_text, output_text def __lowerCAmelCase ( self ) ->Optional[int]: pass # TODO add if relevant def __lowerCAmelCase ( self ) ->Any: pass # TODO add if relevant def __lowerCAmelCase ( self ) ->Union[str, Any]: pass # TODO add if relevant def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='''character''' ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize('''こんにちは、世界。 \nこんばんは、世界。''' ) self.assertListEqual( _lowerCamelCase , ['''こ''', '''ん''', '''に''', '''ち''', '''は''', '''、''', '''世''', '''界''', '''。''', '''こ''', '''ん''', '''ば''', '''ん''', '''は''', '''、''', '''世''', '''界''', '''。'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Any = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。'''] SCREAMING_SNAKE_CASE : str = {} for i, token in enumerate(_lowerCamelCase ): SCREAMING_SNAKE_CASE : Optional[int] = i SCREAMING_SNAKE_CASE : Dict = CharacterTokenizer(vocab=_lowerCamelCase , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''は'''] ) self.assertListEqual(tokenizer.tokenize('''こんにちほ''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''[UNK]'''] ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : str = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese-char''' ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode('''ありがとう。''' , add_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = tokenizer.encode('''どういたしまして。''' , add_special_tokens=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : str = '''cl-tohoku/bert-base-japanese''' SCREAMING_SNAKE_CASE : Tuple = AutoTokenizer.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Union[str, Any] = '''cl-tohoku/bert-base-japanese''' with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm: BertTokenizer.from_pretrained(_lowerCamelCase ) self.assertTrue( cm.records[0].message.startswith( '''The tokenizer class you load from this checkpoint is not the same type as the class this function''' ''' is called from.''' ) ) SCREAMING_SNAKE_CASE : Optional[Any] = '''bert-base-cased''' with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm: BertJapaneseTokenizer.from_pretrained(_lowerCamelCase ) self.assertTrue( cm.records[0].message.startswith( '''The tokenizer class you load from this checkpoint is not the same type as the class this function''' ''' is called from.''' ) )
19
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a__ : List[str] = logging.get_logger(__name__) # General docstring a__ : Tuple = '''MobileNetV1Config''' # Base docstring a__ : Optional[Any] = '''google/mobilenet_v1_1.0_224''' a__ : Tuple = [1, 1_024, 7, 7] # Image classification docstring a__ : Optional[int] = '''google/mobilenet_v1_1.0_224''' a__ : int = '''tabby, tabby cat''' a__ : List[Any] = [ '''google/mobilenet_v1_1.0_224''', '''google/mobilenet_v1_0.75_192''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def UpperCAmelCase_( a__ , a__ , a__=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = {} if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[str] = model.mobilenet_va else: SCREAMING_SNAKE_CASE : Union[str, Any] = model SCREAMING_SNAKE_CASE : Optional[int] = '''MobilenetV1/Conv2d_0/''' SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.convolution.weight SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = backbone.conv_stem.normalization.weight SCREAMING_SNAKE_CASE : Union[str, Any] = backbone.conv_stem.normalization.running_mean SCREAMING_SNAKE_CASE : Any = backbone.conv_stem.normalization.running_var for i in range(13 ): SCREAMING_SNAKE_CASE : Dict = i + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = i * 2 SCREAMING_SNAKE_CASE : Any = backbone.layer[pt_index] SCREAMING_SNAKE_CASE : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" SCREAMING_SNAKE_CASE : Any = pointer.convolution.weight SCREAMING_SNAKE_CASE : Tuple = pointer.normalization.bias SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.running_var SCREAMING_SNAKE_CASE : List[Any] = backbone.layer[pt_index + 1] SCREAMING_SNAKE_CASE : Any = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" SCREAMING_SNAKE_CASE : Dict = pointer.convolution.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : int = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : str = pointer.normalization.running_var if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[Any] = '''MobilenetV1/Logits/Conv2d_1c_1x1/''' SCREAMING_SNAKE_CASE : List[str] = model.classifier.weight SCREAMING_SNAKE_CASE : List[str] = model.classifier.bias return tf_to_pt_map def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ''' '''https://www.tensorflow.org/install/ for installation instructions.''' ) raise # Load weights from TF model SCREAMING_SNAKE_CASE : Optional[Any] = tf.train.list_variables(a__ ) SCREAMING_SNAKE_CASE : List[Any] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) SCREAMING_SNAKE_CASE : Tuple = tf.train.load_variable(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = array # Build TF to PyTorch weights loading map SCREAMING_SNAKE_CASE : int = _build_tf_to_pytorch_map(a__ , a__ , a__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue SCREAMING_SNAKE_CASE : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('''Transposing depthwise''' ) SCREAMING_SNAKE_CASE : Tuple = np.transpose(a__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('''Transposing''' ) if len(pointer.shape ) == 2: # copying into linear layer SCREAMING_SNAKE_CASE : Union[str, Any] = array.squeeze().transpose() else: SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(a__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(a__ ) tf_weights.pop(a__ , a__ ) tf_weights.pop(name + '''/RMSProp''' , a__ ) tf_weights.pop(name + '''/RMSProp_1''' , a__ ) tf_weights.pop(name + '''/ExponentialMovingAverage''' , a__ ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = features.shape[-2:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = conv_layer.stride SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = conv_layer.kernel_size if in_height % stride_height == 0: SCREAMING_SNAKE_CASE : List[str] = max(kernel_height - stride_height , 0 ) else: SCREAMING_SNAKE_CASE : str = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: SCREAMING_SNAKE_CASE : int = max(kernel_width - stride_width , 0 ) else: SCREAMING_SNAKE_CASE : Tuple = max(kernel_width - (in_width % stride_width) , 0 ) SCREAMING_SNAKE_CASE : List[str] = pad_along_width // 2 SCREAMING_SNAKE_CASE : Any = pad_along_width - pad_left SCREAMING_SNAKE_CASE : str = pad_along_height // 2 SCREAMING_SNAKE_CASE : Optional[int] = pad_along_height - pad_top SCREAMING_SNAKE_CASE : List[Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(a__ , a__ , '''constant''' , 0.0 ) class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 1 , _lowerCamelCase = 1 , _lowerCamelCase = False , _lowerCamelCase = True , _lowerCamelCase = True , ) ->None: super().__init__() SCREAMING_SNAKE_CASE : Any = config if in_channels % groups != 0: raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) SCREAMING_SNAKE_CASE : Any = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) SCREAMING_SNAKE_CASE : List[str] = nn.Convad( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=_lowerCamelCase , stride=_lowerCamelCase , padding=_lowerCamelCase , groups=_lowerCamelCase , bias=_lowerCamelCase , padding_mode='''zeros''' , ) if use_normalization: SCREAMING_SNAKE_CASE : List[Any] = nn.BatchNormad( num_features=_lowerCamelCase , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=_lowerCamelCase , track_running_stats=_lowerCamelCase , ) else: SCREAMING_SNAKE_CASE : Dict = None if use_activation: if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Any = ACTaFN[use_activation] elif isinstance(config.hidden_act , _lowerCamelCase ): SCREAMING_SNAKE_CASE : List[str] = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : List[Any] = config.hidden_act else: SCREAMING_SNAKE_CASE : Optional[Any] = None def __lowerCAmelCase ( self , _lowerCamelCase ) ->torch.Tensor: if self.config.tf_padding: SCREAMING_SNAKE_CASE : List[Any] = apply_tf_padding(_lowerCamelCase , self.convolution ) SCREAMING_SNAKE_CASE : Dict = self.convolution(_lowerCamelCase ) if self.normalization is not None: SCREAMING_SNAKE_CASE : int = self.normalization(_lowerCamelCase ) if self.activation is not None: SCREAMING_SNAKE_CASE : List[Any] = self.activation(_lowerCamelCase ) return features class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = MobileNetVaConfig __SCREAMING_SNAKE_CASE : List[Any] = load_tf_weights_in_mobilenet_va __SCREAMING_SNAKE_CASE : int = 'mobilenet_v1' __SCREAMING_SNAKE_CASE : int = 'pixel_values' __SCREAMING_SNAKE_CASE : List[str] = False def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: if isinstance(_lowerCamelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_lowerCamelCase , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) a__ : str = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Union[str, Any] = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase = True ) ->Dict: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = config SCREAMING_SNAKE_CASE : Dict = 32 SCREAMING_SNAKE_CASE : Optional[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) SCREAMING_SNAKE_CASE : str = MobileNetVaConvLayer( _lowerCamelCase , in_channels=config.num_channels , out_channels=_lowerCamelCase , kernel_size=3 , stride=2 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] SCREAMING_SNAKE_CASE : Any = nn.ModuleList() for i in range(13 ): SCREAMING_SNAKE_CASE : int = out_channels if strides[i] == 2 or i == 0: depth *= 2 SCREAMING_SNAKE_CASE : Tuple = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=3 , stride=strides[i] , groups=_lowerCamelCase , ) ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=1 , ) ) SCREAMING_SNAKE_CASE : int = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: raise NotImplementedError @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.conv_stem(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): SCREAMING_SNAKE_CASE : Optional[int] = layer_module(_lowerCamelCase ) if output_hidden_states: SCREAMING_SNAKE_CASE : List[str] = all_hidden_states + (hidden_states,) SCREAMING_SNAKE_CASE : List[str] = hidden_states if self.pooler is not None: SCREAMING_SNAKE_CASE : Tuple = torch.flatten(self.pooler(_lowerCamelCase ) , start_dim=1 ) else: SCREAMING_SNAKE_CASE : List[Any] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_lowerCamelCase , pooler_output=_lowerCamelCase , hidden_states=_lowerCamelCase , ) @add_start_docstrings( '\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->None: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = config.num_labels SCREAMING_SNAKE_CASE : str = MobileNetVaModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head SCREAMING_SNAKE_CASE : Optional[int] = nn.Dropout(config.classifier_dropout_prob , inplace=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = nn.Linear(_lowerCamelCase , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, ImageClassifierOutputWithNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va(_lowerCamelCase , output_hidden_states=_lowerCamelCase , return_dict=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE : Tuple = self.classifier(self.dropout(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : int = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : Any = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : Optional[int] = '''single_label_classification''' else: SCREAMING_SNAKE_CASE : Dict = '''multi_label_classification''' if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Any = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : Dict = loss_fct(_lowerCamelCase , _lowerCamelCase ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : List[Any] = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : List[Any] = loss_fct(_lowerCamelCase , _lowerCamelCase ) if not return_dict: SCREAMING_SNAKE_CASE : Optional[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_lowerCamelCase , logits=_lowerCamelCase , hidden_states=outputs.hidden_states , )
19
1
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : Optional[int] = logging.get_logger(__name__) a__ : int = {'''vocab_file''': '''sentencepiece.model'''} a__ : Dict = { '''vocab_file''': { '''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''', }, } a__ : List[Any] = { '''google/rembert''': 256, } class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : str = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _lowerCamelCase , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase="[CLS]" , _lowerCamelCase="[SEP]" , _lowerCamelCase="[UNK]" , _lowerCamelCase="[SEP]" , _lowerCamelCase="[PAD]" , _lowerCamelCase="[CLS]" , _lowerCamelCase="[MASK]" , **_lowerCamelCase , ) ->Optional[int]: super().__init__( do_lower_case=_lowerCamelCase , remove_space=_lowerCamelCase , keep_accents=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Tuple = do_lower_case SCREAMING_SNAKE_CASE : str = remove_space SCREAMING_SNAKE_CASE : Optional[Any] = keep_accents SCREAMING_SNAKE_CASE : Optional[Any] = vocab_file SCREAMING_SNAKE_CASE : Union[str, Any] = spm.SentencePieceProcessor() self.sp_model.Load(_lowerCamelCase ) @property def __lowerCAmelCase ( self ) ->Optional[int]: return len(self.sp_model ) def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : int = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) ->List[str]: SCREAMING_SNAKE_CASE : Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE : Dict = None return state def __setstate__( self , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : List[str] = d SCREAMING_SNAKE_CASE : List[str] = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=False ) ->Dict: SCREAMING_SNAKE_CASE : Optional[int] = self.sp_model.EncodeAsPieces(_lowerCamelCase ) return pieces def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: return self.sp_model.PieceToId(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[Any]: return self.sp_model.IdToPiece(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[int] = self.sp_model.decode_pieces(_lowerCamelCase ) return out_string def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ) ->List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : List[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(_lowerCamelCase ) ) return SCREAMING_SNAKE_CASE : Dict = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file , _lowerCamelCase ) return (out_vocab_file,)
19
import math def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(a__ ) def UpperCAmelCase_( a__ = 1 / 12_345 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : int = 3 while True: SCREAMING_SNAKE_CASE : Union[str, Any] = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(a__ ): SCREAMING_SNAKE_CASE : List[str] = int(a__ ) total_partitions += 1 if check_partition_perfect(a__ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(a__ ) integer += 1 if __name__ == "__main__": print(F"{solution() = }")
19
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Optional[int] = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ '''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: a__ : List[str] = [ '''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 a__ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar a__ : Any = TypeVar('''T''') def UpperCAmelCase_( a__ ): """simple docstring""" return (position - 1) // 2 def UpperCAmelCase_( a__ ): """simple docstring""" return (2 * position) + 1 def UpperCAmelCase_( a__ ): """simple docstring""" return (2 * position) + 2 class a_ ( Generic[T] ): """simple docstring""" def __init__( self ) ->None: SCREAMING_SNAKE_CASE : list[tuple[T, int]] = [] SCREAMING_SNAKE_CASE : dict[T, int] = {} SCREAMING_SNAKE_CASE : int = 0 def __len__( self ) ->int: return self.elements def __repr__( self ) ->str: return str(self.heap ) def __lowerCAmelCase ( self ) ->bool: # Check if the priority queue is empty return self.elements == 0 def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) SCREAMING_SNAKE_CASE : Tuple = self.elements self.elements += 1 self._bubble_up(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.heap[0] self._bubble_down(_lowerCamelCase ) return elem def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Update the weight of the given key SCREAMING_SNAKE_CASE : List[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE : Any = (elem, weight) if position > 0: SCREAMING_SNAKE_CASE : List[Any] = get_parent_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._bubble_up(_lowerCamelCase ) else: self._bubble_down(_lowerCamelCase ) else: self._bubble_down(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Place a node at the proper position (upward movement) [to be used internally # only] SCREAMING_SNAKE_CASE : Optional[Any] = self.position_map[elem] if curr_pos == 0: return None SCREAMING_SNAKE_CASE : str = get_parent_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.heap[curr_pos] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_up(_lowerCamelCase ) return None def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Place a node at the proper position (downward movement) [to be used # internally only] SCREAMING_SNAKE_CASE : Optional[Any] = self.position_map[elem] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.heap[curr_pos] SCREAMING_SNAKE_CASE : List[str] = get_child_left_position(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = get_child_right_position(_lowerCamelCase ) if child_left_position < self.elements and child_right_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.heap[child_left_position] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) if child_left_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) else: return None if child_right_position < self.elements: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(_lowerCamelCase , _lowerCamelCase ) return self._bubble_down(_lowerCamelCase ) return None def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->None: # Swap the nodes at the given positions SCREAMING_SNAKE_CASE : Optional[int] = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE : Any = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) SCREAMING_SNAKE_CASE : Optional[int] = nodea_pos SCREAMING_SNAKE_CASE : List[str] = nodea_pos class a_ ( Generic[T] ): """simple docstring""" def __init__( self ) ->None: SCREAMING_SNAKE_CASE : dict[T, dict[T, int]] = {} SCREAMING_SNAKE_CASE : int = 0 def __repr__( self ) ->str: return str(self.connections ) def __len__( self ) ->int: return self.nodes def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: # Add a node in the graph if it is not in the graph if node not in self.connections: SCREAMING_SNAKE_CASE : Any = {} self.nodes += 1 def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->None: # Add an edge between 2 nodes in the graph self.add_node(_lowerCamelCase ) self.add_node(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = weight SCREAMING_SNAKE_CASE : str = weight def UpperCAmelCase_( a__ , ): """simple docstring""" SCREAMING_SNAKE_CASE : dict[T, int] = {node: maxsize for node in graph.connections} SCREAMING_SNAKE_CASE : dict[T, T | None] = {node: None for node in graph.connections} SCREAMING_SNAKE_CASE : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(a__ , a__ ) if priority_queue.is_empty(): return dist, parent # initialization SCREAMING_SNAKE_CASE : List[Any] = priority_queue.extract_min() SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE : Any = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) SCREAMING_SNAKE_CASE : str = node # running prim's algorithm while not priority_queue.is_empty(): SCREAMING_SNAKE_CASE : List[str] = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE : List[Any] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) SCREAMING_SNAKE_CASE : str = node return dist, parent
19
1
def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = 0 while b > 0: if b & 1: SCREAMING_SNAKE_CASE : int = ((res % c) + (a % c)) % c a += a b >>= 1 return res
19
from math import pi, sqrt, tan def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''surface_area_cube() only accepts non-negative values''' ) return 6 * side_length**2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if length < 0 or breadth < 0 or height < 0: raise ValueError('''surface_area_cuboid() only accepts non-negative values''' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_sphere() only accepts non-negative values''' ) return 4 * pi * radius**2 def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' ) return 3 * pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cone() only accepts non-negative values''' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( '''surface_area_conical_frustum() only accepts non-negative values''' ) SCREAMING_SNAKE_CASE : Optional[Any] = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius < 0 or height < 0: raise ValueError('''surface_area_cylinder() only accepts non-negative values''' ) return 2 * pi * radius * (height + radius) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if torus_radius < 0 or tube_radius < 0: raise ValueError('''surface_area_torus() only accepts non-negative values''' ) if torus_radius < tube_radius: raise ValueError( '''surface_area_torus() does not support spindle or self intersecting tori''' ) return 4 * pow(a__ , 2 ) * torus_radius * tube_radius def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if length < 0 or width < 0: raise ValueError('''area_rectangle() only accepts non-negative values''' ) return length * width def UpperCAmelCase_( a__ ): """simple docstring""" if side_length < 0: raise ValueError('''area_square() only accepts non-negative values''' ) return side_length**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_triangle() only accepts non-negative values''' ) return (base * height) / 2 def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('''Given three sides do not form a triangle''' ) SCREAMING_SNAKE_CASE : int = (sidea + sidea + sidea) / 2 SCREAMING_SNAKE_CASE : List[str] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if base < 0 or height < 0: raise ValueError('''area_parallelogram() only accepts non-negative values''' ) return base * height def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if basea < 0 or basea < 0 or height < 0: raise ValueError('''area_trapezium() only accepts non-negative values''' ) return 1 / 2 * (basea + basea) * height def UpperCAmelCase_( a__ ): """simple docstring""" if radius < 0: raise ValueError('''area_circle() only accepts non-negative values''' ) return pi * radius**2 def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if radius_x < 0 or radius_y < 0: raise ValueError('''area_ellipse() only accepts non-negative values''' ) return pi * radius_x * radius_y def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if diagonal_a < 0 or diagonal_a < 0: raise ValueError('''area_rhombus() only accepts non-negative values''' ) return 1 / 2 * diagonal_a * diagonal_a def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if not isinstance(a__ , a__ ) or sides < 3: raise ValueError( '''area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides''' ) elif length < 0: raise ValueError( '''area_reg_polygon() only accepts non-negative values as \ length of a side''' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('''[DEMO] Areas of various geometric shapes: \n''') print(F"Rectangle: {area_rectangle(10, 20) = }") print(F"Square: {area_square(10) = }") print(F"Triangle: {area_triangle(10, 10) = }") print(F"Triangle: {area_triangle_three_sides(5, 12, 13) = }") print(F"Parallelogram: {area_parallelogram(10, 20) = }") print(F"Rhombus: {area_rhombus(10, 20) = }") print(F"Trapezium: {area_trapezium(10, 20, 30) = }") print(F"Circle: {area_circle(20) = }") print(F"Ellipse: {area_ellipse(10, 20) = }") print('''\nSurface Areas of various geometric shapes: \n''') print(F"Cube: {surface_area_cube(20) = }") print(F"Cuboid: {surface_area_cuboid(10, 20, 30) = }") print(F"Sphere: {surface_area_sphere(20) = }") print(F"Hemisphere: {surface_area_hemisphere(20) = }") print(F"Cone: {surface_area_cone(10, 20) = }") print(F"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") print(F"Cylinder: {surface_area_cylinder(10, 20) = }") print(F"Torus: {surface_area_torus(20, 10) = }") print(F"Equilateral Triangle: {area_reg_polygon(3, 10) = }") print(F"Square: {area_reg_polygon(4, 10) = }") print(F"Reqular Pentagon: {area_reg_polygon(5, 10) = }")
19
1
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Dict = 10 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : str = [1, 2, 3, 4] SCREAMING_SNAKE_CASE : Optional[int] = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(_lowerCamelCase , self.block_size , 0 ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] SCREAMING_SNAKE_CASE : int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(_lowerCamelCase , self.block_size , 0 ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : str = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] SCREAMING_SNAKE_CASE : Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(_lowerCamelCase , self.block_size , 0 ) , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : List[str] = '''It was the year of Our Lord one thousand seven hundred and seventy-five.\n\nSpiritual revelations were conceded to England at that favoured period, as at this.''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = process_story(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , [] ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : List[Any] = '''''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = process_story(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , [] ) self.assertEqual(_lowerCamelCase , [] ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Any = ( '''It was the year of Our Lord one thousand seven hundred and ''' '''seventy-five\n\nSpiritual revelations were conceded to England ''' '''at that favoured period, as at this.\n@highlight\n\nIt was the best of times''' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = process_story(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = [ '''It was the year of Our Lord one thousand seven hundred and seventy-five.''', '''Spiritual revelations were conceded to England at that favoured period, as at this.''', ] self.assertEqual(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = ['''It was the best of times.'''] self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1, 2, 3, 4] ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(_lowerCamelCase , 0 ).numpy() , expected.numpy() ) def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : int = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(_lowerCamelCase , 23 ).numpy() , expected.numpy() ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) SCREAMING_SNAKE_CASE : Dict = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(_lowerCamelCase , 1 ).numpy() , expected.numpy() ) def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Dict = 101 SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) SCREAMING_SNAKE_CASE : List[str] = compute_token_type_ids(_lowerCamelCase , _lowerCamelCase ) np.testing.assert_array_equal(_lowerCamelCase , _lowerCamelCase )
19
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: a__ : List[str] = None a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Dict = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/mbart-large-en-ro''': '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json''', '''facebook/mbart-large-cc25''': '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json''', }, } a__ : str = { '''facebook/mbart-large-en-ro''': 1_024, '''facebook/mbart-large-cc25''': 1_024, } # fmt: off a__ : List[str] = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = ['input_ids', 'attention_mask'] __SCREAMING_SNAKE_CASE : Tuple = MBartTokenizer __SCREAMING_SNAKE_CASE : List[int] = [] __SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase , ) ->List[Any]: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : List[str] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token super().__init__( vocab_file=_lowerCamelCase , tokenizer_file=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , src_lang=_lowerCamelCase , tgt_lang=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : Any = vocab_file SCREAMING_SNAKE_CASE : List[Any] = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : Any = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) SCREAMING_SNAKE_CASE : int = { lang_code: self.convert_tokens_to_ids(_lowerCamelCase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE : List[str] = src_lang if src_lang is not None else '''en_XX''' SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __lowerCAmelCase ( self ) ->str: return self._src_lang @src_lang.setter def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[int] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : str = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) ->Optional[Any]: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[str] = self(_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = tgt_lang_id return inputs def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = "en_XX" , _lowerCamelCase = None , _lowerCamelCase = "ro_RO" , **_lowerCamelCase , ) ->BatchEncoding: SCREAMING_SNAKE_CASE : List[str] = src_lang SCREAMING_SNAKE_CASE : List[str] = tgt_lang return super().prepare_seqaseq_batch(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Dict: return self.set_src_lang_special_tokens(self.src_lang ) def __lowerCAmelCase ( self ) ->List[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: SCREAMING_SNAKE_CASE : str = self.convert_tokens_to_ids(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : Optional[Any] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Any = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file , _lowerCamelCase ) return (out_vocab_file,)
19
1
import argparse import os import re a__ : Union[str, Any] = '''src/diffusers''' # Pattern that looks at the indentation in a line. a__ : Tuple = re.compile(r'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. a__ : Tuple = re.compile(r'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. a__ : List[str] = re.compile(r'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. a__ : List[str] = re.compile(r'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. a__ : int = re.compile(r'''\[([^\]]+)\]''') def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = _re_indent.search(a__ ) return "" if search is None else search.groups()[0] def UpperCAmelCase_( a__ , a__="" , a__=None , a__=None ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = 0 SCREAMING_SNAKE_CASE : str = code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(a__ ): index += 1 SCREAMING_SNAKE_CASE : Tuple = ['''\n'''.join(lines[:index] )] else: SCREAMING_SNAKE_CASE : Optional[Any] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). SCREAMING_SNAKE_CASE : str = [lines[index]] index += 1 while index < len(a__ ) and (end_prompt is None or not lines[index].startswith(a__ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(a__ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(a__ ) ) if index < len(a__ ) - 1: SCREAMING_SNAKE_CASE : Tuple = [lines[index + 1]] index += 1 else: SCREAMING_SNAKE_CASE : int = [] else: blocks.append('''\n'''.join(a__ ) ) SCREAMING_SNAKE_CASE : Dict = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(a__ ) > 0: blocks.append('''\n'''.join(a__ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(a__ ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def UpperCAmelCase_( a__ ): """simple docstring""" def _inner(a__ ): return key(a__ ).lower().replace('''_''' , '''''' ) return _inner def UpperCAmelCase_( a__ , a__=None ): """simple docstring""" def noop(a__ ): return x if key is None: SCREAMING_SNAKE_CASE : Any = noop # Constants are all uppercase, they go first. SCREAMING_SNAKE_CASE : Any = [obj for obj in objects if key(a__ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. SCREAMING_SNAKE_CASE : Optional[Any] = [obj for obj in objects if key(a__ )[0].isupper() and not key(a__ ).isupper()] # Functions begin with a lowercase, they go last. SCREAMING_SNAKE_CASE : Optional[int] = [obj for obj in objects if not key(a__ )[0].isupper()] SCREAMING_SNAKE_CASE : Tuple = ignore_underscore(a__ ) return sorted(a__ , key=a__ ) + sorted(a__ , key=a__ ) + sorted(a__ , key=a__ ) def UpperCAmelCase_( a__ ): """simple docstring""" def _replace(a__ ): SCREAMING_SNAKE_CASE : List[Any] = match.groups()[0] if "," not in imports: return F"""[{imports}]""" SCREAMING_SNAKE_CASE : Optional[int] = [part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: SCREAMING_SNAKE_CASE : Optional[Any] = keys[:-1] return "[" + ", ".join([F"""\"{k}\"""" for k in sort_objects(a__ )] ) + "]" SCREAMING_SNAKE_CASE : Optional[Any] = import_statement.split('''\n''' ) if len(a__ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. SCREAMING_SNAKE_CASE : Any = 2 if lines[1].strip() == '''[''' else 1 SCREAMING_SNAKE_CASE : List[Any] = [(i, _re_strip_line.search(a__ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] SCREAMING_SNAKE_CASE : List[Any] = sort_objects(a__ , key=lambda a__ : x[1] ) SCREAMING_SNAKE_CASE : Optional[Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(a__ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: SCREAMING_SNAKE_CASE : Tuple = _re_bracket_content.sub(_replace , lines[1] ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = [part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: SCREAMING_SNAKE_CASE : Optional[int] = keys[:-1] SCREAMING_SNAKE_CASE : Union[str, Any] = get_indent(lines[1] ) + ''', '''.join([F"""\"{k}\"""" for k in sort_objects(a__ )] ) return "\n".join(a__ ) else: # Finally we have to deal with imports fitting on one line SCREAMING_SNAKE_CASE : Optional[int] = _re_bracket_content.sub(_replace , a__ ) return import_statement def UpperCAmelCase_( a__ , a__=True ): """simple docstring""" with open(a__ , '''r''' ) as f: SCREAMING_SNAKE_CASE : Optional[Any] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 SCREAMING_SNAKE_CASE : List[Any] = split_code_in_indented_blocks( a__ , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(a__ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. SCREAMING_SNAKE_CASE : Tuple = main_blocks[block_idx] SCREAMING_SNAKE_CASE : int = block.split('''\n''' ) # Get to the start of the imports. SCREAMING_SNAKE_CASE : Optional[Any] = 0 while line_idx < len(a__ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: SCREAMING_SNAKE_CASE : int = len(a__ ) else: line_idx += 1 if line_idx >= len(a__ ): continue # Ignore beginning and last line: they don't contain anything. SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(block_lines[line_idx:-1] ) SCREAMING_SNAKE_CASE : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. SCREAMING_SNAKE_CASE : Tuple = split_code_in_indented_blocks(a__ , indent_level=a__ ) # We have two categories of import key: list or _import_structure[key].append/extend SCREAMING_SNAKE_CASE : Union[str, Any] = _re_direct_key if '''_import_structure''' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. SCREAMING_SNAKE_CASE : Dict = [(pattern.search(a__ ).groups()[0] if pattern.search(a__ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. SCREAMING_SNAKE_CASE : Optional[int] = [(i, key) for i, key in enumerate(a__ ) if key is not None] SCREAMING_SNAKE_CASE : Tuple = [x[0] for x in sorted(a__ , key=lambda a__ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : Tuple = [] for i in range(len(a__ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: SCREAMING_SNAKE_CASE : List[Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(a__ ) count += 1 # And we put our main block back together with its first and last line. SCREAMING_SNAKE_CASE : Any = '''\n'''.join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(a__ ): if check_only: return True else: print(F"""Overwriting {file}.""" ) with open(a__ , '''w''' ) as f: f.write('''\n'''.join(a__ ) ) def UpperCAmelCase_( a__=True ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = [] for root, _, files in os.walk(a__ ): if "__init__.py" in files: SCREAMING_SNAKE_CASE : Union[str, Any] = sort_imports(os.path.join(a__ , '''__init__.py''' ) , check_only=a__ ) if result: SCREAMING_SNAKE_CASE : Union[str, Any] = [os.path.join(a__ , '''__init__.py''' )] if len(a__ ) > 0: raise ValueError(F"""Would overwrite {len(a__ )} files, run `make style`.""" ) if __name__ == "__main__": a__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') a__ : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
19
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging a__ : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=768 ) ->List[Any]: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = proj_size SCREAMING_SNAKE_CASE : Any = CLIPVisionModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = PaintByExampleMapper(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = nn.LayerNorm(config.hidden_size ) SCREAMING_SNAKE_CASE : int = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=False ) ->int: SCREAMING_SNAKE_CASE : Optional[Any] = self.model(pixel_values=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = clip_output.pooler_output SCREAMING_SNAKE_CASE : Optional[Any] = self.mapper(latent_states[:, None] ) SCREAMING_SNAKE_CASE : Tuple = self.final_layer_norm(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.proj_out(_lowerCamelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->List[str]: super().__init__() SCREAMING_SNAKE_CASE : str = (config.num_hidden_layers + 1) // 5 SCREAMING_SNAKE_CASE : List[Any] = config.hidden_size SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : Optional[Any] = nn.ModuleList( [ BasicTransformerBlock(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , activation_fn='''gelu''' , attention_bias=_lowerCamelCase ) for _ in range(_lowerCamelCase ) ] ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: for block in self.blocks: SCREAMING_SNAKE_CASE : Optional[int] = block(_lowerCamelCase ) return hidden_states
19
1
class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Optional[int] = graph self._normalize_graph(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = len(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = None def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Union[str, Any]: if sources is int: SCREAMING_SNAKE_CASE : Tuple = [sources] if sinks is int: SCREAMING_SNAKE_CASE : int = [sinks] if len(_lowerCamelCase ) == 0 or len(_lowerCamelCase ) == 0: return SCREAMING_SNAKE_CASE : str = sources[0] SCREAMING_SNAKE_CASE : Any = sinks[0] # make fake vertex if there are more # than one source or sink if len(_lowerCamelCase ) > 1 or len(_lowerCamelCase ) > 1: SCREAMING_SNAKE_CASE : List[str] = 0 for i in sources: max_input_flow += sum(self.graph[i] ) SCREAMING_SNAKE_CASE : int = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: SCREAMING_SNAKE_CASE : Dict = max_input_flow SCREAMING_SNAKE_CASE : Union[str, Any] = 0 SCREAMING_SNAKE_CASE : Optional[Any] = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: SCREAMING_SNAKE_CASE : Union[str, Any] = max_input_flow SCREAMING_SNAKE_CASE : int = size - 1 def __lowerCAmelCase ( self ) ->Optional[int]: if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def __lowerCAmelCase ( self , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Any = algorithm(self ) class a_ : """simple docstring""" def __init__( self , _lowerCamelCase ) ->List[str]: SCREAMING_SNAKE_CASE : str = flow_network SCREAMING_SNAKE_CASE : str = flow_network.verticesCount SCREAMING_SNAKE_CASE : Dict = flow_network.sourceIndex SCREAMING_SNAKE_CASE : Tuple = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that SCREAMING_SNAKE_CASE : int = flow_network.graph SCREAMING_SNAKE_CASE : Optional[int] = False def __lowerCAmelCase ( self ) ->int: if not self.executed: self._algorithm() SCREAMING_SNAKE_CASE : Union[str, Any] = True def __lowerCAmelCase ( self ) ->int: pass class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->Optional[Any]: super().__init__(_lowerCamelCase ) # use this to save your result SCREAMING_SNAKE_CASE : Dict = -1 def __lowerCAmelCase ( self ) ->Tuple: if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->Union[str, Any]: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = [[0] * self.verticies_count for i in range(self.verticies_count )] SCREAMING_SNAKE_CASE : Dict = [0] * self.verticies_count SCREAMING_SNAKE_CASE : Any = [0] * self.verticies_count def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : List[str] = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule SCREAMING_SNAKE_CASE : Dict = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list SCREAMING_SNAKE_CASE : Any = 0 while i < len(_lowerCamelCase ): SCREAMING_SNAKE_CASE : Tuple = vertices_list[i] SCREAMING_SNAKE_CASE : Any = self.heights[vertex_index] self.process_vertex(_lowerCamelCase ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : Any = 0 else: i += 1 SCREAMING_SNAKE_CASE : str = sum(self.preflow[self.source_index] ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(_lowerCamelCase , _lowerCamelCase ) self.relabel(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->str: SCREAMING_SNAKE_CASE : Optional[Any] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Any = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): SCREAMING_SNAKE_CASE : Dict = self.heights[to_index] if min_height is not None: SCREAMING_SNAKE_CASE : Optional[Any] = min_height + 1 if __name__ == "__main__": a__ : Dict = [0] a__ : Optional[int] = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] a__ : int = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network a__ : str = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate a__ : str = flow_network.find_maximum_flow() print(F"maximum flow is {maximum_flow}")
19
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 a__ : Tuple = '''▁''' a__ : List[Any] = {'''vocab_file''': '''spiece.model'''} a__ : Optional[Any] = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } a__ : str = { '''google/pegasus-xsum''': 512, } a__ : str = logging.get_logger(__name__) class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : str = ['input_ids', 'attention_mask'] def __init__( self , _lowerCamelCase , _lowerCamelCase="<pad>" , _lowerCamelCase="</s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<mask_2>" , _lowerCamelCase="<mask_1>" , _lowerCamelCase=None , _lowerCamelCase=103 , _lowerCamelCase = None , **_lowerCamelCase , ) ->None: SCREAMING_SNAKE_CASE : Dict = offset if additional_special_tokens is not None: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError( F"""additional_special_tokens should be of type {type(_lowerCamelCase )}, but is""" F""" {type(_lowerCamelCase )}""" ) SCREAMING_SNAKE_CASE : List[Any] = ( ([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(_lowerCamelCase ) , self.offset - 1 ) ] if len(set(_lowerCamelCase ) ) != len(_lowerCamelCase ): 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}.""" ) SCREAMING_SNAKE_CASE : Dict = additional_special_tokens_extended else: SCREAMING_SNAKE_CASE : str = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F"""<unk_{i}>""" for i in range(2 , self.offset )] SCREAMING_SNAKE_CASE : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , mask_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token_sent=_lowerCamelCase , offset=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[str] = mask_token_sent SCREAMING_SNAKE_CASE : Optional[int] = vocab_file SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) # add special tokens to encoder dict SCREAMING_SNAKE_CASE : Dict[int, str] = { 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 )} ) SCREAMING_SNAKE_CASE : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def __lowerCAmelCase ( self ) ->int: return len(self.sp_model ) + self.offset def __lowerCAmelCase ( self ) ->Dict[str, int]: SCREAMING_SNAKE_CASE : Union[str, Any] = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = self.__dict__.copy() SCREAMING_SNAKE_CASE : str = None return state def __setstate__( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : List[str] = {} SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.piece_to_id(_lowerCamelCase ) return sp_id + self.offset def __lowerCAmelCase ( self , _lowerCamelCase ) ->str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: SCREAMING_SNAKE_CASE : Dict = self.sp_model.IdToPiece(index - self.offset ) return token def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : int = '''''' 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(_lowerCamelCase ) + token SCREAMING_SNAKE_CASE : Optional[Any] = [] else: current_sub_tokens.append(_lowerCamelCase ) out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def __lowerCAmelCase ( self , _lowerCamelCase=False ) ->str: return 1 def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Dict = 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ) ->List[int]: if already_has_special_tokens: return self._special_token_mask(_lowerCamelCase ) elif token_ids_a is None: return self._special_token_mask(_lowerCamelCase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=None ) ->List[int]: 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : int = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE : Tuple = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
19
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class a_ ( unittest.TestCase ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=7 , _lowerCamelCase=3 , _lowerCamelCase=30 , _lowerCamelCase=400 , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=[0.5, 0.5, 0.5] , _lowerCamelCase=[0.5, 0.5, 0.5] , _lowerCamelCase=True , _lowerCamelCase=1 / 255 , _lowerCamelCase=True , ) ->Optional[Any]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p SCREAMING_SNAKE_CASE : Optional[int] = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333} SCREAMING_SNAKE_CASE : Optional[Any] = parent SCREAMING_SNAKE_CASE : List[Any] = batch_size SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : Optional[int] = min_resolution SCREAMING_SNAKE_CASE : Dict = max_resolution SCREAMING_SNAKE_CASE : Optional[int] = do_resize SCREAMING_SNAKE_CASE : Optional[int] = size SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std SCREAMING_SNAKE_CASE : Tuple = do_rescale SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE : Dict = do_pad def __lowerCAmelCase ( self ) ->Optional[int]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=False ) ->int: if not batched: SCREAMING_SNAKE_CASE : Optional[int] = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = image.size else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: SCREAMING_SNAKE_CASE : Dict = int(self.size['''shortest_edge'''] * h / w ) SCREAMING_SNAKE_CASE : str = self.size['''shortest_edge'''] elif w > h: SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: SCREAMING_SNAKE_CASE : Optional[int] = self.size['''shortest_edge'''] SCREAMING_SNAKE_CASE : Any = self.size['''shortest_edge'''] else: SCREAMING_SNAKE_CASE : Any = [] for image in image_inputs: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] SCREAMING_SNAKE_CASE : Tuple = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = YolosImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Any = YolosImageProcessingTester(self ) @property def __lowerCAmelCase ( self ) ->Union[str, Any]: return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1333} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) SCREAMING_SNAKE_CASE : int = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->int: pass def __lowerCAmelCase ( self ) ->Optional[int]: # Initialize image_processing SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCAmelCase ( self ) ->Union[str, Any]: # Initialize image_processing SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCAmelCase ( self ) ->Any: # Initialize image_processing SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCAmelCase ( self ) ->int: # Initialize image_processings SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors SCREAMING_SNAKE_CASE : List[Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def __lowerCAmelCase ( self ) ->List[str]: # prepare image and target SCREAMING_SNAKE_CASE : Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) SCREAMING_SNAKE_CASE : str = {'''image_id''': 3_9769, '''annotations''': target} # encode them SCREAMING_SNAKE_CASE : Union[str, Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) SCREAMING_SNAKE_CASE : Tuple = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area SCREAMING_SNAKE_CASE : Dict = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes SCREAMING_SNAKE_CASE : Dict = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : int = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id SCREAMING_SNAKE_CASE : int = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels SCREAMING_SNAKE_CASE : List[str] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size SCREAMING_SNAKE_CASE : Any = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size SCREAMING_SNAKE_CASE : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def __lowerCAmelCase ( self ) ->Union[str, Any]: # prepare image, target and masks_path SCREAMING_SNAKE_CASE : Optional[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) SCREAMING_SNAKE_CASE : str = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9769, '''segments_info''': target} SCREAMING_SNAKE_CASE : str = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them SCREAMING_SNAKE_CASE : Optional[int] = YolosImageProcessor(format='''coco_panoptic''' ) SCREAMING_SNAKE_CASE : int = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes SCREAMING_SNAKE_CASE : str = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id SCREAMING_SNAKE_CASE : Any = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd SCREAMING_SNAKE_CASE : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks SCREAMING_SNAKE_CASE : Union[str, Any] = 82_2873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
19
def UpperCAmelCase_( a__ ): """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Tuple = 1 while repunit: SCREAMING_SNAKE_CASE : Dict = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def UpperCAmelCase_( a__ = 1_000_000 ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(a__ ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F"{solution() = }")
19
1
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class a_ ( a__ ): """simple docstring""" def __lt__( self , _lowerCamelCase ) ->List[Any]: return self[-1] < other[-1] def __eq__( self , _lowerCamelCase ) ->List[Any]: return self[-1] == other[-1] def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : list[Stack] = [] # sort into stacks for element in collection: SCREAMING_SNAKE_CASE : Union[str, Any] = Stack([element] ) SCREAMING_SNAKE_CASE : Union[str, Any] = bisect_left(a__ , a__ ) if i != len(a__ ): stacks[i].append(a__ ) else: stacks.append(a__ ) # use a heap-based merge to merge stack efficiently SCREAMING_SNAKE_CASE : Optional[int] = merge(*(reversed(a__ ) for stack in stacks) ) return collection if __name__ == "__main__": a__ : Tuple = input('''Enter numbers separated by a comma:\n''').strip() a__ : Dict = [int(item) for item in user_input.split(''',''')] print(patience_sort(unsorted))
19
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=32 , _lowerCamelCase=3 , _lowerCamelCase=4 , _lowerCamelCase=[10, 20, 30, 40] , _lowerCamelCase=[2, 2, 3, 2] , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=10 , _lowerCamelCase=0.0_2 , _lowerCamelCase=["stage2", "stage3", "stage4"] , _lowerCamelCase=3 , _lowerCamelCase=None , ) ->Dict: SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Optional[Any] = batch_size SCREAMING_SNAKE_CASE : Optional[Any] = image_size SCREAMING_SNAKE_CASE : str = num_channels SCREAMING_SNAKE_CASE : Any = num_stages SCREAMING_SNAKE_CASE : List[str] = hidden_sizes SCREAMING_SNAKE_CASE : Optional[Any] = depths SCREAMING_SNAKE_CASE : Any = is_training SCREAMING_SNAKE_CASE : Tuple = use_labels SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : int = out_features SCREAMING_SNAKE_CASE : List[str] = num_labels SCREAMING_SNAKE_CASE : int = scope SCREAMING_SNAKE_CASE : Optional[Any] = num_stages def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : str = None if self.use_labels: SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) ->List[Any]: return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def __lowerCAmelCase ( self ) ->Any: return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_lowerCamelCase , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_lowerCamelCase , loss_ignore_index=255 , num_labels=self.num_labels , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->Any: SCREAMING_SNAKE_CASE : List[Any] = UperNetForSemanticSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = (UperNetForSemanticSegmentation,) if is_torch_available() else () __SCREAMING_SNAKE_CASE : List[str] = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {} __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Union[str, Any] = False __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : Any = False def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Optional[Any] = UperNetModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def __lowerCAmelCase ( self ) ->str: 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 __lowerCAmelCase ( self ) ->str: return def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Optional[int] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase ) @unittest.skip(reason='''UperNet does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) ->Union[str, Any]: pass @unittest.skip(reason='''UperNet does not support input and output embeddings''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->int: pass @unittest.skip(reason='''UperNet does not have a base model''' ) def __lowerCAmelCase ( self ) ->str: pass @require_torch_multi_gpu @unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def __lowerCAmelCase ( self ) ->str: pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowerCAmelCase ( self ) ->Tuple: pass def __lowerCAmelCase ( self ) ->int: def check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) SCREAMING_SNAKE_CASE : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # ConvNext'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] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Union[str, Any] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : str = _config_zero_init(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip(reason='''UperNet does not have tied weights''' ) def __lowerCAmelCase ( self ) ->List[Any]: pass @slow def __lowerCAmelCase ( self ) ->List[Any]: for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Any = UperNetForSemanticSegmentation.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = hf_hub_download( repo_id='''hf-internal-testing/fixtures_ade20k''' , repo_type='''dataset''' , filename='''ADE_val_00000001.jpg''' ) SCREAMING_SNAKE_CASE : Any = Image.open(a__ ).convert('''RGB''' ) return image @require_torch @require_vision @slow class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny''' ) SCREAMING_SNAKE_CASE : Tuple = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny''' ) SCREAMING_SNAKE_CASE : str = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny''' ).to(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = prepare_img() SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowerCamelCase , atol=1e-4 ) )
19
1
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Union[str, Any] = {'''vocab_file''': '''spiece.model'''} a__ : Tuple = { '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', } } a__ : Optional[Any] = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) a__ : Optional[Any] = 0 a__ : Dict = 1 a__ : Optional[Any] = 2 a__ : Any = 3 a__ : List[Any] = 4 class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : str = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : int = 'left' def __init__( self , _lowerCamelCase , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<sep>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<cls>" , _lowerCamelCase="<mask>" , _lowerCamelCase=["<eop>", "<eod>"] , _lowerCamelCase = None , **_lowerCamelCase , ) ->None: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : Union[str, Any] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token SCREAMING_SNAKE_CASE : List[str] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_lowerCamelCase , remove_space=_lowerCamelCase , keep_accents=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) SCREAMING_SNAKE_CASE : List[str] = 3 SCREAMING_SNAKE_CASE : str = do_lower_case SCREAMING_SNAKE_CASE : List[str] = remove_space SCREAMING_SNAKE_CASE : Dict = keep_accents SCREAMING_SNAKE_CASE : Any = vocab_file SCREAMING_SNAKE_CASE : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @property def __lowerCAmelCase ( self ) ->int: return len(self.sp_model ) def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Optional[int] = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = self.__dict__.copy() SCREAMING_SNAKE_CASE : List[Any] = None return state def __setstate__( self , _lowerCamelCase ) ->List[Any]: SCREAMING_SNAKE_CASE : Any = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : str = {} SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->Optional[Any]: if self.remove_space: SCREAMING_SNAKE_CASE : Dict = ''' '''.join(inputs.strip().split() ) else: SCREAMING_SNAKE_CASE : Tuple = inputs SCREAMING_SNAKE_CASE : str = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: SCREAMING_SNAKE_CASE : int = unicodedata.normalize('''NFKD''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = ''''''.join([c for c in outputs if not unicodedata.combining(_lowerCamelCase )] ) if self.do_lower_case: SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.lower() return outputs def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: SCREAMING_SNAKE_CASE : List[str] = self.preprocess_text(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = [] for piece in pieces: if len(_lowerCamelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): SCREAMING_SNAKE_CASE : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(_lowerCamelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: SCREAMING_SNAKE_CASE : Optional[int] = cur_pieces[1:] else: SCREAMING_SNAKE_CASE : List[Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_lowerCamelCase ) else: new_pieces.append(_lowerCamelCase ) return new_pieces def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: return self.sp_model.PieceToId(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->Union[str, Any]: return self.sp_model.IdToPiece(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[Any] = ''''''.join(_lowerCamelCase ).replace(_lowerCamelCase , ''' ''' ).strip() return out_string def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = True , **_lowerCamelCase , ) ->str: SCREAMING_SNAKE_CASE : List[str] = kwargs.pop('''use_source_tokenizer''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.convert_ids_to_tokens(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : str = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : Tuple = [] sub_texts.append(_lowerCamelCase ) else: current_sub_text.append(_lowerCamelCase ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_lowerCamelCase ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens SCREAMING_SNAKE_CASE : Optional[Any] = ''''''.join(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: SCREAMING_SNAKE_CASE : int = self.clean_up_tokenization(_lowerCamelCase ) return clean_text else: return text def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ) ->List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) if token_ids_a is not None: return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1, 1] return ([0] * len(_lowerCamelCase )) + [1, 1] def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->List[int]: SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE : Tuple = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
19
import datasets from .evaluate import evaluate a__ : Dict = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' a__ : List[str] = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' a__ : List[Any] = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric("cuad") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': { '''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.features.Sequence(datasets.Value('''string''' ) ), }, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://www.atticusprojectai.org/cuad'''] , reference_urls=['''https://www.atticusprojectai.org/cuad'''] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase ) ->Tuple: SCREAMING_SNAKE_CASE : Any = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} SCREAMING_SNAKE_CASE : int = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] SCREAMING_SNAKE_CASE : Dict = evaluate(dataset=_lowerCamelCase , predictions=_lowerCamelCase ) return score
19
1
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( '''split_dict''' , [ SplitDict(), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1_337 , num_examples=42 , dataset_name='''my_dataset''' )} ), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1_337 , num_examples=42 )} ), SplitDict({'''train''': SplitInfo()} ), ] , ) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = split_dict._to_yaml_list() assert len(a__ ) == len(a__ ) SCREAMING_SNAKE_CASE : Optional[int] = SplitDict._from_yaml_list(a__ ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump SCREAMING_SNAKE_CASE : Optional[int] = None # the split name of split_dict takes over the name of the split info object SCREAMING_SNAKE_CASE : Union[str, Any] = split_name assert split_dict == reloaded @pytest.mark.parametrize( '''split_info''' , [SplitInfo(), SplitInfo(dataset_name=a__ ), SplitInfo(dataset_name='''my_dataset''' )] ) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = asdict(SplitDict({'''train''': split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
19
from sklearn.metrics import matthews_corrcoef import datasets a__ : Optional[Any] = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' a__ : str = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' a__ : Union[str, Any] = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ) ->List[str]: return { "matthews_correlation": float(matthews_corrcoef(_lowerCamelCase , _lowerCamelCase , sample_weight=_lowerCamelCase ) ), }
19
1
from __future__ import annotations def UpperCAmelCase_( a__ , a__ ): """simple docstring""" if b == 0: return (1, 0) ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Tuple = extended_euclid(a__ , a % b ) SCREAMING_SNAKE_CASE : int = a // b return (y, x - k * y) def UpperCAmelCase_( a__ , a__ , a__ , a__ ): """simple docstring""" ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Union[str, Any] = extended_euclid(a__ , a__ ) SCREAMING_SNAKE_CASE : Tuple = na * na SCREAMING_SNAKE_CASE : Dict = ra * x * na + ra * y * na return (n % m + m) % m def UpperCAmelCase_( a__ , a__ ): """simple docstring""" ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) : Tuple = extended_euclid(a__ , a__ ) if b < 0: SCREAMING_SNAKE_CASE : List[str] = (b % n + n) % n return b def UpperCAmelCase_( a__ , a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = invert_modulo(a__ , a__ ), invert_modulo(a__ , a__ ) SCREAMING_SNAKE_CASE : List[Any] = na * na SCREAMING_SNAKE_CASE : Tuple = ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name='''chinese_remainder_theorem''', verbose=True) testmod(name='''chinese_remainder_theorem2''', verbose=True) testmod(name='''invert_modulo''', verbose=True) testmod(name='''extended_euclid''', verbose=True)
19
# Copyright 2021 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 argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_( ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=a__ ) SCREAMING_SNAKE_CASE : int = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=a__ ) env_command_parser(subparsers=a__ ) launch_command_parser(subparsers=a__ ) tpu_command_parser(subparsers=a__ ) test_command_parser(subparsers=a__ ) # Let's go SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() if not hasattr(a__ , '''func''' ): parser.print_help() exit(1 ) # Run args.func(a__ ) if __name__ == "__main__": main()
19
1
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a_ ( a__ ): """simple docstring""" def __init__( self , *_lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase ) ->int: super().__init__(*_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = eval_examples SCREAMING_SNAKE_CASE : Optional[int] = post_process_function def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase=None , _lowerCamelCase = None , _lowerCamelCase = "eval" , **_lowerCamelCase , ) ->Dict[str, float]: SCREAMING_SNAKE_CASE : Any = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) SCREAMING_SNAKE_CASE : Dict = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) SCREAMING_SNAKE_CASE : Any = gen_kwargs SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : str = self.get_eval_dataloader(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Optional[Any] = self.compute_metrics SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : Optional[Any] = time.time() SCREAMING_SNAKE_CASE : List[str] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Tuple = eval_loop( _lowerCamelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Dict = compute_metrics SCREAMING_SNAKE_CASE : Tuple = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : Optional[int] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_lowerCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : int = self.callback_handler.on_evaluate(self.args , self.state , self.control , _lowerCamelCase ) return metrics def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase = "test" , **_lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : str = gen_kwargs.copy() SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(_lowerCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[str] = time.time() SCREAMING_SNAKE_CASE : Optional[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : Any = eval_loop( _lowerCamelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowerCamelCase , metric_key_prefix=_lowerCamelCase , ) finally: SCREAMING_SNAKE_CASE : Optional[int] = compute_metrics SCREAMING_SNAKE_CASE : List[Any] = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _lowerCamelCase , _lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Tuple = self.post_process_function(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , '''predict''' ) SCREAMING_SNAKE_CASE : Dict = self.compute_metrics(_lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): SCREAMING_SNAKE_CASE : List[Any] = metrics.pop(_lowerCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_lowerCamelCase )
19
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Optional[Any] = {'''vocab_file''': '''vocab.json'''} a__ : str = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } a__ : Tuple = {'''mgp-str''': 27} class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : Dict = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _lowerCamelCase , _lowerCamelCase="[GO]" , _lowerCamelCase="[GO]" , _lowerCamelCase="[s]" , _lowerCamelCase="[GO]" , **_lowerCamelCase ) ->Dict: super().__init__( unk_token=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , pad_token=_lowerCamelCase , **_lowerCamelCase , ) with open(_lowerCamelCase , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE : List[Any] = json.load(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.vocab.items()} @property def __lowerCAmelCase ( self ) ->List[Any]: return len(self.vocab ) def __lowerCAmelCase ( self ) ->Union[str, Any]: return dict(self.vocab , **self.added_tokens_encoder ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: SCREAMING_SNAKE_CASE : Union[str, Any] = [] for s in text: char_tokens.extend(_lowerCamelCase ) return char_tokens def __lowerCAmelCase ( self , _lowerCamelCase ) ->Dict: return self.vocab.get(_lowerCamelCase , self.vocab.get(self.unk_token ) ) def __lowerCAmelCase ( self , _lowerCamelCase ) ->int: return self.decoder.get(_lowerCamelCase ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ) ->Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error('''Vocabulary path ({}) should be a directory'''.format(_lowerCamelCase ) ) return SCREAMING_SNAKE_CASE : str = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=_lowerCamelCase , ensure_ascii=_lowerCamelCase ) + '''\n''' ) return (vocab_file,)
19
1
def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" if principal <= 0: raise Exception('''Principal borrowed must be > 0''' ) if rate_per_annum < 0: raise Exception('''Rate of interest must be >= 0''' ) if years_to_repay <= 0 or not isinstance(a__ , a__ ): raise Exception('''Years to repay must be an integer > 0''' ) # Yearly rate is divided by 12 to get monthly rate SCREAMING_SNAKE_CASE : int = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly SCREAMING_SNAKE_CASE : int = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a__ : Optional[Any] = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = ['''DeiTFeatureExtractor'''] a__ : Any = ['''DeiTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DeiTForImageClassification''', '''DeiTForImageClassificationWithTeacher''', '''DeiTForMaskedImageModeling''', '''DeiTModel''', '''DeiTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ '''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 a__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
19
1
import math def UpperCAmelCase_( a__ , a__ = 0 , a__ = 0 ): """simple docstring""" SCREAMING_SNAKE_CASE : str = end or len(a__ ) for i in range(a__ , a__ ): SCREAMING_SNAKE_CASE : Any = i SCREAMING_SNAKE_CASE : List[str] = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: SCREAMING_SNAKE_CASE : Optional[int] = array[temp_index - 1] temp_index -= 1 SCREAMING_SNAKE_CASE : List[Any] = temp_index_value return array def UpperCAmelCase_( a__ , a__ , a__ ): # Max Heap """simple docstring""" SCREAMING_SNAKE_CASE : int = index SCREAMING_SNAKE_CASE : Tuple = 2 * index + 1 # Left Node SCREAMING_SNAKE_CASE : int = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: SCREAMING_SNAKE_CASE : int = left_index if right_index < heap_size and array[largest] < array[right_index]: SCREAMING_SNAKE_CASE : Optional[int] = right_index if largest != index: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = array[largest], array[index] heapify(a__ , a__ , a__ ) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : str = len(a__ ) for i in range(n // 2 , -1 , -1 ): heapify(a__ , a__ , a__ ) for i in range(n - 1 , 0 , -1 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = array[0], array[i] heapify(a__ , 0 , a__ ) return array def UpperCAmelCase_( a__ , a__ , a__ , a__ ): """simple docstring""" if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def UpperCAmelCase_( a__ , a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = low SCREAMING_SNAKE_CASE : List[Any] = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = array[j], array[i] i += 1 def UpperCAmelCase_( a__ ): """simple docstring""" if len(a__ ) == 0: return array SCREAMING_SNAKE_CASE : List[str] = 2 * math.ceil(math.loga(len(a__ ) ) ) SCREAMING_SNAKE_CASE : int = 16 return intro_sort(a__ , 0 , len(a__ ) , a__ , a__ ) def UpperCAmelCase_( a__ , a__ , a__ , a__ , a__ ): """simple docstring""" while end - start > size_threshold: if max_depth == 0: return heap_sort(a__ ) max_depth -= 1 SCREAMING_SNAKE_CASE : int = median_of_a(a__ , a__ , start + ((end - start) // 2) + 1 , end - 1 ) SCREAMING_SNAKE_CASE : Dict = partition(a__ , a__ , a__ , a__ ) intro_sort(a__ , a__ , a__ , a__ , a__ ) SCREAMING_SNAKE_CASE : Optional[int] = p return insertion_sort(a__ , a__ , a__ ) if __name__ == "__main__": import doctest doctest.testmod() a__ : int = input('''Enter numbers separated by a comma : ''').strip() a__ : Dict = [float(item) for item in user_input.split(''',''')] print(sort(unsorted))
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''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 a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
19
1