code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class A_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str] , snake_case__ : Optional[Any] , snake_case__ : List[str]=13 , snake_case__ : List[str]=7 , snake_case__ : Union[str, Any]=True , snake_case__ : int=True , snake_case__ : List[Any]=True , snake_case__ : List[Any]=True , snake_case__ : Optional[int]=99 , snake_case__ : Any=32 , snake_case__ : Any=5 , snake_case__ : int=4 , snake_case__ : Optional[Any]=37 , snake_case__ : Dict="gelu" , snake_case__ : Tuple=0.1 , snake_case__ : Tuple=0.1 , snake_case__ : int=5_12 , snake_case__ : Optional[Any]=16 , snake_case__ : List[Any]=2 , snake_case__ : Union[str, Any]=0.02 , snake_case__ : List[str]=4 , ): lowercase = parent lowercase = batch_size lowercase = seq_length lowercase = is_training lowercase = use_attention_mask lowercase = use_token_type_ids lowercase = use_labels lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = intermediate_size lowercase = hidden_act lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = type_vocab_size lowercase = type_sequence_label_size lowercase = initializer_range lowercase = num_choices def SCREAMING_SNAKE_CASE__ ( self : List[str] ): lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase = None if self.use_attention_mask: lowercase = random_attention_mask([self.batch_size, self.seq_length] ) lowercase = None if self.use_token_type_ids: lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase = RoFormerConfig( 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=snake_case__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE__ ( self : Any ): lowercase = self.prepare_config_and_inputs() lowercase , lowercase , lowercase , lowercase = config_and_inputs lowercase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class A_ ( __a , unittest.TestCase ): '''simple docstring''' _A :List[Any] = True _A :Union[str, Any] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE__ ( self : int ): lowercase = FlaxRoFormerModelTester(self ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): for model_class_name in self.all_model_classes: lowercase = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=snake_case__ ) lowercase = model(np.ones((1, 1) ) ) self.assertIsNotNone(snake_case__ ) @require_flax class A_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowercase = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) lowercase = jnp.array([[0, 1, 2, 3, 4, 5]] ) lowercase = model(snake_case__ )[0] lowercase = 5_00_00 lowercase = (1, 6, vocab_size) self.assertEqual(output.shape , snake_case__ ) lowercase = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , snake_case__ , atol=1E-4 ) )
703
import math from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : str =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str ={ '''facebook/data2vec-base-960h''': '''https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json''', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class A_ ( __a ): _A :Tuple = '''data2vec-audio''' def __init__( self : Optional[Any] , snake_case__ : List[Any]=32 , snake_case__ : List[Any]=7_68 , snake_case__ : int=12 , snake_case__ : Dict=12 , snake_case__ : List[str]=30_72 , snake_case__ : List[str]="gelu" , snake_case__ : Optional[int]=0.1 , snake_case__ : List[Any]=0.1 , snake_case__ : int=0.1 , snake_case__ : Tuple=0.0 , snake_case__ : Tuple=0.1 , snake_case__ : Any=0.1 , snake_case__ : Dict=0.02 , snake_case__ : List[str]=1E-5 , snake_case__ : Optional[Any]="gelu" , snake_case__ : Union[str, Any]=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , snake_case__ : List[str]=(5, 2, 2, 2, 2, 2, 2) , snake_case__ : str=(10, 3, 3, 3, 3, 2, 2) , snake_case__ : Any=False , snake_case__ : List[str]=16 , snake_case__ : Any=19 , snake_case__ : Optional[Any]=5 , snake_case__ : str=0.05 , snake_case__ : Tuple=10 , snake_case__ : Optional[Any]=2 , snake_case__ : Dict=0.0 , snake_case__ : int=10 , snake_case__ : Any=0 , snake_case__ : int="sum" , snake_case__ : str=False , snake_case__ : str=False , snake_case__ : Optional[int]=2_56 , snake_case__ : List[str]=(5_12, 5_12, 5_12, 5_12, 15_00) , snake_case__ : List[str]=(5, 3, 3, 1, 1) , snake_case__ : int=(1, 2, 3, 1, 1) , snake_case__ : Optional[Any]=5_12 , snake_case__ : Dict=0 , snake_case__ : Optional[Any]=1 , snake_case__ : Tuple=2 , snake_case__ : Tuple=False , snake_case__ : List[str]=3 , snake_case__ : List[str]=2 , snake_case__ : Tuple=3 , snake_case__ : List[str]=None , **snake_case__ : str , ): super().__init__(**snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ ) lowercase = hidden_size lowercase = feat_extract_activation lowercase = list(snake_case__ ) lowercase = list(snake_case__ ) lowercase = list(snake_case__ ) lowercase = conv_bias lowercase = num_conv_pos_embeddings lowercase = num_conv_pos_embedding_groups lowercase = conv_pos_kernel_size lowercase = len(self.conv_dim ) lowercase = num_hidden_layers lowercase = intermediate_size lowercase = hidden_act lowercase = num_attention_heads lowercase = hidden_dropout lowercase = attention_dropout lowercase = activation_dropout lowercase = feat_proj_dropout lowercase = final_dropout lowercase = layerdrop lowercase = layer_norm_eps lowercase = initializer_range lowercase = vocab_size lowercase = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase = mask_time_prob lowercase = mask_time_length lowercase = mask_time_min_masks lowercase = mask_feature_prob lowercase = mask_feature_length lowercase = mask_feature_min_masks # ctc loss lowercase = ctc_loss_reduction lowercase = ctc_zero_infinity # adapter lowercase = add_adapter lowercase = adapter_kernel_size lowercase = adapter_stride lowercase = num_adapter_layers lowercase = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. lowercase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. lowercase = list(snake_case__ ) lowercase = list(snake_case__ ) lowercase = list(snake_case__ ) lowercase = xvector_output_dim @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): return math.prod(self.conv_stride )
72
0
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 __SCREAMING_SNAKE_CASE : List[Any] =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[Any] ={'''vocab_file''': '''spiece.model'''} __SCREAMING_SNAKE_CASE : 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''', } } __SCREAMING_SNAKE_CASE : Any ={ '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) __SCREAMING_SNAKE_CASE : List[str] =0 __SCREAMING_SNAKE_CASE : List[str] =1 __SCREAMING_SNAKE_CASE : Dict =2 __SCREAMING_SNAKE_CASE : List[str] =3 __SCREAMING_SNAKE_CASE : List[Any] =4 class lowercase ( __a ): _A :Optional[Any] = VOCAB_FILES_NAMES _A :int = PRETRAINED_VOCAB_FILES_MAP _A :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A :str = '''left''' def __init__( self : Dict , snake_case__ : int , snake_case__ : Optional[Any]=False , snake_case__ : List[str]=True , snake_case__ : Tuple=False , snake_case__ : int="<s>" , snake_case__ : Tuple="</s>" , snake_case__ : Tuple="<unk>" , snake_case__ : str="<sep>" , snake_case__ : Dict="<pad>" , snake_case__ : int="<cls>" , snake_case__ : Union[str, Any]="<mask>" , snake_case__ : List[Any]=["<eop>", "<eod>"] , snake_case__ : Optional[Dict[str, Any]] = None , **snake_case__ : str , ): # Mask token behave like a normal word, i.e. include the space before it lowercase = AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else mask_token lowercase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=snake_case__ , remove_space=snake_case__ , keep_accents=snake_case__ , bos_token=snake_case__ , eos_token=snake_case__ , unk_token=snake_case__ , sep_token=snake_case__ , pad_token=snake_case__ , cls_token=snake_case__ , mask_token=snake_case__ , additional_special_tokens=snake_case__ , sp_model_kwargs=self.sp_model_kwargs , **snake_case__ , ) lowercase = 3 lowercase = do_lower_case lowercase = remove_space lowercase = keep_accents lowercase = vocab_file lowercase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case__ ) @property def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): return len(self.sp_model ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): lowercase = {self.convert_ids_to_tokens(snake_case__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ): lowercase = self.__dict__.copy() lowercase = None return state def __setstate__( self : Union[str, Any] , snake_case__ : Optional[int] ): lowercase = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowercase = {} lowercase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case__ : List[Any] ): if self.remove_space: lowercase = """ """.join(inputs.strip().split() ) else: lowercase = inputs lowercase = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: lowercase = unicodedata.normalize("""NFKD""" , snake_case__ ) lowercase = """""".join([c for c in outputs if not unicodedata.combining(snake_case__ )] ) if self.do_lower_case: lowercase = outputs.lower() return outputs def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case__ : str ): lowercase = self.preprocess_text(snake_case__ ) lowercase = self.sp_model.encode(snake_case__ , out_type=snake_case__ ) lowercase = [] for piece in pieces: if len(snake_case__ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): lowercase = self.sp_model.EncodeAsPieces(piece[:-1].replace(snake_case__ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowercase = cur_pieces[1:] else: lowercase = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case__ ) else: new_pieces.append(snake_case__ ) return new_pieces def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case__ : int ): return self.sp_model.PieceToId(snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case__ : Optional[Any] ): return self.sp_model.IdToPiece(snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case__ : int ): lowercase = """""".join(snake_case__ ).replace(snake_case__ , """ """ ).strip() return out_string def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case__ : List[int] , snake_case__ : bool = False , snake_case__ : bool = None , snake_case__ : bool = True , **snake_case__ : Optional[int] , ): lowercase = kwargs.pop("""use_source_tokenizer""" , snake_case__ ) lowercase = self.convert_ids_to_tokens(snake_case__ , skip_special_tokens=snake_case__ ) # 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 lowercase = [] lowercase = [] 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(snake_case__ ) ) lowercase = [] sub_texts.append(snake_case__ ) else: current_sub_text.append(snake_case__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case__ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowercase = """""".join(snake_case__ ) lowercase = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowercase = self.clean_up_tokenization(snake_case__ ) return clean_text else: return text def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case__ : List[int] , snake_case__ : Optional[List[int]] = None ): lowercase = [self.sep_token_id] lowercase = [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 SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case__ : List[int] , snake_case__ : Optional[List[int]] = None , snake_case__ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case__ , token_ids_a=snake_case__ , already_has_special_tokens=snake_case__ ) if token_ids_a is not None: return ([0] * len(snake_case__ )) + [1] + ([0] * len(snake_case__ )) + [1, 1] return ([0] * len(snake_case__ )) + [1, 1] def SCREAMING_SNAKE_CASE__ ( self : str , snake_case__ : List[int] , snake_case__ : Optional[List[int]] = None ): lowercase = [self.sep_token_id] lowercase = [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 SCREAMING_SNAKE_CASE__ ( self : Any , snake_case__ : str , snake_case__ : Optional[str] = None ): if not os.path.isdir(snake_case__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowercase = os.path.join( snake_case__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case__ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case__ , """wb""" ) as fi: lowercase = self.sp_model.serialized_model_proto() fi.write(snake_case__ ) return (out_vocab_file,)
704
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = [ """decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(lowerCAmelCase__ ,lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase , lowercase = emb.weight.shape lowercase = nn.Linear(lowerCAmelCase__ ,lowerCAmelCase__ ,bias=lowerCAmelCase__ ) lowercase = emb.weight.data return lin_layer def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = torch.load(lowerCAmelCase__ ,map_location="""cpu""" ) lowercase = Namespace(**checkpoint["""cfg"""]["""model"""] ) lowercase = checkpoint["""model"""] remove_ignore_keys_(lowerCAmelCase__ ) lowercase = state_dict["""decoder.embed_tokens.weight"""].shape[0] lowercase = {key.replace("""decoder""" ,"""model""" ): val for key, val in state_dict.items()} lowercase = XGLMConfig( vocab_size=lowerCAmelCase__ ,max_position_embeddings=args.max_target_positions ,num_layers=args.decoder_layers ,attention_heads=args.decoder_attention_heads ,ffn_dim=args.decoder_ffn_embed_dim ,d_model=args.decoder_embed_dim ,layerdrop=args.decoder_layerdrop ,dropout=args.dropout ,attention_dropout=args.attention_dropout ,activation_dropout=args.activation_dropout ,activation_function="""gelu""" ,scale_embedding=not args.no_scale_embedding ,tie_word_embeddings=args.share_decoder_input_output_embed ,) lowercase = XGLMForCausalLM(lowerCAmelCase__ ) lowercase = model.load_state_dict(lowerCAmelCase__ ,strict=lowerCAmelCase__ ) print(lowerCAmelCase__ ) lowercase = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int =argparse.ArgumentParser() # Required parameters parser.add_argument('''fairseq_path''', type=str, help='''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.''') __SCREAMING_SNAKE_CASE : Optional[Any] =parser.parse_args() __SCREAMING_SNAKE_CASE : Optional[int] =convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
72
0
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : str ={'''configuration_timm_backbone''': ['''TimmBackboneConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : List[Any] =['''TimmBackbone'''] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys __SCREAMING_SNAKE_CASE : Any =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
705
from __future__ import annotations import bisect def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = 0 ,lowerCAmelCase__ = -1 ): if hi < 0: lowercase = len(lowerCAmelCase__ ) while lo < hi: lowercase = lo + (hi - lo) // 2 if sorted_collection[mid] < item: lowercase = mid + 1 else: lowercase = mid return lo def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = 0 ,lowerCAmelCase__ = -1 ): if hi < 0: lowercase = len(lowerCAmelCase__ ) while lo < hi: lowercase = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: lowercase = mid + 1 else: lowercase = mid return lo def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = 0 ,lowerCAmelCase__ = -1 ): sorted_collection.insert(bisect_left(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) ,lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = 0 ,lowerCAmelCase__ = -1 ): sorted_collection.insert(bisect_right(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) ,lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = 0 lowercase = len(lowerCAmelCase__ ) - 1 while left <= right: lowercase = left + (right - left) // 2 lowercase = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: lowercase = midpoint - 1 else: lowercase = midpoint + 1 return None def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = bisect.bisect_left(lowerCAmelCase__ ,lowerCAmelCase__ ) if index != len(lowerCAmelCase__ ) and sorted_collection[index] == item: return index return None def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): if right < left: return None lowercase = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,midpoint - 1 ) else: return binary_search_by_recursion(lowerCAmelCase__ ,lowerCAmelCase__ ,midpoint + 1 ,lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] =input('''Enter numbers separated by comma:\n''').strip() __SCREAMING_SNAKE_CASE : Tuple =sorted(int(item) for item in user_input.split(''',''')) __SCREAMING_SNAKE_CASE : Tuple =int(input('''Enter a single number to be found in the list:\n''')) __SCREAMING_SNAKE_CASE : Union[str, Any] =binary_search(collection, target) if result is None: print(f'''{target} was not found in {collection}.''') else: print(f'''{target} was found at position {result} in {collection}.''')
72
0
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
706
# This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = multiprocessing.Manager() lowercase = manager.list() lowercase = multiprocessing.Process(target=lowerCAmelCase__ ,args=(check_program, result, timeout) ) p.start() p.join(timeout=timeout + 1 ) if p.is_alive(): p.kill() if not result: result.append("""timed out""" ) return { "task_id": task_id, "passed": result[0] == "passed", "result": result[0], "completion_id": completion_id, } def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): with create_tempdir(): # These system calls are needed when cleaning up tempdir. import os import shutil lowercase = shutil.rmtree lowercase = os.rmdir lowercase = os.chdir # Disable functionalities that can make destructive changes to the test. reliability_guard() # Run program. try: lowercase = {} with swallow_io(): with time_limit(lowerCAmelCase__ ): exec(lowerCAmelCase__ ,lowerCAmelCase__ ) result.append("""passed""" ) except TimeoutException: result.append("""timed out""" ) except BaseException as e: result.append(f"""failed: {e}""" ) # Needed for cleaning up. lowercase = rmtree lowercase = rmdir lowercase = chdir @contextlib.contextmanager def UpperCamelCase__ ( lowerCAmelCase__ ): def signal_handler(lowerCAmelCase__ ,lowerCAmelCase__ ): raise TimeoutException("""Timed out!""" ) signal.setitimer(signal.ITIMER_REAL ,lowerCAmelCase__ ) signal.signal(signal.SIGALRM ,lowerCAmelCase__ ) try: yield finally: signal.setitimer(signal.ITIMER_REAL ,0 ) @contextlib.contextmanager def UpperCamelCase__ ( ): lowercase = WriteOnlyStringIO() with contextlib.redirect_stdout(lowerCAmelCase__ ): with contextlib.redirect_stderr(lowerCAmelCase__ ): with redirect_stdin(lowerCAmelCase__ ): yield @contextlib.contextmanager def UpperCamelCase__ ( ): with tempfile.TemporaryDirectory() as dirname: with chdir(lowerCAmelCase__ ): yield dirname class A_ ( __a ): pass class A_ ( io.StringIO ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , *snake_case__ : int , **snake_case__ : int ): raise OSError def SCREAMING_SNAKE_CASE__ ( self : int , *snake_case__ : Optional[Any] , **snake_case__ : int ): raise OSError def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , *snake_case__ : List[Any] , **snake_case__ : Optional[Any] ): raise OSError def SCREAMING_SNAKE_CASE__ ( self : Dict , *snake_case__ : int , **snake_case__ : Any ): return False class A_ ( contextlib._RedirectStream ): # type: ignore _A :List[Any] = '''stdin''' @contextlib.contextmanager def UpperCamelCase__ ( lowerCAmelCase__ ): if root == ".": yield return lowercase = os.getcwd() os.chdir(lowerCAmelCase__ ) try: yield except BaseException as exc: raise exc finally: os.chdir(lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__=None ): if maximum_memory_bytes is not None: import resource resource.setrlimit(resource.RLIMIT_AS ,(maximum_memory_bytes, maximum_memory_bytes) ) resource.setrlimit(resource.RLIMIT_DATA ,(maximum_memory_bytes, maximum_memory_bytes) ) if not platform.uname().system == "Darwin": resource.setrlimit(resource.RLIMIT_STACK ,(maximum_memory_bytes, maximum_memory_bytes) ) faulthandler.disable() import builtins lowercase = None lowercase = None import os lowercase = """1""" lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None import shutil lowercase = None lowercase = None lowercase = None import subprocess lowercase = None # type: ignore lowercase = None import sys lowercase = None lowercase = None lowercase = None lowercase = None lowercase = None
72
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __SCREAMING_SNAKE_CASE : Union[str, Any] =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int ={ '''microsoft/swin-tiny-patch4-window7-224''': ( '''https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json''' ), # See all Swin models at https://huggingface.co/models?filter=swin } class A_ ( __a , __a ): _A :List[str] = '''swin''' _A :str = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : int , snake_case__ : List[Any]=2_24 , snake_case__ : List[str]=4 , snake_case__ : Optional[Any]=3 , snake_case__ : Optional[Any]=96 , snake_case__ : int=[2, 2, 6, 2] , snake_case__ : Any=[3, 6, 12, 24] , snake_case__ : str=7 , snake_case__ : List[Any]=4.0 , snake_case__ : int=True , snake_case__ : Optional[Any]=0.0 , snake_case__ : Dict=0.0 , snake_case__ : Tuple=0.1 , snake_case__ : List[Any]="gelu" , snake_case__ : List[Any]=False , snake_case__ : Tuple=0.02 , snake_case__ : Union[str, Any]=1E-5 , snake_case__ : str=32 , snake_case__ : Tuple=None , snake_case__ : Any=None , **snake_case__ : Optional[int] , ): super().__init__(**snake_case__ ) lowercase = image_size lowercase = patch_size lowercase = num_channels lowercase = embed_dim lowercase = depths lowercase = len(snake_case__ ) lowercase = num_heads lowercase = window_size lowercase = mlp_ratio lowercase = qkv_bias lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = drop_path_rate lowercase = hidden_act lowercase = use_absolute_embeddings lowercase = layer_norm_eps lowercase = initializer_range lowercase = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase = int(embed_dim * 2 ** (len(snake_case__ ) - 1) ) lowercase = ["""stem"""] + [F"""stage{idx}""" for idx in range(1 , len(snake_case__ ) + 1 )] lowercase , lowercase = get_aligned_output_features_output_indices( out_features=snake_case__ , out_indices=snake_case__ , stage_names=self.stage_names ) class A_ ( __a ): _A :Dict = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): return 1E-4
707
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( __a ): _A :Optional[int] = ['''image_processor''', '''tokenizer'''] _A :Tuple = '''BlipImageProcessor''' _A :List[Any] = '''AutoTokenizer''' def __init__( self : List[Any] , snake_case__ : Any , snake_case__ : Dict ): lowercase = False super().__init__(snake_case__ , snake_case__ ) lowercase = self.image_processor def __call__( self : List[str] , snake_case__ : ImageInput = None , snake_case__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , snake_case__ : bool = True , snake_case__ : Union[bool, str, PaddingStrategy] = False , snake_case__ : Union[bool, str, TruncationStrategy] = None , snake_case__ : Optional[int] = None , snake_case__ : int = 0 , snake_case__ : Optional[int] = None , snake_case__ : Optional[bool] = None , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = True , snake_case__ : Optional[Union[str, TensorType]] = None , **snake_case__ : str , ): if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: lowercase = self.tokenizer lowercase = self.tokenizer( text=snake_case__ , add_special_tokens=snake_case__ , padding=snake_case__ , truncation=snake_case__ , max_length=snake_case__ , stride=snake_case__ , pad_to_multiple_of=snake_case__ , return_attention_mask=snake_case__ , return_overflowing_tokens=snake_case__ , return_special_tokens_mask=snake_case__ , return_offsets_mapping=snake_case__ , return_token_type_ids=snake_case__ , return_length=snake_case__ , verbose=snake_case__ , return_tensors=snake_case__ , **snake_case__ , ) return text_encoding # add pixel_values lowercase = self.image_processor(snake_case__ , return_tensors=snake_case__ ) if text is not None: lowercase = self.tokenizer( text=snake_case__ , add_special_tokens=snake_case__ , padding=snake_case__ , truncation=snake_case__ , max_length=snake_case__ , stride=snake_case__ , pad_to_multiple_of=snake_case__ , return_attention_mask=snake_case__ , return_overflowing_tokens=snake_case__ , return_special_tokens_mask=snake_case__ , return_offsets_mapping=snake_case__ , return_token_type_ids=snake_case__ , return_length=snake_case__ , verbose=snake_case__ , return_tensors=snake_case__ , **snake_case__ , ) else: lowercase = None if text_encoding is not None: encoding_image_processor.update(snake_case__ ) return encoding_image_processor def SCREAMING_SNAKE_CASE__ ( self : Dict , *snake_case__ : int , **snake_case__ : List[str] ): return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : str , *snake_case__ : int , **snake_case__ : int ): return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def SCREAMING_SNAKE_CASE__ ( self : List[str] ): lowercase = self.tokenizer.model_input_names lowercase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
72
0
def UpperCamelCase__ ( lowerCAmelCase__ ): '''simple docstring''' if not numbers: return 0 if not isinstance(lowerCAmelCase__ ,(list, tuple) ) or not all( isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) lowercase = lowercase = lowercase = numbers[0] for i in range(1 ,len(lowerCAmelCase__ ) ): # update the maximum and minimum subarray products lowercase = numbers[i] if number < 0: lowercase , lowercase = min_till_now, max_till_now lowercase = max(lowerCAmelCase__ ,max_till_now * number ) lowercase = min(lowerCAmelCase__ ,min_till_now * number ) # update the maximum product found till now lowercase = max(lowerCAmelCase__ ,lowerCAmelCase__ ) return max_prod
708
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __SCREAMING_SNAKE_CASE : List[str] =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Any =OrderedDict( [ ('''audio-spectrogram-transformer''', '''ASTFeatureExtractor'''), ('''beit''', '''BeitFeatureExtractor'''), ('''chinese_clip''', '''ChineseCLIPFeatureExtractor'''), ('''clap''', '''ClapFeatureExtractor'''), ('''clip''', '''CLIPFeatureExtractor'''), ('''clipseg''', '''ViTFeatureExtractor'''), ('''conditional_detr''', '''ConditionalDetrFeatureExtractor'''), ('''convnext''', '''ConvNextFeatureExtractor'''), ('''cvt''', '''ConvNextFeatureExtractor'''), ('''data2vec-audio''', '''Wav2Vec2FeatureExtractor'''), ('''data2vec-vision''', '''BeitFeatureExtractor'''), ('''deformable_detr''', '''DeformableDetrFeatureExtractor'''), ('''deit''', '''DeiTFeatureExtractor'''), ('''detr''', '''DetrFeatureExtractor'''), ('''dinat''', '''ViTFeatureExtractor'''), ('''donut-swin''', '''DonutFeatureExtractor'''), ('''dpt''', '''DPTFeatureExtractor'''), ('''encodec''', '''EncodecFeatureExtractor'''), ('''flava''', '''FlavaFeatureExtractor'''), ('''glpn''', '''GLPNFeatureExtractor'''), ('''groupvit''', '''CLIPFeatureExtractor'''), ('''hubert''', '''Wav2Vec2FeatureExtractor'''), ('''imagegpt''', '''ImageGPTFeatureExtractor'''), ('''layoutlmv2''', '''LayoutLMv2FeatureExtractor'''), ('''layoutlmv3''', '''LayoutLMv3FeatureExtractor'''), ('''levit''', '''LevitFeatureExtractor'''), ('''maskformer''', '''MaskFormerFeatureExtractor'''), ('''mctct''', '''MCTCTFeatureExtractor'''), ('''mobilenet_v1''', '''MobileNetV1FeatureExtractor'''), ('''mobilenet_v2''', '''MobileNetV2FeatureExtractor'''), ('''mobilevit''', '''MobileViTFeatureExtractor'''), ('''nat''', '''ViTFeatureExtractor'''), ('''owlvit''', '''OwlViTFeatureExtractor'''), ('''perceiver''', '''PerceiverFeatureExtractor'''), ('''poolformer''', '''PoolFormerFeatureExtractor'''), ('''regnet''', '''ConvNextFeatureExtractor'''), ('''resnet''', '''ConvNextFeatureExtractor'''), ('''segformer''', '''SegformerFeatureExtractor'''), ('''sew''', '''Wav2Vec2FeatureExtractor'''), ('''sew-d''', '''Wav2Vec2FeatureExtractor'''), ('''speech_to_text''', '''Speech2TextFeatureExtractor'''), ('''speecht5''', '''SpeechT5FeatureExtractor'''), ('''swiftformer''', '''ViTFeatureExtractor'''), ('''swin''', '''ViTFeatureExtractor'''), ('''swinv2''', '''ViTFeatureExtractor'''), ('''table-transformer''', '''DetrFeatureExtractor'''), ('''timesformer''', '''VideoMAEFeatureExtractor'''), ('''tvlt''', '''TvltFeatureExtractor'''), ('''unispeech''', '''Wav2Vec2FeatureExtractor'''), ('''unispeech-sat''', '''Wav2Vec2FeatureExtractor'''), ('''van''', '''ConvNextFeatureExtractor'''), ('''videomae''', '''VideoMAEFeatureExtractor'''), ('''vilt''', '''ViltFeatureExtractor'''), ('''vit''', '''ViTFeatureExtractor'''), ('''vit_mae''', '''ViTFeatureExtractor'''), ('''vit_msn''', '''ViTFeatureExtractor'''), ('''wav2vec2''', '''Wav2Vec2FeatureExtractor'''), ('''wav2vec2-conformer''', '''Wav2Vec2FeatureExtractor'''), ('''wavlm''', '''Wav2Vec2FeatureExtractor'''), ('''whisper''', '''WhisperFeatureExtractor'''), ('''xclip''', '''CLIPFeatureExtractor'''), ('''yolos''', '''YolosFeatureExtractor'''), ] ) __SCREAMING_SNAKE_CASE : Tuple =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def UpperCamelCase__ ( lowerCAmelCase__ ): for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: lowercase = model_type_to_module_name(lowerCAmelCase__ ) lowercase = importlib.import_module(f""".{module_name}""" ,"""transformers.models""" ) try: return getattr(lowerCAmelCase__ ,lowerCAmelCase__ ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(lowerCAmelCase__ ,"""__name__""" ,lowerCAmelCase__ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. lowercase = importlib.import_module("""transformers""" ) if hasattr(lowerCAmelCase__ ,lowerCAmelCase__ ): return getattr(lowerCAmelCase__ ,lowerCAmelCase__ ) return None def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ = None ,lowerCAmelCase__ = False ,lowerCAmelCase__ = False ,lowerCAmelCase__ = None ,lowerCAmelCase__ = None ,lowerCAmelCase__ = None ,lowerCAmelCase__ = False ,**lowerCAmelCase__ ,): lowercase = get_file_from_repo( lowerCAmelCase__ ,lowerCAmelCase__ ,cache_dir=lowerCAmelCase__ ,force_download=lowerCAmelCase__ ,resume_download=lowerCAmelCase__ ,proxies=lowerCAmelCase__ ,use_auth_token=lowerCAmelCase__ ,revision=lowerCAmelCase__ ,local_files_only=lowerCAmelCase__ ,) if resolved_config_file is None: logger.info( """Could not locate the feature extractor configuration file, will try to use the model config instead.""" ) return {} with open(lowerCAmelCase__ ,encoding="""utf-8""" ) as reader: return json.load(lowerCAmelCase__ ) class A_ : def __init__( self : List[Any] ): raise EnvironmentError( """AutoFeatureExtractor is designed to be instantiated """ """using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.""" ) @classmethod @replace_list_option_in_docstrings(snake_case__ ) def SCREAMING_SNAKE_CASE__ ( cls : Dict , snake_case__ : Tuple , **snake_case__ : int ): lowercase = kwargs.pop("""config""" , snake_case__ ) lowercase = kwargs.pop("""trust_remote_code""" , snake_case__ ) lowercase = True lowercase , lowercase = FeatureExtractionMixin.get_feature_extractor_dict(snake_case__ , **snake_case__ ) lowercase = config_dict.get("""feature_extractor_type""" , snake_case__ ) lowercase = None if "AutoFeatureExtractor" in config_dict.get("""auto_map""" , {} ): lowercase = config_dict["""auto_map"""]["""AutoFeatureExtractor"""] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(snake_case__ , snake_case__ ): lowercase = AutoConfig.from_pretrained(snake_case__ , **snake_case__ ) # It could be in `config.feature_extractor_type`` lowercase = getattr(snake_case__ , """feature_extractor_type""" , snake_case__ ) if hasattr(snake_case__ , """auto_map""" ) and "AutoFeatureExtractor" in config.auto_map: lowercase = config.auto_map["""AutoFeatureExtractor"""] if feature_extractor_class is not None: lowercase = feature_extractor_class_from_name(snake_case__ ) lowercase = feature_extractor_auto_map is not None lowercase = feature_extractor_class is not None or type(snake_case__ ) in FEATURE_EXTRACTOR_MAPPING lowercase = resolve_trust_remote_code( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) if has_remote_code and trust_remote_code: lowercase = get_class_from_dynamic_module( snake_case__ , snake_case__ , **snake_case__ ) lowercase = kwargs.pop("""code_revision""" , snake_case__ ) if os.path.isdir(snake_case__ ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(snake_case__ , **snake_case__ ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(snake_case__ , **snake_case__ ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(snake_case__ ) in FEATURE_EXTRACTOR_MAPPING: lowercase = FEATURE_EXTRACTOR_MAPPING[type(snake_case__ )] return feature_extractor_class.from_dict(snake_case__ , **snake_case__ ) raise ValueError( F"""Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a """ F"""`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case__ : Optional[int] , snake_case__ : List[str] ): FEATURE_EXTRACTOR_MAPPING.register(snake_case__ , snake_case__ )
72
0
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = args.pruning_method lowercase = args.threshold lowercase = args.model_name_or_path.rstrip("""/""" ) lowercase = args.target_model_path print(f"""Load fine-pruned model from {model_name_or_path}""" ) lowercase = torch.load(os.path.join(lowerCAmelCase__ ,"""pytorch_model.bin""" ) ) lowercase = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: lowercase = tensor print(f"""Copied layer {name}""" ) elif "classifier" in name or "qa_output" in name: lowercase = tensor print(f"""Copied layer {name}""" ) elif "bias" in name: lowercase = tensor print(f"""Copied layer {name}""" ) else: if pruning_method == "magnitude": lowercase = MagnitudeBinarizer.apply(inputs=lowerCAmelCase__ ,threshold=lowerCAmelCase__ ) lowercase = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "topK": if "mask_scores" in name: continue lowercase = name[:-6] lowercase = model[f"""{prefix_}mask_scores"""] lowercase = TopKBinarizer.apply(lowerCAmelCase__ ,lowerCAmelCase__ ) lowercase = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue lowercase = name[:-6] lowercase = model[f"""{prefix_}mask_scores"""] lowercase = ThresholdBinarizer.apply(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) lowercase = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "l0": if "mask_scores" in name: continue lowercase = name[:-6] lowercase = model[f"""{prefix_}mask_scores"""] lowercase , lowercase = -0.1, 1.1 lowercase = torch.sigmoid(lowerCAmelCase__ ) lowercase = s * (r - l) + l lowercase = s_bar.clamp(min=0.0 ,max=1.0 ) lowercase = tensor * mask print(f"""Pruned layer {name}""" ) else: raise ValueError("""Unknown pruning method""" ) if target_model_path is None: lowercase = os.path.join( os.path.dirname(lowerCAmelCase__ ) ,f"""bertarized_{os.path.basename(lowerCAmelCase__ )}""" ) if not os.path.isdir(lowerCAmelCase__ ): shutil.copytree(lowerCAmelCase__ ,lowerCAmelCase__ ) print(f"""\nCreated folder {target_model_path}""" ) torch.save(lowerCAmelCase__ ,os.path.join(lowerCAmelCase__ ,"""pytorch_model.bin""" ) ) print("""\nPruned model saved! See you later!""" ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] =argparse.ArgumentParser() parser.add_argument( '''--pruning_method''', choices=['''l0''', '''magnitude''', '''topK''', '''sigmoied_threshold'''], type=str, required=True, help=( '''Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,''' ''' sigmoied_threshold = Soft movement pruning)''' ), ) parser.add_argument( '''--threshold''', type=float, required=False, help=( '''For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.''' '''For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.''' '''Not needed for `l0`''' ), ) parser.add_argument( '''--model_name_or_path''', type=str, required=True, help='''Folder containing the model that was previously fine-pruned''', ) parser.add_argument( '''--target_model_path''', default=None, type=str, required=False, help='''Folder containing the model that was previously fine-pruned''', ) __SCREAMING_SNAKE_CASE : str =parser.parse_args() main(args)
709
import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Any =logging.get_logger('''transformers.models.speecht5''') __SCREAMING_SNAKE_CASE : Optional[Any] ={ '''speech_encoder_prenet.layer_norm''': '''speecht5.encoder.prenet.feature_projection.layer_norm''', '''speech_encoder_prenet.post_extract_proj''': '''speecht5.encoder.prenet.feature_projection.projection''', '''speech_encoder_prenet.pos_conv.0''': '''speecht5.encoder.prenet.pos_conv_embed.conv''', '''speech_encoder_prenet.mask_emb''': '''speecht5.encoder.prenet.masked_spec_embed''', } __SCREAMING_SNAKE_CASE : Union[str, Any] ={ '''text_encoder_prenet.encoder_prenet.0''': '''speecht5.encoder.prenet.embed_tokens''', '''text_encoder_prenet.encoder_prenet.1.alpha''': '''speecht5.encoder.prenet.encode_positions.alpha''', } __SCREAMING_SNAKE_CASE : Optional[int] ={ '''speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0''': '''speecht5.decoder.prenet.layers.0''', '''speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0''': '''speecht5.decoder.prenet.layers.1''', '''speech_decoder_prenet.decoder_prenet.0.1''': '''speecht5.decoder.prenet.final_layer''', '''speech_decoder_prenet.decoder_prenet.1.alpha''': '''speecht5.decoder.prenet.encode_positions.alpha''', '''speech_decoder_prenet.spkembs_layer.0''': '''speecht5.decoder.prenet.speaker_embeds_layer''', } __SCREAMING_SNAKE_CASE : List[Any] ={ '''speech_decoder_postnet.feat_out''': '''speech_decoder_postnet.feat_out''', '''speech_decoder_postnet.prob_out''': '''speech_decoder_postnet.prob_out''', '''speech_decoder_postnet.postnet.postnet.0.0''': '''speech_decoder_postnet.layers.0.conv''', '''speech_decoder_postnet.postnet.postnet.0.1''': '''speech_decoder_postnet.layers.0.batch_norm''', '''speech_decoder_postnet.postnet.postnet.1.0''': '''speech_decoder_postnet.layers.1.conv''', '''speech_decoder_postnet.postnet.postnet.1.1''': '''speech_decoder_postnet.layers.1.batch_norm''', '''speech_decoder_postnet.postnet.postnet.2.0''': '''speech_decoder_postnet.layers.2.conv''', '''speech_decoder_postnet.postnet.postnet.2.1''': '''speech_decoder_postnet.layers.2.batch_norm''', '''speech_decoder_postnet.postnet.postnet.3.0''': '''speech_decoder_postnet.layers.3.conv''', '''speech_decoder_postnet.postnet.postnet.3.1''': '''speech_decoder_postnet.layers.3.batch_norm''', '''speech_decoder_postnet.postnet.postnet.4.0''': '''speech_decoder_postnet.layers.4.conv''', '''speech_decoder_postnet.postnet.postnet.4.1''': '''speech_decoder_postnet.layers.4.batch_norm''', } __SCREAMING_SNAKE_CASE : List[Any] ={ '''text_decoder_prenet.embed_tokens''': '''speecht5.decoder.prenet.embed_tokens''', } __SCREAMING_SNAKE_CASE : Optional[Any] ={ '''text_decoder_postnet.output_projection''': '''text_decoder_postnet.lm_head''', } __SCREAMING_SNAKE_CASE : Optional[int] ={ '''encoder.layers.*.self_attn.k_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj''', '''encoder.layers.*.self_attn.v_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj''', '''encoder.layers.*.self_attn.q_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj''', '''encoder.layers.*.self_attn.out_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj''', '''encoder.layers.*.self_attn_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.layer_norm''', '''encoder.layers.*.fc1''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense''', '''encoder.layers.*.fc2''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense''', '''encoder.layers.*.final_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''speecht5.encoder.wrapped_encoder.layer_norm''', '''encoder.pos_emb.pe_k''': '''speecht5.encoder.wrapped_encoder.embed_positions.pe_k''', } __SCREAMING_SNAKE_CASE : List[Any] ={ '''decoder.layers.*.self_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj''', '''decoder.layers.*.self_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj''', '''decoder.layers.*.self_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj''', '''decoder.layers.*.self_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj''', '''decoder.layers.*.self_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm''', '''decoder.layers.*.encoder_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj''', '''decoder.layers.*.encoder_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj''', '''decoder.layers.*.encoder_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj''', '''decoder.layers.*.encoder_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj''', '''decoder.layers.*.encoder_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm''', '''decoder.layers.*.fc1''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense''', '''decoder.layers.*.fc2''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense''', '''decoder.layers.*.final_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm''', } __SCREAMING_SNAKE_CASE : List[Any] ={ **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_TEXT_DECODER_PRENET, **MAPPING_TEXT_DECODER_POSTNET, } __SCREAMING_SNAKE_CASE : List[str] ={ **MAPPING_TEXT_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } __SCREAMING_SNAKE_CASE : Optional[int] ={ **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } __SCREAMING_SNAKE_CASE : Dict =[] __SCREAMING_SNAKE_CASE : List[str] =[ '''encoder.version''', '''encoder.layers.*.norm_k.weight''', '''encoder.layers.*.norm_k.bias''', '''decoder.version''', '''decoder.layers.*.norm_k.weight''', '''decoder.layers.*.norm_k.bias''', '''decoder.pos_emb.pe_k''', '''speech_encoder_prenet.embed_positions._float_tensor''', '''text_decoder_prenet.embed_positions._float_tensor''', ] __SCREAMING_SNAKE_CASE : List[str] =IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''speech_decoder_prenet.*''', '''speech_decoder_postnet.*''', ] __SCREAMING_SNAKE_CASE : Any =IGNORE_KEYS + [ '''encoder.proj''', '''speech_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] __SCREAMING_SNAKE_CASE : Any =IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): for attribute in key.split(""".""" ): lowercase = getattr(lowerCAmelCase__ ,lowerCAmelCase__ ) if weight_type is not None: lowercase = getattr(lowerCAmelCase__ ,lowerCAmelCase__ ).shape else: lowercase = 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": lowercase = value elif weight_type == "weight_g": lowercase = value elif weight_type == "weight_v": lowercase = value elif weight_type == "bias": lowercase = value elif weight_type == "running_mean": lowercase = value elif weight_type == "running_var": lowercase = value elif weight_type == "num_batches_tracked": lowercase = value else: lowercase = value logger.info(f"""{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.""" ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): for key in ignore_keys: if key.endswith(""".*""" ): if name.startswith(key[:-1] ): return True elif ".*." in key: lowercase , lowercase = key.split(""".*.""" ) if prefix in name and suffix in name: return True elif key in name: return True return False def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = [] if task == "s2t": lowercase = hf_model.speechta.encoder.prenet.feature_encoder lowercase = MAPPING_S2T lowercase = IGNORE_KEYS_S2T elif task == "t2s": lowercase = None lowercase = MAPPING_T2S lowercase = IGNORE_KEYS_T2S elif task == "s2s": lowercase = hf_model.speechta.encoder.prenet.feature_encoder lowercase = MAPPING_S2S lowercase = IGNORE_KEYS_S2S else: raise ValueError(f"""Unsupported task: {task}""" ) for name, value in fairseq_dict.items(): if should_ignore(lowerCAmelCase__ ,lowerCAmelCase__ ): logger.info(f"""{name} was ignored""" ) continue lowercase = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,hf_model.config.feat_extract_norm == """group""" ,) lowercase = True else: for key, mapped_key in MAPPING.items(): # mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if "*" in key: lowercase , lowercase = key.split(""".*.""" ) if prefix in name and suffix in name: lowercase = suffix # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: if key in name: lowercase = True if "*" in mapped_key: lowercase = name.split(lowerCAmelCase__ )[0].split(""".""" )[-2] lowercase = mapped_key.replace("""*""" ,lowerCAmelCase__ ) if "weight_g" in name: lowercase = """weight_g""" elif "weight_v" in name: lowercase = """weight_v""" elif "bias" in name: lowercase = """bias""" elif "weight" in name: lowercase = """weight""" elif "running_mean" in name: lowercase = """running_mean""" elif "running_var" in name: lowercase = """running_var""" elif "num_batches_tracked" in name: lowercase = """num_batches_tracked""" else: lowercase = None set_recursively(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) continue if not is_used: unused_weights.append(lowerCAmelCase__ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = full_name.split("""conv_layers.""" )[-1] lowercase = name.split(""".""" ) lowercase = int(items[0] ) lowercase = 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.""" ) lowercase = 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.""" ) lowercase = 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.""" ) lowercase = 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.""" ) lowercase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(lowerCAmelCase__ ) @torch.no_grad() def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=None ,lowerCAmelCase__=None ,lowerCAmelCase__=None ,): if config_path is not None: lowercase = SpeechTaConfig.from_pretrained(lowerCAmelCase__ ) else: lowercase = SpeechTaConfig() if task == "s2t": lowercase = config.max_text_positions lowercase = SpeechTaForSpeechToText(lowerCAmelCase__ ) elif task == "t2s": lowercase = 1_876 lowercase = 600 lowercase = config.max_speech_positions lowercase = SpeechTaForTextToSpeech(lowerCAmelCase__ ) elif task == "s2s": lowercase = 1_876 lowercase = config.max_speech_positions lowercase = SpeechTaForSpeechToSpeech(lowerCAmelCase__ ) else: raise ValueError(f"""Unknown task name: {task}""" ) if vocab_path: lowercase = SpeechTaTokenizer(lowerCAmelCase__ ,model_max_length=config.max_text_positions ) # Mask token behaves like a normal word, i.e. include the space before it lowercase = AddedToken("""<mask>""" ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) lowercase = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) lowercase = SpeechTaFeatureExtractor() lowercase = SpeechTaProcessor(tokenizer=lowerCAmelCase__ ,feature_extractor=lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) lowercase = torch.load(lowerCAmelCase__ ) recursively_load_weights(fairseq_checkpoint["""model"""] ,lowerCAmelCase__ ,lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) if repo_id: print("""Pushing to the hub...""" ) processor.push_to_hub(lowerCAmelCase__ ) model.push_to_hub(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Optional[Any] =argparse.ArgumentParser() parser.add_argument( '''--task''', default='''s2t''', type=str, help='''Type of the SpeechT5 model you\'d like to convert. Should be one of \'s2t\', \'t2s\', \'s2s\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--vocab_path''', default=None, type=str, help='''Path to SentencePiece model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) __SCREAMING_SNAKE_CASE : Optional[Any] =parser.parse_args() convert_speechta_checkpoint( args.task, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.vocab_path, args.push_to_hub, )
72
0
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__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = 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}}""" ) lowercase = DatasetInfosDict.from_directory(lowerCAmelCase__ ) 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__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = str(lowerCAmelCase__ ) dataset_info.write_to_directory(lowerCAmelCase__ ) lowercase = DatasetInfo.from_directory(lowerCAmelCase__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowerCAmelCase__ ,"""dataset_info.json""" ) ) def UpperCamelCase__ ( ): lowercase = 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 ,) lowercase = dataset_info._to_yaml_dict() assert sorted(lowerCAmelCase__ ) == 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) ) lowercase = yaml.safe_dump(lowerCAmelCase__ ) lowercase = yaml.safe_load(lowerCAmelCase__ ) assert dataset_info_yaml_dict == reloaded def UpperCamelCase__ ( ): lowercase = DatasetInfo() lowercase = 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__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = str(lowerCAmelCase__ ) dataset_infos_dict.write_to_directory(lowerCAmelCase__ ) lowercase = DatasetInfosDict.from_directory(lowerCAmelCase__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): lowercase = 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 lowercase = 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(lowerCAmelCase__ ,"""README.md""" ) )
710
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py __SCREAMING_SNAKE_CASE : List[Any] ='''.''' if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] =os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') __SCREAMING_SNAKE_CASE : Dict =[] __SCREAMING_SNAKE_CASE : Dict =[] with open(doctest_file_path) as fp: for line in fp: __SCREAMING_SNAKE_CASE : Optional[Any] =line.strip() __SCREAMING_SNAKE_CASE : Tuple =os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: __SCREAMING_SNAKE_CASE : Optional[Any] ='''\n'''.join(non_existent_paths) raise ValueError(f'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''') if all_paths != sorted(all_paths): raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')
72
0
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class A_ ( __a ): def SCREAMING_SNAKE_CASE__ ( self : str ): lowercase = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): with self.assertRaises(snake_case__ ): lowercase = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): with self.assertRaises(snake_case__ ): lowercase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): lowercase = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def SCREAMING_SNAKE_CASE__ ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): lowercase = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): lowercase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): lowercase = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def SCREAMING_SNAKE_CASE__ ( self : str ): lowercase = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): lowercase = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): lowercase = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): lowercase = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def SCREAMING_SNAKE_CASE__ ( self : Tuple ): import PIL.Image lowercase = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=snake_case__ ) as mock_cast_to_python_objects: lowercase = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) lowercase , lowercase = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , snake_case__ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = pa.BufferReader(lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,pa.Buffer ) else pa.memory_map(lowerCAmelCase__ ) lowercase = pa.ipc.open_stream(lowerCAmelCase__ ) lowercase = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 10] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = pa.BufferOutputStream() lowercase = pa.schema(lowerCAmelCase__ ) if fields else None with ArrowWriter(stream=lowerCAmelCase__ ,schema=lowerCAmelCase__ ,writer_batch_size=lowerCAmelCase__ ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: lowercase = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase__ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def UpperCamelCase__ ( ): lowercase = pa.BufferOutputStream() lowercase = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=lowerCAmelCase__ ,features=lowerCAmelCase__ ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata lowercase = pa.BufferReader(output.getvalue() ) lowercase = pa.ipc.open_stream(lowerCAmelCase__ ) lowercase = f.read_all() lowercase = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCAmelCase__ ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 10] ) def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase__ ,writer_batch_size=lowerCAmelCase__ ,hash_salt="""split_name""" ,check_duplicates=lowerCAmelCase__ ,) as writer: with pytest.raises(lowerCAmelCase__ ): writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=[1, 2] ) lowercase , lowercase = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" ,[None, 2, 10] ) def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase__ ,writer_batch_size=lowerCAmelCase__ ,hash_salt="""split_name""" ,check_duplicates=lowerCAmelCase__ ,) as writer: with pytest.raises(lowerCAmelCase__ ): writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} ,key=10 ) lowercase , lowercase = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" ,[None, 2, 10] ) def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase__ ,writer_batch_size=lowerCAmelCase__ ,hash_salt="""split_name""" ,check_duplicates=lowerCAmelCase__ ,) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} ,key=2 ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 10] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = pa.BufferOutputStream() lowercase = pa.schema(lowerCAmelCase__ ) if fields else None with ArrowWriter(stream=lowerCAmelCase__ ,schema=lowerCAmelCase__ ,writer_batch_size=lowerCAmelCase__ ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: lowercase = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase__ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 10] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = pa.BufferOutputStream() lowercase = pa.schema(lowerCAmelCase__ ) if fields else None with ArrowWriter(stream=lowerCAmelCase__ ,schema=lowerCAmelCase__ ,writer_batch_size=lowerCAmelCase__ ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: lowercase = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase__ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 10] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = pa.BufferOutputStream() lowercase = pa.schema(lowerCAmelCase__ ) if fields else None with ArrowWriter(stream=lowerCAmelCase__ ,schema=lowerCAmelCase__ ,writer_batch_size=lowerCAmelCase__ ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: lowercase = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase__ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def UpperCamelCase__ ( ): with tempfile.TemporaryDirectory() as tmp_dir: lowercase = {"""col_1""": pa.string(), """col_2""": pa.intaa()} lowercase = os.path.join(lowerCAmelCase__ ,"""test.arrow""" ) with ArrowWriter(path=lowerCAmelCase__ ,schema=pa.schema(lowerCAmelCase__ ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase__ ,metadata=writer._schema.metadata ) _check_output(lowerCAmelCase__ ,1 ) def UpperCamelCase__ ( lowerCAmelCase__ ): if pa.types.is_list(lowerCAmelCase__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): if isinstance(lst[0] ,lowerCAmelCase__ ): change_first_primitive_element_in_list(lst[0] ,lowerCAmelCase__ ) else: lowercase = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" ,[(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" ,[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = pa.array(TypedSequence(lowerCAmelCase__ ,optimized_int_type=lowerCAmelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" ,[ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] ,) @pytest.mark.parametrize("""sequence""" ,[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): # in range lowercase = pa.array(OptimizedTypedSequence(lowerCAmelCase__ ,col=lowerCAmelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications lowercase = copy.deepcopy(lowerCAmelCase__ ) lowercase = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase__ ,lowerCAmelCase__ ) lowercase = pa.array(OptimizedTypedSequence(lowerCAmelCase__ ,col=lowerCAmelCase__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" ,[False, True] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=lowerCAmelCase__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = """mock://dataset-train.arrow""" with ArrowWriter(path=lowerCAmelCase__ ,storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs ,type(lowerCAmelCase__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase__ ) def UpperCamelCase__ ( ): lowercase = pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase__ ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) lowercase , lowercase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 lowercase = pa.BufferReader(output.getvalue() ) lowercase = pq.read_table(lowerCAmelCase__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" ,[False, True] ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): import PIL.Image lowercase = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) ,dtype=np.uinta ) ).save(lowerCAmelCase__ ,format="""png""" ) lowercase = pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase__ ,features=Features({"""image""": Image()} ) ,embed_local_files=lowerCAmelCase__ ) as writer: writer.write({"""image""": image_path} ) writer.finalize() lowercase = pa.BufferReader(output.getvalue() ) lowercase = pq.read_table(lowerCAmelCase__ ) lowercase = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] ,lowerCAmelCase__ ) with open(lowerCAmelCase__ ,"""rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def UpperCamelCase__ ( ): lowercase = pa.schema([pa.field("""col_1""" ,pa.string() ,nullable=lowerCAmelCase__ )] ) lowercase = pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase__ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase__ ) assert writer._schema == pa.schema([pa.field("""col_1""" ,pa.string() )] )
711
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __SCREAMING_SNAKE_CASE : Tuple ={ '''configuration_resnet''': ['''RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ResNetConfig''', '''ResNetOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Union[str, Any] =[ '''RESNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ResNetForImageClassification''', '''ResNetModel''', '''ResNetPreTrainedModel''', '''ResNetBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] =[ '''TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFResNetForImageClassification''', '''TFResNetModel''', '''TFResNetPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Union[str, Any] =[ '''FlaxResNetForImageClassification''', '''FlaxResNetModel''', '''FlaxResNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys __SCREAMING_SNAKE_CASE : int =_LazyModule(__name__, globals()['''__file__'''], _import_structure)
72
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType __SCREAMING_SNAKE_CASE : Tuple =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[Any] ={ '''openai/whisper-base''': '''https://huggingface.co/openai/whisper-base/resolve/main/config.json''', } # fmt: off __SCREAMING_SNAKE_CASE : Dict =[ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377, 1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211, 4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786, 11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791, 17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409, 34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361 ] __SCREAMING_SNAKE_CASE : Optional[Any] =[ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627, 3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647, 7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793, 14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675, 22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865, 42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362 ] class A_ ( __a ): _A :List[str] = '''whisper''' _A :str = ['''past_key_values'''] _A :Tuple = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self : Tuple , snake_case__ : Optional[Any]=5_18_65 , snake_case__ : List[str]=80 , snake_case__ : int=6 , snake_case__ : Union[str, Any]=4 , snake_case__ : Tuple=6 , snake_case__ : Any=4 , snake_case__ : List[Any]=15_36 , snake_case__ : List[Any]=15_36 , snake_case__ : List[str]=0.0 , snake_case__ : Union[str, Any]=0.0 , snake_case__ : Optional[Any]=5_02_57 , snake_case__ : Union[str, Any]=True , snake_case__ : Optional[int]=True , snake_case__ : List[str]="gelu" , snake_case__ : str=2_56 , snake_case__ : Any=0.0 , snake_case__ : Union[str, Any]=0.0 , snake_case__ : Dict=0.0 , snake_case__ : Tuple=0.02 , snake_case__ : Union[str, Any]=False , snake_case__ : int=15_00 , snake_case__ : int=4_48 , snake_case__ : str=5_02_56 , snake_case__ : str=5_02_56 , snake_case__ : List[Any]=5_02_56 , snake_case__ : str=None , snake_case__ : Optional[int]=[2_20, 5_02_56] , snake_case__ : List[str]=False , snake_case__ : Optional[int]=2_56 , snake_case__ : List[Any]=False , snake_case__ : int=0.05 , snake_case__ : List[str]=10 , snake_case__ : List[Any]=2 , snake_case__ : str=0.0 , snake_case__ : Any=10 , snake_case__ : Any=0 , snake_case__ : str=7 , **snake_case__ : Optional[Any] , ): lowercase = vocab_size lowercase = num_mel_bins lowercase = d_model lowercase = encoder_layers lowercase = encoder_attention_heads lowercase = decoder_layers lowercase = decoder_attention_heads lowercase = decoder_ffn_dim lowercase = encoder_ffn_dim lowercase = dropout lowercase = attention_dropout lowercase = activation_dropout lowercase = activation_function lowercase = init_std lowercase = encoder_layerdrop lowercase = decoder_layerdrop lowercase = use_cache lowercase = encoder_layers lowercase = scale_embedding # scale factor will be sqrt(d_model) if True lowercase = max_source_positions lowercase = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. lowercase = classifier_proj_size lowercase = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase = apply_spec_augment lowercase = mask_time_prob lowercase = mask_time_length lowercase = mask_time_min_masks lowercase = mask_feature_prob lowercase = mask_feature_length lowercase = mask_feature_min_masks lowercase = median_filter_width super().__init__( pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , is_encoder_decoder=snake_case__ , decoder_start_token_id=snake_case__ , suppress_tokens=snake_case__ , begin_suppress_tokens=snake_case__ , **snake_case__ , ) class A_ ( __a ): @property def SCREAMING_SNAKE_CASE__ ( self : int ): lowercase = OrderedDict( [ ("""input_features""", {0: """batch""", 1: """feature_size""", 2: """encoder_sequence"""}), ] ) if self.use_past: lowercase = {0: """batch"""} else: lowercase = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(snake_case__ , direction="""inputs""" ) return common_inputs def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , snake_case__ : int = -1 , snake_case__ : int = -1 , snake_case__ : bool = False , snake_case__ : Optional["TensorType"] = None , snake_case__ : int = 2_20_50 , snake_case__ : float = 5.0 , snake_case__ : int = 2_20 , ): lowercase = OrderedDict() lowercase = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=snake_case__ , framework=snake_case__ , sampling_rate=snake_case__ , time_duration=snake_case__ , frequency=snake_case__ , ) lowercase = encoder_inputs["""input_features"""].shape[2] lowercase = encoder_sequence_length // 2 if self.use_past else seq_length lowercase = super().generate_dummy_inputs( preprocessor.tokenizer , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) lowercase = encoder_inputs.pop("""input_features""" ) lowercase = decoder_inputs.pop("""decoder_input_ids""" ) if "past_key_values" in decoder_inputs: lowercase = decoder_inputs.pop("""past_key_values""" ) return dummy_inputs @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): return 1E-3
712
import argparse import os import re import packaging.version __SCREAMING_SNAKE_CASE : Optional[int] ='''examples/''' __SCREAMING_SNAKE_CASE : Any ={ '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } __SCREAMING_SNAKE_CASE : Union[str, Any] ={ '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } __SCREAMING_SNAKE_CASE : Any ='''README.md''' def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): with open(lowerCAmelCase__ ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: lowercase = f.read() lowercase , lowercase = REPLACE_PATTERNS[pattern] lowercase = replace.replace("""VERSION""" ,lowerCAmelCase__ ) lowercase = re_pattern.sub(lowerCAmelCase__ ,lowerCAmelCase__ ) with open(lowerCAmelCase__ ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.write(lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ): for folder, directories, fnames in os.walk(lowerCAmelCase__ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(lowerCAmelCase__ ,lowerCAmelCase__ ) ,lowerCAmelCase__ ,pattern="""examples""" ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) if not patch: update_version_in_examples(lowerCAmelCase__ ) def UpperCamelCase__ ( ): lowercase = """🤗 Transformers currently provides the following architectures""" lowercase = """1. Want to contribute a new model?""" with open(lowerCAmelCase__ ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: lowercase = f.readlines() # Find the start of the list. lowercase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowercase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): lowercase = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" ,"""https://huggingface.co/docs/transformers/model_doc""" ,) index += 1 with open(lowerCAmelCase__ ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.writelines(lowerCAmelCase__ ) def UpperCamelCase__ ( ): with open(REPLACE_FILES["""init"""] ,"""r""" ) as f: lowercase = f.read() lowercase = REPLACE_PATTERNS["""init"""][0].search(lowerCAmelCase__ ).groups()[0] return packaging.version.parse(lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__=False ): lowercase = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: lowercase = default_version.base_version elif patch: lowercase = f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: lowercase = f"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. lowercase = input(f"""Which version are you releasing? [{default_version}]""" ) if len(lowerCAmelCase__ ) == 0: lowercase = default_version print(f"""Updating version to {version}.""" ) global_version_update(lowerCAmelCase__ ,patch=lowerCAmelCase__ ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def UpperCamelCase__ ( ): lowercase = get_version() lowercase = f"""{current_version.major}.{current_version.minor + 1}.0.dev0""" lowercase = current_version.base_version # Check with the user we got that right. lowercase = input(f"""Which version are we developing now? [{dev_version}]""" ) if len(lowerCAmelCase__ ) == 0: lowercase = dev_version print(f"""Updating version to {version}.""" ) global_version_update(lowerCAmelCase__ ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[Any] =argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') __SCREAMING_SNAKE_CASE : Optional[int] =parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
72
0
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values __SCREAMING_SNAKE_CASE : Optional[Any] =argparse.ArgumentParser() parser.add_argument('''--user''', type=str, default='''ubuntu''') parser.add_argument('''--host''', type=str, default='''localhost''') parser.add_argument('''--key_path''', type=str, default=None) parser.add_argument('''--instance''', type=str, default='''V100:1''') parser.add_argument('''--provider''', type=str, default='''cheapest''') parser.add_argument('''--use_spot''', type=bool, default=False) parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''') __SCREAMING_SNAKE_CASE : Union[str, Any] =parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('''Cannot specify both BYO and on-demand cluster args''') __SCREAMING_SNAKE_CASE : Dict =rh.cluster( name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path} ) else: __SCREAMING_SNAKE_CASE : Dict =rh.cluster( name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) __SCREAMING_SNAKE_CASE : str =args.example.rsplit('''/''', 1)[0] # Set up remote environment cluster.install_packages(['''pip:./''']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f'''pip install -r transformers/examples/{example_dir}/requirements.txt''']) cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117''']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f'''python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}''']) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
713
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple ={ '''google/pix2struct-textcaps-base''': ( '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json''' ), } class A_ ( __a ): _A :List[str] = '''pix2struct_text_model''' _A :int = ['''past_key_values'''] _A :Optional[Any] = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : int , snake_case__ : str=5_02_44 , snake_case__ : Dict=7_68 , snake_case__ : Optional[Any]=64 , snake_case__ : Union[str, Any]=20_48 , snake_case__ : Union[str, Any]=12 , snake_case__ : str=12 , snake_case__ : int=32 , snake_case__ : List[Any]=1_28 , snake_case__ : Optional[int]=0.1 , snake_case__ : int=1E-6 , snake_case__ : int=1.0 , snake_case__ : Dict="gelu_new" , snake_case__ : Union[str, Any]=0 , snake_case__ : str=False , snake_case__ : List[str]=0 , snake_case__ : str=1 , snake_case__ : Optional[Any]=False , snake_case__ : Tuple=True , **snake_case__ : List[str] , ): lowercase = vocab_size lowercase = hidden_size lowercase = d_kv lowercase = d_ff lowercase = num_layers lowercase = num_heads lowercase = relative_attention_num_buckets lowercase = relative_attention_max_distance lowercase = dropout_rate lowercase = layer_norm_epsilon lowercase = initializer_factor lowercase = use_cache lowercase = eos_token_id lowercase = decoder_start_token_id # for backwards compatibility lowercase = dense_act_fn super().__init__( pad_token_id=snake_case__ , eos_token_id=snake_case__ , decoder_start_token_id=snake_case__ , tie_word_embeddings=snake_case__ , is_decoder=snake_case__ , **snake_case__ , ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Optional[int] , snake_case__ : Union[str, os.PathLike] , **snake_case__ : int ): cls._set_token_in_kwargs(snake_case__ ) lowercase , lowercase = cls.get_config_dict(snake_case__ , **snake_case__ ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": lowercase = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(snake_case__ , **snake_case__ ) class A_ ( __a ): _A :Optional[int] = '''pix2struct_vision_model''' def __init__( self : Tuple , snake_case__ : Union[str, Any]=7_68 , snake_case__ : Any=7_68 , snake_case__ : Dict=20_48 , snake_case__ : int=64 , snake_case__ : str=12 , snake_case__ : Optional[int]=12 , snake_case__ : Union[str, Any]="gelu_new" , snake_case__ : Union[str, Any]=1E-6 , snake_case__ : int=0.0 , snake_case__ : Tuple=0.0 , snake_case__ : Optional[int]=1E-10 , snake_case__ : Optional[int]=1.0 , snake_case__ : Optional[Any]=40_96 , snake_case__ : Optional[int]=32 , snake_case__ : List[Any]=1_28 , **snake_case__ : Union[str, Any] , ): super().__init__(**snake_case__ ) lowercase = hidden_size lowercase = patch_embed_hidden_size lowercase = d_ff lowercase = dropout_rate lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = initializer_range lowercase = initializer_factor lowercase = attention_dropout lowercase = layer_norm_eps lowercase = dense_act_fn lowercase = seq_len lowercase = relative_attention_num_buckets lowercase = relative_attention_max_distance lowercase = d_kv @classmethod def SCREAMING_SNAKE_CASE__ ( cls : List[Any] , snake_case__ : Union[str, os.PathLike] , **snake_case__ : int ): cls._set_token_in_kwargs(snake_case__ ) lowercase , lowercase = cls.get_config_dict(snake_case__ , **snake_case__ ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": lowercase = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(snake_case__ , **snake_case__ ) class A_ ( __a ): _A :int = '''pix2struct''' _A :str = True def __init__( self : Optional[int] , snake_case__ : List[str]=None , snake_case__ : Optional[Any]=None , snake_case__ : List[Any]=1.0 , snake_case__ : Any=0.02 , snake_case__ : Tuple=False , snake_case__ : Union[str, Any]=False , snake_case__ : Tuple=True , **snake_case__ : int , ): super().__init__(tie_word_embeddings=snake_case__ , is_encoder_decoder=snake_case__ , **snake_case__ ) if text_config is None: lowercase = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: lowercase = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) lowercase = PixaStructTextConfig(**snake_case__ ) lowercase = PixaStructVisionConfig(**snake_case__ ) lowercase = self.text_config.decoder_start_token_id lowercase = self.text_config.pad_token_id lowercase = self.text_config.eos_token_id lowercase = initializer_factor lowercase = initializer_range lowercase = self.initializer_range lowercase = self.initializer_range lowercase = is_vqa @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple , snake_case__ : PixaStructTextConfig , snake_case__ : PixaStructVisionConfig , **snake_case__ : Any ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : str ): lowercase = copy.deepcopy(self.__dict__ ) lowercase = self.text_config.to_dict() lowercase = self.vision_config.to_dict() lowercase = self.__class__.model_type return output
72
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __SCREAMING_SNAKE_CASE : Union[str, Any] ='''src/diffusers''' __SCREAMING_SNAKE_CASE : Union[str, Any] ='''.''' # This is to make sure the diffusers module imported is the one in the repo. __SCREAMING_SNAKE_CASE : int =importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) __SCREAMING_SNAKE_CASE : Any =spec.loader.load_module() def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): return line.startswith(lowerCAmelCase__ ) or len(lowerCAmelCase__ ) <= 1 or re.search(r"""^\s*\)(\s*->.*:|:)\s*$""" ,lowerCAmelCase__ ) is not None def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = object_name.split(""".""" ) lowercase = 0 # First let's find the module where our object lives. lowercase = parts[i] while i < len(lowerCAmelCase__ ) and not os.path.isfile(os.path.join(lowerCAmelCase__ ,f"""{module}.py""" ) ): i += 1 if i < len(lowerCAmelCase__ ): lowercase = os.path.join(lowerCAmelCase__ ,parts[i] ) if i >= len(lowerCAmelCase__ ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(lowerCAmelCase__ ,f"""{module}.py""" ) ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: lowercase = f.readlines() # Now let's find the class / func in the code! lowercase = """""" lowercase = 0 for name in parts[i + 1 :]: while ( line_index < len(lowerCAmelCase__ ) and re.search(rf"""^{indent}(class|def)\s+{name}(\(|\:)""" ,lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(lowerCAmelCase__ ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). lowercase = line_index while line_index < len(lowerCAmelCase__ ) and _should_continue(lines[line_index] ,lowerCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 lowercase = lines[start_index:line_index] return "".join(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] =re.compile(R'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') __SCREAMING_SNAKE_CASE : Tuple =re.compile(R'''^\s*(\S+)->(\S+)(\s+.*|$)''') __SCREAMING_SNAKE_CASE : str =re.compile(R'''<FILL\s+[^>]*>''') def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = code.split("""\n""" ) lowercase = 0 while idx < len(lowerCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(lowerCAmelCase__ ): return re.search(r"""^(\s*)\S""" ,lines[idx] ).groups()[0] return "" def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = len(get_indent(lowerCAmelCase__ ) ) > 0 if has_indent: lowercase = f"""class Bla:\n{code}""" lowercase = black.Mode(target_versions={black.TargetVersion.PYaa} ,line_length=119 ,preview=lowerCAmelCase__ ) lowercase = black.format_str(lowerCAmelCase__ ,mode=lowerCAmelCase__ ) lowercase , lowercase = style_docstrings_in_code(lowerCAmelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__=False ): with open(lowerCAmelCase__ ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: lowercase = f.readlines() lowercase = [] lowercase = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(lowerCAmelCase__ ): lowercase = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. lowercase , lowercase , lowercase = search.groups() lowercase = find_code_in_diffusers(lowerCAmelCase__ ) lowercase = get_indent(lowerCAmelCase__ ) lowercase = line_index + 1 if indent == theoretical_indent else line_index + 2 lowercase = theoretical_indent lowercase = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. lowercase = True while line_index < len(lowerCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(lowerCAmelCase__ ): break lowercase = lines[line_index] lowercase = _should_continue(lowerCAmelCase__ ,lowerCAmelCase__ ) and re.search(f"""^{indent}# End copy""" ,lowerCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 lowercase = lines[start_index:line_index] lowercase = """""".join(lowerCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies lowercase = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(lowerCAmelCase__ ) is None] lowercase = """\n""".join(lowerCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(lowerCAmelCase__ ) > 0: lowercase = replace_pattern.replace("""with""" ,"""""" ).split(""",""" ) lowercase = [_re_replace_pattern.search(lowerCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue lowercase , lowercase , lowercase = pattern.groups() lowercase = re.sub(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) if option.strip() == "all-casing": lowercase = re.sub(obja.lower() ,obja.lower() ,lowerCAmelCase__ ) lowercase = re.sub(obja.upper() ,obja.upper() ,lowerCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line lowercase = blackify(lines[start_index - 1] + theoretical_code ) lowercase = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: lowercase = lines[:start_index] + [theoretical_code] + lines[line_index:] lowercase = start_index + 1 if overwrite and len(lowerCAmelCase__ ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(lowerCAmelCase__ ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.writelines(lowerCAmelCase__ ) return diffs def UpperCamelCase__ ( lowerCAmelCase__ = False ): lowercase = glob.glob(os.path.join(lowerCAmelCase__ ,"""**/*.py""" ) ,recursive=lowerCAmelCase__ ) lowercase = [] for filename in all_files: lowercase = is_copy_consistent(lowerCAmelCase__ ,lowerCAmelCase__ ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(lowerCAmelCase__ ) > 0: lowercase = """\n""".join(lowerCAmelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Optional[int] =argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') __SCREAMING_SNAKE_CASE : Any =parser.parse_args() check_copies(args.fix_and_overwrite)
714
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): for param, grad_param in zip(model_a.parameters() ,model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad ,grad_param.grad ) is False ), f"""Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad ,grad_param.grad ) is True ), f"""Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})""" def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=True ): model.train() lowercase = model(lowerCAmelCase__ ) lowercase = F.mse_loss(lowerCAmelCase__ ,target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__=False ): set_seed(42 ) lowercase = RegressionModel() lowercase = deepcopy(lowerCAmelCase__ ) lowercase = RegressionDataset(length=80 ) lowercase = DataLoader(lowerCAmelCase__ ,batch_size=16 ) model.to(accelerator.device ) if sched: lowercase = AdamW(params=model.parameters() ,lr=1E-3 ) lowercase = AdamW(params=ddp_model.parameters() ,lr=1E-3 ) lowercase = LambdaLR(lowerCAmelCase__ ,lr_lambda=lambda lowerCAmelCase__ : epoch**0.65 ) lowercase = LambdaLR(lowerCAmelCase__ ,lr_lambda=lambda lowerCAmelCase__ : epoch**0.65 ) # Make a copy of `model` if sched: lowercase , lowercase , lowercase , lowercase = accelerator.prepare(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) else: lowercase , lowercase = accelerator.prepare(lowerCAmelCase__ ,lowerCAmelCase__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def UpperCamelCase__ ( lowerCAmelCase__ ): # Test when on a single CPU or GPU that the context manager does nothing lowercase , lowercase , lowercase = get_training_setup(lowerCAmelCase__ ) # Use a single batch lowercase , lowercase = next(iter(lowerCAmelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model lowercase , lowercase = accelerator.gather((ddp_input, ddp_target) ) lowercase , lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(lowerCAmelCase__ ): step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) else: # Sync grads step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) for param, ddp_param in zip(model.parameters() ,ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad ,ddp_param.grad ), f"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) lowercase = ddp_input[torch.randperm(len(lowerCAmelCase__ ) )] def UpperCamelCase__ ( lowerCAmelCase__ ): # Test on distributed setup that context manager behaves properly lowercase , lowercase , lowercase = get_training_setup(lowerCAmelCase__ ) # Use a single batch lowercase , lowercase = next(iter(lowerCAmelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model lowercase , lowercase = accelerator.gather((ddp_input, ddp_target) ) lowercase , lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(lowerCAmelCase__ ): step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) else: # Sync grads step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() ,ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad ,ddp_param.grad ) is False ), f"""Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad ,ddp_param.grad ) is True ), f"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) lowercase = ddp_input[torch.randperm(len(lowerCAmelCase__ ) )] def UpperCamelCase__ ( lowerCAmelCase__=False ,lowerCAmelCase__=False ): lowercase = Accelerator( split_batches=lowerCAmelCase__ ,dispatch_batches=lowerCAmelCase__ ,gradient_accumulation_steps=2 ) # Test that context manager behaves properly lowercase , lowercase , lowercase = get_training_setup(lowerCAmelCase__ ) for iteration, batch in enumerate(lowerCAmelCase__ ): lowercase , lowercase = batch.values() # Gather the distributed inputs and targs for the base model lowercase , lowercase = accelerator.gather((ddp_input, ddp_target) ) lowercase , lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(lowerCAmelCase__ ): step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() ,ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(lowerCAmelCase__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad ,ddp_param.grad ) is True ), f"""Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" else: # Grads should not be in sync assert ( torch.allclose(param.grad ,ddp_param.grad ) is False ), f"""Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) lowercase = ddp_input[torch.randperm(len(lowerCAmelCase__ ) )] GradientState._reset_state() def UpperCamelCase__ ( lowerCAmelCase__=False ,lowerCAmelCase__=False ): lowercase = Accelerator( split_batches=lowerCAmelCase__ ,dispatch_batches=lowerCAmelCase__ ,gradient_accumulation_steps=2 ) # Test that context manager behaves properly lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase = get_training_setup(lowerCAmelCase__ ,lowerCAmelCase__ ) for iteration, batch in enumerate(lowerCAmelCase__ ): lowercase , lowercase = batch.values() # Gather the distributed inputs and targs for the base model lowercase , lowercase = accelerator.gather((ddp_input, ddp_target) ) lowercase , lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(lowerCAmelCase__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(lowerCAmelCase__ ): step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f"""Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n""" lowercase = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(lowerCAmelCase__ )) if accelerator.num_processes > 1: check_model_parameters(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def UpperCamelCase__ ( ): lowercase = Accelerator() lowercase = RegressionDataset(length=80 ) lowercase = DataLoader(lowerCAmelCase__ ,batch_size=16 ) lowercase = RegressionDataset(length=96 ) lowercase = DataLoader(lowerCAmelCase__ ,batch_size=16 ) lowercase , lowercase = accelerator.prepare(lowerCAmelCase__ ,lowerCAmelCase__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(lowerCAmelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(lowerCAmelCase__ ) if iteration < len(lowerCAmelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(lowerCAmelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(lowerCAmelCase__ ) if batch_num < len(lowerCAmelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def UpperCamelCase__ ( ): lowercase = Accelerator() lowercase = accelerator.state if state.local_process_index == 0: print("""**Test `accumulate` gradient accumulation with dataloader break**""" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("""**Test NOOP `no_sync` context manager**""" ) test_noop_sync(lowerCAmelCase__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("""**Test Distributed `no_sync` context manager**""" ) test_distributed_sync(lowerCAmelCase__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation, """ ,f"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""" ,) test_gradient_accumulation(lowerCAmelCase__ ,lowerCAmelCase__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("""<""" ,"""2.0""" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ ,"""`split_batches=False`, `dispatch_batches=False`**""" ,) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ ,f"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""" ,) test_gradient_accumulation_with_opt_and_scheduler(lowerCAmelCase__ ,lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
72
0
import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : str =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Any ={ '''facebook/encodec_24khz''': '''https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json''', '''facebook/encodec_48khz''': '''https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json''', } class A_ ( __a ): _A :List[str] = '''encodec''' def __init__( self : List[Any] , snake_case__ : str=[1.5, 3.0, 6.0, 12.0, 24.0] , snake_case__ : int=2_40_00 , snake_case__ : Any=1 , snake_case__ : Optional[int]=False , snake_case__ : Tuple=None , snake_case__ : Optional[int]=None , snake_case__ : str=1_28 , snake_case__ : Tuple=32 , snake_case__ : Optional[int]=1 , snake_case__ : Dict=[8, 5, 4, 2] , snake_case__ : List[Any]="weight_norm" , snake_case__ : Union[str, Any]=7 , snake_case__ : Optional[int]=7 , snake_case__ : List[Any]=3 , snake_case__ : Optional[int]=2 , snake_case__ : List[str]=True , snake_case__ : str="reflect" , snake_case__ : int=2 , snake_case__ : Union[str, Any]=2 , snake_case__ : str=1.0 , snake_case__ : str=10_24 , snake_case__ : str=None , snake_case__ : List[Any]=True , **snake_case__ : Any , ): lowercase = target_bandwidths lowercase = sampling_rate lowercase = audio_channels lowercase = normalize lowercase = chunk_length_s lowercase = overlap lowercase = hidden_size lowercase = num_filters lowercase = num_residual_layers lowercase = upsampling_ratios lowercase = norm_type lowercase = kernel_size lowercase = last_kernel_size lowercase = residual_kernel_size lowercase = dilation_growth_rate lowercase = use_causal_conv lowercase = pad_mode lowercase = compress lowercase = num_lstm_layers lowercase = trim_right_ratio lowercase = codebook_size lowercase = codebook_dim if codebook_dim is not None else hidden_size lowercase = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**snake_case__ ) @property def SCREAMING_SNAKE_CASE__ ( self : Any ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def SCREAMING_SNAKE_CASE__ ( self : str ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): lowercase = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def SCREAMING_SNAKE_CASE__ ( self : str ): return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
715
import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 __SCREAMING_SNAKE_CASE : Tuple =get_tests_dir('''fixtures/dummy_feature_extractor_config.json''') __SCREAMING_SNAKE_CASE : Union[str, Any] =get_tests_dir('''fixtures/vocab.json''') __SCREAMING_SNAKE_CASE : Union[str, Any] =get_tests_dir('''fixtures''') class A_ ( unittest.TestCase ): _A :List[str] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): lowercase = 0 def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowercase = AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(snake_case__ , snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): with tempfile.TemporaryDirectory() as tmpdirname: lowercase = WavaVecaConfig() lowercase = AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h""" ) # save in new folder model_config.save_pretrained(snake_case__ ) processor.save_pretrained(snake_case__ ) lowercase = AutoProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Any ): with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(snake_case__ , os.path.join(snake_case__ , snake_case__ ) ) copyfile(snake_case__ , os.path.join(snake_case__ , """vocab.json""" ) ) lowercase = AutoProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : int ): with tempfile.TemporaryDirectory() as tmpdirname: lowercase = WavaVecaFeatureExtractor() lowercase = AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h""" ) lowercase = WavaVecaProcessor(snake_case__ , snake_case__ ) # save in new folder processor.save_pretrained(snake_case__ ) # drop `processor_class` in tokenizer with open(os.path.join(snake_case__ , snake_case__ ) , """r""" ) as f: lowercase = json.load(snake_case__ ) config_dict.pop("""processor_class""" ) with open(os.path.join(snake_case__ , snake_case__ ) , """w""" ) as f: f.write(json.dumps(snake_case__ ) ) lowercase = AutoProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Any ): with tempfile.TemporaryDirectory() as tmpdirname: lowercase = WavaVecaFeatureExtractor() lowercase = AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h""" ) lowercase = WavaVecaProcessor(snake_case__ , snake_case__ ) # save in new folder processor.save_pretrained(snake_case__ ) # drop `processor_class` in feature extractor with open(os.path.join(snake_case__ , snake_case__ ) , """r""" ) as f: lowercase = json.load(snake_case__ ) config_dict.pop("""processor_class""" ) with open(os.path.join(snake_case__ , snake_case__ ) , """w""" ) as f: f.write(json.dumps(snake_case__ ) ) lowercase = AutoProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : str ): with tempfile.TemporaryDirectory() as tmpdirname: lowercase = WavaVecaConfig(processor_class="""Wav2Vec2Processor""" ) model_config.save_pretrained(snake_case__ ) # copy relevant files copyfile(snake_case__ , os.path.join(snake_case__ , """vocab.json""" ) ) # create emtpy sample processor with open(os.path.join(snake_case__ , snake_case__ ) , """w""" ) as f: f.write("""{}""" ) lowercase = AutoProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(snake_case__ ): lowercase = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(snake_case__ ): lowercase = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=snake_case__ ) lowercase = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" , trust_remote_code=snake_case__ ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) lowercase = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) lowercase = processor.tokenizer self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version lowercase = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=snake_case__ , use_fast=snake_case__ ) lowercase = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): try: AutoConfig.register("""custom""" , snake_case__ ) AutoFeatureExtractor.register(snake_case__ , snake_case__ ) AutoTokenizer.register(snake_case__ , slow_tokenizer_class=snake_case__ ) AutoProcessor.register(snake_case__ , snake_case__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(snake_case__ ): AutoProcessor.register(snake_case__ , snake_case__ ) # Now that the config is registered, it can be used as any other config with the auto-API lowercase = CustomFeatureExtractor.from_pretrained(snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dir: lowercase = os.path.join(snake_case__ , """vocab.txt""" ) with open(snake_case__ , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) lowercase = CustomTokenizer(snake_case__ ) lowercase = CustomProcessor(snake_case__ , snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(snake_case__ ) lowercase = AutoProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): class A_ ( __a ): _A :List[str] = False class A_ ( __a ): _A :Dict = False class A_ ( __a ): _A :Union[str, Any] = '''AutoFeatureExtractor''' _A :Tuple = '''AutoTokenizer''' _A :Optional[Any] = False try: AutoConfig.register("""custom""" , snake_case__ ) AutoFeatureExtractor.register(snake_case__ , snake_case__ ) AutoTokenizer.register(snake_case__ , slow_tokenizer_class=snake_case__ ) AutoProcessor.register(snake_case__ , snake_case__ ) # If remote code is not set, the default is to use local classes. lowercase = AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. lowercase = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=snake_case__ ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. lowercase = AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=snake_case__ ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): lowercase = AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(processor.__class__.__name__ , """BertTokenizerFast""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): lowercase = AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-convnext""" ) self.assertEqual(processor.__class__.__name__ , """ConvNextImageProcessor""" ) @is_staging_test class A_ ( unittest.TestCase ): _A :Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Optional[int] ): lowercase = TOKEN HfFolder.save_token(snake_case__ ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Union[str, Any] ): try: delete_repo(token=cls._token , repo_id="""test-processor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-processor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-processor""" ) except HTTPError: pass def SCREAMING_SNAKE_CASE__ ( self : List[str] ): lowercase = WavaVecaProcessor.from_pretrained(snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(snake_case__ , """test-processor""" ) , push_to_hub=snake_case__ , use_auth_token=self._token ) lowercase = WavaVecaProcessor.from_pretrained(F"""{USER}/test-processor""" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(snake_case__ , getattr(new_processor.feature_extractor , snake_case__ ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): lowercase = WavaVecaProcessor.from_pretrained(snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(snake_case__ , """test-processor-org""" ) , push_to_hub=snake_case__ , use_auth_token=self._token , organization="""valid_org""" , ) lowercase = WavaVecaProcessor.from_pretrained("""valid_org/test-processor-org""" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(snake_case__ , getattr(new_processor.feature_extractor , snake_case__ ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() lowercase = CustomFeatureExtractor.from_pretrained(snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dir: lowercase = os.path.join(snake_case__ , """vocab.txt""" ) with open(snake_case__ , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) lowercase = CustomTokenizer(snake_case__ ) lowercase = CustomProcessor(snake_case__ , snake_case__ ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(F"""{USER}/test-dynamic-processor""" , token=self._token ) lowercase = Repository(snake_case__ , clone_from=F"""{USER}/test-dynamic-processor""" , token=self._token ) processor.save_pretrained(snake_case__ ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { """AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor""", """AutoProcessor""": """custom_processing.CustomProcessor""", } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(snake_case__ , """tokenizer_config.json""" ) ) as f: lowercase = json.load(snake_case__ ) self.assertDictEqual( tokenizer_config["""auto_map"""] , { """AutoTokenizer""": ["""custom_tokenization.CustomTokenizer""", None], """AutoProcessor""": """custom_processing.CustomProcessor""", } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(snake_case__ , """custom_feature_extraction.py""" ) ) ) self.assertTrue(os.path.isfile(os.path.join(snake_case__ , """custom_tokenization.py""" ) ) ) self.assertTrue(os.path.isfile(os.path.join(snake_case__ , """custom_processing.py""" ) ) ) repo.push_to_hub() lowercase = AutoProcessor.from_pretrained(F"""{USER}/test-dynamic-processor""" , trust_remote_code=snake_case__ ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , """CustomProcessor""" )
72
0
import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.17.0.dev0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''') __SCREAMING_SNAKE_CASE =logging.getLogger(__name__) @dataclass class A_ : _A :Optional[str] = field( default='''tab_fact''' , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) _A :Optional[str] = field( default='''tab_fact''' , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} , ) _A :int = field( default=1024 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) _A :bool = field( default=__a , metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} ) _A :bool = field( default=__a , metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) } , ) _A :Optional[int] = field( default=__a , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) _A :Optional[int] = field( default=__a , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) _A :Optional[int] = field( default=__a , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of prediction examples to this ''' '''value if set.''' ) } , ) _A :Optional[str] = field( default=__a , metadata={'''help''': '''A csv or a json file containing the training data.'''} ) _A :Optional[str] = field( default=__a , metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) _A :Optional[str] = field(default=__a , metadata={'''help''': '''A csv or a json file containing the test data.'''} ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError("""Need either a GLUE task, a training/validation file or a dataset name.""" ) else: lowercase = self.train_file.split(""".""" )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." lowercase = self.validation_file.split(""".""" )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class A_ : _A :str = field( default=__a , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _A :Optional[str] = field( default=__a , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _A :Optional[str] = field( default=__a , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _A :Optional[str] = field( default=__a , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _A :bool = field( default=__a , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) _A :str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) _A :bool = field( default=__a , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) def UpperCamelCase__ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowercase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowercase , lowercase , lowercase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowercase , lowercase , lowercase = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) lowercase = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase__ ) datasets.utils.logging.set_verbosity(lowerCAmelCase__ ) transformers.utils.logging.set_verbosity(lowerCAmelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. lowercase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowercase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowercase = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. lowercase = {"""train""": data_args.train_file, """validation""": data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: lowercase = data_args.train_file.split(""".""" )[-1] lowercase = data_args.test_file.split(""".""" )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." lowercase = data_args.test_file else: raise ValueError("""Need either a GLUE task or a test file for `do_predict`.""" ) for key in data_files.keys(): logger.info(f"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith(""".csv""" ): # Loading a dataset from local csv files lowercase = load_dataset("""csv""" ,data_files=lowerCAmelCase__ ,cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files lowercase = load_dataset("""json""" ,data_files=lowerCAmelCase__ ,cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels lowercase = raw_datasets["""train"""].features["""label"""].names lowercase = len(lowerCAmelCase__ ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path ,num_labels=lowerCAmelCase__ ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # load tapex tokenizer lowercase = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,cache_dir=model_args.cache_dir ,use_fast=model_args.use_fast_tokenizer ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,add_prefix_space=lowerCAmelCase__ ,) lowercase = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) ,config=lowerCAmelCase__ ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # Padding strategy if data_args.pad_to_max_length: lowercase = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch lowercase = False # Some models have set the order of the labels to use, so let's make sure we do use it. lowercase = {"""Refused""": 0, """Entailed""": 1} lowercase = {0: """Refused""", 1: """Entailed"""} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) lowercase = min(data_args.max_seq_length ,tokenizer.model_max_length ) def preprocess_tabfact_function(lowerCAmelCase__ ): # Tokenize the texts def _convert_table_text_to_pandas(lowerCAmelCase__ ): lowercase = [_table_row.split("""#""" ) for _table_row in _table_text.strip("""\n""" ).split("""\n""" )] lowercase = pd.DataFrame.from_records(_table_content[1:] ,columns=_table_content[0] ) return _table_pd lowercase = examples["""statement"""] lowercase = list(map(_convert_table_text_to_pandas ,examples["""table_text"""] ) ) lowercase = tokenizer(lowerCAmelCase__ ,lowerCAmelCase__ ,padding=lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,truncation=lowerCAmelCase__ ) lowercase = examples["""label"""] return result with training_args.main_process_first(desc="""dataset map pre-processing""" ): lowercase = raw_datasets.map( lowerCAmelCase__ ,batched=lowerCAmelCase__ ,load_from_cache_file=not data_args.overwrite_cache ,desc="""Running tokenizer on dataset""" ,) if training_args.do_train: if "train" not in raw_datasets: raise ValueError("""--do_train requires a train dataset""" ) lowercase = raw_datasets["""train"""] if data_args.max_train_samples is not None: lowercase = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError("""--do_eval requires a validation dataset""" ) lowercase = raw_datasets["""validation"""] if data_args.max_eval_samples is not None: lowercase = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError("""--do_predict requires a test dataset""" ) lowercase = raw_datasets["""test"""] if data_args.max_predict_samples is not None: lowercase = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(lowerCAmelCase__ ) ) ,3 ): logger.info(f"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(lowerCAmelCase__ ): lowercase = p.predictions[0] if isinstance(p.predictions ,lowerCAmelCase__ ) else p.predictions lowercase = np.argmax(lowerCAmelCase__ ,axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: lowercase = default_data_collator elif training_args.fpaa: lowercase = DataCollatorWithPadding(lowerCAmelCase__ ,pad_to_multiple_of=8 ) else: lowercase = None # Initialize our Trainer lowercase = Trainer( model=lowerCAmelCase__ ,args=lowerCAmelCase__ ,train_dataset=train_dataset if training_args.do_train else None ,eval_dataset=eval_dataset if training_args.do_eval else None ,compute_metrics=lowerCAmelCase__ ,tokenizer=lowerCAmelCase__ ,data_collator=lowerCAmelCase__ ,) # Training if training_args.do_train: lowercase = None if training_args.resume_from_checkpoint is not None: lowercase = training_args.resume_from_checkpoint elif last_checkpoint is not None: lowercase = last_checkpoint lowercase = trainer.train(resume_from_checkpoint=lowerCAmelCase__ ) lowercase = train_result.metrics lowercase = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase__ ) ) lowercase = min(lowerCAmelCase__ ,len(lowerCAmelCase__ ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" ,lowerCAmelCase__ ) trainer.save_metrics("""train""" ,lowerCAmelCase__ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) lowercase = trainer.evaluate(eval_dataset=lowerCAmelCase__ ) lowercase = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase__ ) lowercase = min(lowerCAmelCase__ ,len(lowerCAmelCase__ ) ) trainer.log_metrics("""eval""" ,lowerCAmelCase__ ) trainer.save_metrics("""eval""" ,lowerCAmelCase__ ) if training_args.do_predict: logger.info("""*** Predict ***""" ) # Removing the `label` columns because it contains -1 and Trainer won't like that. lowercase = predict_dataset.remove_columns("""label""" ) lowercase = trainer.predict(lowerCAmelCase__ ,metric_key_prefix="""predict""" ).predictions lowercase = np.argmax(lowerCAmelCase__ ,axis=1 ) lowercase = os.path.join(training_args.output_dir ,"""predict_results_tabfact.txt""" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase__ ,"""w""" ) as writer: logger.info("""***** Predict Results *****""" ) writer.write("""index\tprediction\n""" ) for index, item in enumerate(lowerCAmelCase__ ): lowercase = label_list[item] writer.write(f"""{index}\t{item}\n""" ) lowercase = {"""finetuned_from""": model_args.model_name_or_path, """tasks""": """text-classification"""} if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase__ ) else: trainer.create_model_card(**lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
716
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__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = 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}}""" ) lowercase = DatasetInfosDict.from_directory(lowerCAmelCase__ ) 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__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = str(lowerCAmelCase__ ) dataset_info.write_to_directory(lowerCAmelCase__ ) lowercase = DatasetInfo.from_directory(lowerCAmelCase__ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowerCAmelCase__ ,"""dataset_info.json""" ) ) def UpperCamelCase__ ( ): lowercase = 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 ,) lowercase = dataset_info._to_yaml_dict() assert sorted(lowerCAmelCase__ ) == 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) ) lowercase = yaml.safe_dump(lowerCAmelCase__ ) lowercase = yaml.safe_load(lowerCAmelCase__ ) assert dataset_info_yaml_dict == reloaded def UpperCamelCase__ ( ): lowercase = DatasetInfo() lowercase = 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__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = str(lowerCAmelCase__ ) dataset_infos_dict.write_to_directory(lowerCAmelCase__ ) lowercase = DatasetInfosDict.from_directory(lowerCAmelCase__ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): lowercase = 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 lowercase = 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(lowerCAmelCase__ ,"""README.md""" ) )
72
0
from statistics import mean import numpy as np def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = 0 # Number of processes finished lowercase = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowercase = [0] * no_of_process # List to include calculation results lowercase = [0] * no_of_process # Sort by arrival time. lowercase = [burst_time[i] for i in np.argsort(lowerCAmelCase__ )] lowercase = [process_name[i] for i in np.argsort(lowerCAmelCase__ )] arrival_time.sort() while no_of_process > finished_process_count: lowercase = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowercase = arrival_time[i] lowercase = 0 # Index showing the location of the process being performed lowercase = 0 # Saves the current response ratio. lowercase = 0 for i in range(0 ,lowerCAmelCase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowercase = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowercase = temp lowercase = i # Calculate the turn around time lowercase = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowercase = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = [0] * no_of_process for i in range(0 ,lowerCAmelCase__ ): lowercase = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] =5 __SCREAMING_SNAKE_CASE : Optional[int] =['''A''', '''B''', '''C''', '''D''', '''E'''] __SCREAMING_SNAKE_CASE : Union[str, Any] =[1, 2, 3, 4, 5] __SCREAMING_SNAKE_CASE : Dict =[1, 2, 3, 4, 5] __SCREAMING_SNAKE_CASE : List[str] =calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) __SCREAMING_SNAKE_CASE : int =calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( f'''{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t''' f'''{turn_around_time[i]}\t\t\t{waiting_time[i]}''' ) print(f'''average waiting time : {mean(waiting_time):.5f}''') print(f'''average turn around time : {mean(turn_around_time):.5f}''')
717
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def UpperCamelCase__ ( lowerCAmelCase__ ): lowercase = args.pruning_method lowercase = args.threshold lowercase = args.model_name_or_path.rstrip("""/""" ) lowercase = args.target_model_path print(f"""Load fine-pruned model from {model_name_or_path}""" ) lowercase = torch.load(os.path.join(lowerCAmelCase__ ,"""pytorch_model.bin""" ) ) lowercase = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: lowercase = tensor print(f"""Copied layer {name}""" ) elif "classifier" in name or "qa_output" in name: lowercase = tensor print(f"""Copied layer {name}""" ) elif "bias" in name: lowercase = tensor print(f"""Copied layer {name}""" ) else: if pruning_method == "magnitude": lowercase = MagnitudeBinarizer.apply(inputs=lowerCAmelCase__ ,threshold=lowerCAmelCase__ ) lowercase = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "topK": if "mask_scores" in name: continue lowercase = name[:-6] lowercase = model[f"""{prefix_}mask_scores"""] lowercase = TopKBinarizer.apply(lowerCAmelCase__ ,lowerCAmelCase__ ) lowercase = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue lowercase = name[:-6] lowercase = model[f"""{prefix_}mask_scores"""] lowercase = ThresholdBinarizer.apply(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) lowercase = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "l0": if "mask_scores" in name: continue lowercase = name[:-6] lowercase = model[f"""{prefix_}mask_scores"""] lowercase , lowercase = -0.1, 1.1 lowercase = torch.sigmoid(lowerCAmelCase__ ) lowercase = s * (r - l) + l lowercase = s_bar.clamp(min=0.0 ,max=1.0 ) lowercase = tensor * mask print(f"""Pruned layer {name}""" ) else: raise ValueError("""Unknown pruning method""" ) if target_model_path is None: lowercase = os.path.join( os.path.dirname(lowerCAmelCase__ ) ,f"""bertarized_{os.path.basename(lowerCAmelCase__ )}""" ) if not os.path.isdir(lowerCAmelCase__ ): shutil.copytree(lowerCAmelCase__ ,lowerCAmelCase__ ) print(f"""\nCreated folder {target_model_path}""" ) torch.save(lowerCAmelCase__ ,os.path.join(lowerCAmelCase__ ,"""pytorch_model.bin""" ) ) print("""\nPruned model saved! See you later!""" ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] =argparse.ArgumentParser() parser.add_argument( '''--pruning_method''', choices=['''l0''', '''magnitude''', '''topK''', '''sigmoied_threshold'''], type=str, required=True, help=( '''Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,''' ''' sigmoied_threshold = Soft movement pruning)''' ), ) parser.add_argument( '''--threshold''', type=float, required=False, help=( '''For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.''' '''For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.''' '''Not needed for `l0`''' ), ) parser.add_argument( '''--model_name_or_path''', type=str, required=True, help='''Folder containing the model that was previously fine-pruned''', ) parser.add_argument( '''--target_model_path''', default=None, type=str, required=False, help='''Folder containing the model that was previously fine-pruned''', ) __SCREAMING_SNAKE_CASE : str =parser.parse_args() main(args)
72
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple ={ '''google/pix2struct-textcaps-base''': ( '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json''' ), } class A_ ( __a ): _A :List[str] = '''pix2struct_text_model''' _A :int = ['''past_key_values'''] _A :Optional[Any] = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : int , snake_case__ : str=5_02_44 , snake_case__ : Dict=7_68 , snake_case__ : Optional[Any]=64 , snake_case__ : Union[str, Any]=20_48 , snake_case__ : Union[str, Any]=12 , snake_case__ : str=12 , snake_case__ : int=32 , snake_case__ : List[Any]=1_28 , snake_case__ : Optional[int]=0.1 , snake_case__ : int=1E-6 , snake_case__ : int=1.0 , snake_case__ : Dict="gelu_new" , snake_case__ : Union[str, Any]=0 , snake_case__ : str=False , snake_case__ : List[str]=0 , snake_case__ : str=1 , snake_case__ : Optional[Any]=False , snake_case__ : Tuple=True , **snake_case__ : List[str] , ): lowercase = vocab_size lowercase = hidden_size lowercase = d_kv lowercase = d_ff lowercase = num_layers lowercase = num_heads lowercase = relative_attention_num_buckets lowercase = relative_attention_max_distance lowercase = dropout_rate lowercase = layer_norm_epsilon lowercase = initializer_factor lowercase = use_cache lowercase = eos_token_id lowercase = decoder_start_token_id # for backwards compatibility lowercase = dense_act_fn super().__init__( pad_token_id=snake_case__ , eos_token_id=snake_case__ , decoder_start_token_id=snake_case__ , tie_word_embeddings=snake_case__ , is_decoder=snake_case__ , **snake_case__ , ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Optional[int] , snake_case__ : Union[str, os.PathLike] , **snake_case__ : int ): cls._set_token_in_kwargs(snake_case__ ) lowercase , lowercase = cls.get_config_dict(snake_case__ , **snake_case__ ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": lowercase = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(snake_case__ , **snake_case__ ) class A_ ( __a ): _A :Optional[int] = '''pix2struct_vision_model''' def __init__( self : Tuple , snake_case__ : Union[str, Any]=7_68 , snake_case__ : Any=7_68 , snake_case__ : Dict=20_48 , snake_case__ : int=64 , snake_case__ : str=12 , snake_case__ : Optional[int]=12 , snake_case__ : Union[str, Any]="gelu_new" , snake_case__ : Union[str, Any]=1E-6 , snake_case__ : int=0.0 , snake_case__ : Tuple=0.0 , snake_case__ : Optional[int]=1E-10 , snake_case__ : Optional[int]=1.0 , snake_case__ : Optional[Any]=40_96 , snake_case__ : Optional[int]=32 , snake_case__ : List[Any]=1_28 , **snake_case__ : Union[str, Any] , ): super().__init__(**snake_case__ ) lowercase = hidden_size lowercase = patch_embed_hidden_size lowercase = d_ff lowercase = dropout_rate lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = initializer_range lowercase = initializer_factor lowercase = attention_dropout lowercase = layer_norm_eps lowercase = dense_act_fn lowercase = seq_len lowercase = relative_attention_num_buckets lowercase = relative_attention_max_distance lowercase = d_kv @classmethod def SCREAMING_SNAKE_CASE__ ( cls : List[Any] , snake_case__ : Union[str, os.PathLike] , **snake_case__ : int ): cls._set_token_in_kwargs(snake_case__ ) lowercase , lowercase = cls.get_config_dict(snake_case__ , **snake_case__ ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": lowercase = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(snake_case__ , **snake_case__ ) class A_ ( __a ): _A :int = '''pix2struct''' _A :str = True def __init__( self : Optional[int] , snake_case__ : List[str]=None , snake_case__ : Optional[Any]=None , snake_case__ : List[Any]=1.0 , snake_case__ : Any=0.02 , snake_case__ : Tuple=False , snake_case__ : Union[str, Any]=False , snake_case__ : Tuple=True , **snake_case__ : int , ): super().__init__(tie_word_embeddings=snake_case__ , is_encoder_decoder=snake_case__ , **snake_case__ ) if text_config is None: lowercase = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: lowercase = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) lowercase = PixaStructTextConfig(**snake_case__ ) lowercase = PixaStructVisionConfig(**snake_case__ ) lowercase = self.text_config.decoder_start_token_id lowercase = self.text_config.pad_token_id lowercase = self.text_config.eos_token_id lowercase = initializer_factor lowercase = initializer_range lowercase = self.initializer_range lowercase = self.initializer_range lowercase = is_vqa @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple , snake_case__ : PixaStructTextConfig , snake_case__ : PixaStructVisionConfig , **snake_case__ : Any ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : str ): lowercase = copy.deepcopy(self.__dict__ ) lowercase = self.text_config.to_dict() lowercase = self.vision_config.to_dict() lowercase = self.__class__.model_type return output
718
# using dfs for finding eulerian path traversal def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=None ): lowercase = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: lowercase , lowercase = True, True lowercase = dfs(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) return path def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = 0 lowercase = -1 for i in range(lowerCAmelCase__ ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 lowercase = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] lowercase , lowercase = check_circuit_or_path(lowerCAmelCase__ ,lowerCAmelCase__ ) if check == 3: print("""graph is not Eulerian""" ) print("""no path""" ) return lowercase = 1 if check == 2: lowercase = odd_node print("""graph has a Euler path""" ) if check == 1: print("""graph has a Euler cycle""" ) lowercase = dfs(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) print(lowerCAmelCase__ ) def UpperCamelCase__ ( ): lowercase = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} lowercase = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} lowercase = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} lowercase = {1: [2, 3], 2: [1, 3], 3: [1, 2]} lowercase = { 1: [], 2: [] # all degree is zero } lowercase = 10 check_euler(lowerCAmelCase__ ,lowerCAmelCase__ ) check_euler(lowerCAmelCase__ ,lowerCAmelCase__ ) check_euler(lowerCAmelCase__ ,lowerCAmelCase__ ) check_euler(lowerCAmelCase__ ,lowerCAmelCase__ ) check_euler(lowerCAmelCase__ ,lowerCAmelCase__ ) if __name__ == "__main__": main()
72
0
from __future__ import annotations import time import numpy as np __SCREAMING_SNAKE_CASE : Tuple =[8, 5, 9, 7] __SCREAMING_SNAKE_CASE : List[str] =[ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] __SCREAMING_SNAKE_CASE : str =[ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class A_ : def __init__( self : Optional[Any] , snake_case__ : list[int] , snake_case__ : list[list[int]] , snake_case__ : list[list[int]] , ): lowercase = claim_vector lowercase = allocated_resources_table lowercase = maximum_claim_table def SCREAMING_SNAKE_CASE__ ( self : List[str] ): return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def SCREAMING_SNAKE_CASE__ ( self : List[str] ): return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(snake_case__ ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def SCREAMING_SNAKE_CASE__ ( self : Any ): return {self.__need().index(snake_case__ ): i for i in self.__need()} def SCREAMING_SNAKE_CASE__ ( self : Any , **snake_case__ : int ): lowercase = self.__need() lowercase = self.__allocated_resources_table lowercase = self.__available_resources() lowercase = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 50 + """\n""" ) while need_list: lowercase = False for each_need in need_list: lowercase = True for index, need in enumerate(snake_case__ ): if need > available_resources[index]: lowercase = False break if execution: lowercase = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: lowercase = original_need_index print(F"""Process {process_number + 1} is executing.""" ) # remove the process run from stack need_list.remove(snake_case__ ) # update available/freed resources stack lowercase = np.array(snake_case__ ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(snake_case__ ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(snake_case__ ) + 1}""" + """ """.join(F"""{it:>8}""" for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( F"""P{self.__maximum_claim_table.index(snake_case__ ) + 1}""" + """ """.join(F"""{it:>8}""" for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(snake_case__ ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(snake_case__ ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
719
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class A_ ( unittest.TestCase ): def __init__( self : List[str] , snake_case__ : Optional[Any] , snake_case__ : List[str]=13 , snake_case__ : List[str]=7 , snake_case__ : Union[str, Any]=True , snake_case__ : int=True , snake_case__ : List[Any]=True , snake_case__ : List[Any]=True , snake_case__ : Optional[int]=99 , snake_case__ : Any=32 , snake_case__ : Any=5 , snake_case__ : int=4 , snake_case__ : Optional[Any]=37 , snake_case__ : Dict="gelu" , snake_case__ : Tuple=0.1 , snake_case__ : Tuple=0.1 , snake_case__ : int=5_12 , snake_case__ : Optional[Any]=16 , snake_case__ : List[Any]=2 , snake_case__ : Union[str, Any]=0.02 , snake_case__ : List[str]=4 , ): lowercase = parent lowercase = batch_size lowercase = seq_length lowercase = is_training lowercase = use_attention_mask lowercase = use_token_type_ids lowercase = use_labels lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = intermediate_size lowercase = hidden_act lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = type_vocab_size lowercase = type_sequence_label_size lowercase = initializer_range lowercase = num_choices def SCREAMING_SNAKE_CASE__ ( self : List[str] ): lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase = None if self.use_attention_mask: lowercase = random_attention_mask([self.batch_size, self.seq_length] ) lowercase = None if self.use_token_type_ids: lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase = RoFormerConfig( 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=snake_case__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE__ ( self : Any ): lowercase = self.prepare_config_and_inputs() lowercase , lowercase , lowercase , lowercase = config_and_inputs lowercase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class A_ ( __a , unittest.TestCase ): _A :List[Any] = True _A :Union[str, Any] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE__ ( self : int ): lowercase = FlaxRoFormerModelTester(self ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): for model_class_name in self.all_model_classes: lowercase = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=snake_case__ ) lowercase = model(np.ones((1, 1) ) ) self.assertIsNotNone(snake_case__ ) @require_flax class A_ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowercase = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) lowercase = jnp.array([[0, 1, 2, 3, 4, 5]] ) lowercase = model(snake_case__ )[0] lowercase = 5_00_00 lowercase = (1, 6, vocab_size) self.assertEqual(output.shape , snake_case__ ) lowercase = jnp.array( [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , snake_case__ , atol=1E-4 ) )
72
0
# limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class A_ ( __a ): def __init__( self : Tuple , snake_case__ : Any , snake_case__ : int ): super().__init__() self.register_modules(unet=snake_case__ , scheduler=snake_case__ ) @torch.no_grad() def __call__( self : Optional[int] , snake_case__ : int = 1 , snake_case__ : Optional[torch.Generator] = None , snake_case__ : int = 50 , snake_case__ : Optional[str] = "pil" , snake_case__ : bool = True , **snake_case__ : Tuple , ): lowercase = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=snake_case__ , ) lowercase = image.to(self.device ) # set step values self.scheduler.set_timesteps(snake_case__ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output lowercase = self.unet(snake_case__ , snake_case__ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowercase = self.scheduler.step(snake_case__ , snake_case__ , snake_case__ ).prev_sample lowercase = (image / 2 + 0.5).clamp(0 , 1 ) lowercase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowercase = self.numpy_to_pil(snake_case__ ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=snake_case__ ), "This is a local test"
720
import argparse import hashlib # hashlib is only used inside the Test class import struct class A_ : def __init__( self : List[str] , snake_case__ : Union[str, Any] ): lowercase = data lowercase = [0X6_7_4_5_2_3_0_1, 0Xe_f_c_d_a_b_8_9, 0X9_8_b_a_d_c_f_e, 0X1_0_3_2_5_4_7_6, 0Xc_3_d_2_e_1_f_0] @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case__ : Union[str, Any] , snake_case__ : Optional[int] ): return ((n << b) | (n >> (32 - b))) & 0Xf_f_f_f_f_f_f_f def SCREAMING_SNAKE_CASE__ ( self : List[str] ): lowercase = b"""\x80""" + b"""\x00""" * (63 - (len(self.data ) + 8) % 64) lowercase = self.data + padding + struct.pack(""">Q""" , 8 * len(self.data ) ) return padded_data def SCREAMING_SNAKE_CASE__ ( self : List[str] ): return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def SCREAMING_SNAKE_CASE__ ( self : str , snake_case__ : Tuple ): lowercase = list(struct.unpack(""">16L""" , snake_case__ ) ) + [0] * 64 for i in range(16 , 80 ): lowercase = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def SCREAMING_SNAKE_CASE__ ( self : Any ): lowercase = self.padding() lowercase = self.split_blocks() for block in self.blocks: lowercase = self.expand_block(snake_case__ ) lowercase , lowercase , lowercase , lowercase , lowercase = self.h for i in range(0 , 80 ): if 0 <= i < 20: lowercase = (b & c) | ((~b) & d) lowercase = 0X5_a_8_2_7_9_9_9 elif 20 <= i < 40: lowercase = b ^ c ^ d lowercase = 0X6_e_d_9_e_b_a_1 elif 40 <= i < 60: lowercase = (b & c) | (b & d) | (c & d) lowercase = 0X8_f_1_b_b_c_d_c elif 60 <= i < 80: lowercase = b ^ c ^ d lowercase = 0Xc_a_6_2_c_1_d_6 lowercase , lowercase , lowercase , lowercase , lowercase = ( self.rotate(snake_case__ , 5 ) + f + e + k + expanded_block[i] & 0Xf_f_f_f_f_f_f_f, a, self.rotate(snake_case__ , 30 ), c, d, ) lowercase = ( self.h[0] + a & 0Xf_f_f_f_f_f_f_f, self.h[1] + b & 0Xf_f_f_f_f_f_f_f, self.h[2] + c & 0Xf_f_f_f_f_f_f_f, self.h[3] + d & 0Xf_f_f_f_f_f_f_f, self.h[4] + e & 0Xf_f_f_f_f_f_f_f, ) return ("{:08x}" * 5).format(*self.h ) def UpperCamelCase__ ( ): lowercase = b"""Test String""" assert SHAaHash(lowerCAmelCase__ ).final_hash() == hashlib.shaa(lowerCAmelCase__ ).hexdigest() # noqa: S324 def UpperCamelCase__ ( ): lowercase = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" ,dest="""input_string""" ,default="""Hello World!! Welcome to Cryptography""" ,help="""Hash the string""" ,) parser.add_argument("""--file""" ,dest="""input_file""" ,help="""Hash contents of a file""" ) lowercase = parser.parse_args() lowercase = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file ,"""rb""" ) as f: lowercase = f.read() else: lowercase = bytes(lowerCAmelCase__ ,"""utf-8""" ) print(SHAaHash(lowerCAmelCase__ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
72
0
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
721
class A_ : def __init__( self : Optional[Any] , snake_case__ : Dict , snake_case__ : Union[str, Any] ): lowercase = name lowercase = val def __str__( self : str ): return F"""{self.__class__.__name__}({self.name}, {self.val})""" def __lt__( self : int , snake_case__ : Optional[int] ): return self.val < other.val class A_ : def __init__( self : str , snake_case__ : List[str] ): lowercase = {} lowercase = {} lowercase = self.build_heap(snake_case__ ) def __getitem__( self : Union[str, Any] , snake_case__ : int ): return self.get_value(snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case__ : Optional[Any] ): return (idx - 1) // 2 def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case__ : Dict ): return idx * 2 + 1 def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case__ : Optional[Any] ): return idx * 2 + 2 def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case__ : Dict ): return self.heap_dict[key] def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case__ : Any ): lowercase = len(snake_case__ ) - 1 lowercase = self.get_parent_idx(snake_case__ ) for idx, i in enumerate(snake_case__ ): lowercase = idx lowercase = i.val for i in range(snake_case__ , -1 , -1 ): self.sift_down(snake_case__ , snake_case__ ) return array def SCREAMING_SNAKE_CASE__ ( self : List[str] , snake_case__ : int , snake_case__ : str ): while True: lowercase = self.get_left_child_idx(snake_case__ ) # noqa: E741 lowercase = self.get_right_child_idx(snake_case__ ) lowercase = idx if l < len(snake_case__ ) and array[l] < array[idx]: lowercase = l if r < len(snake_case__ ) and array[r] < array[smallest]: lowercase = r if smallest != idx: lowercase , lowercase = array[smallest], array[idx] ( ( lowercase ) , ( lowercase ) , ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) lowercase = smallest else: break def SCREAMING_SNAKE_CASE__ ( self : List[str] , snake_case__ : Optional[int] ): lowercase = self.get_parent_idx(snake_case__ ) while p >= 0 and self.heap[p] > self.heap[idx]: lowercase , lowercase = self.heap[idx], self.heap[p] lowercase , lowercase = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) lowercase = p lowercase = self.get_parent_idx(snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : int ): return self.heap[0] def SCREAMING_SNAKE_CASE__ ( self : Any ): lowercase , lowercase = self.heap[-1], self.heap[0] lowercase , lowercase = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) lowercase = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def SCREAMING_SNAKE_CASE__ ( self : List[str] , snake_case__ : Union[str, Any] ): self.heap.append(snake_case__ ) lowercase = len(self.heap ) - 1 lowercase = node.val self.sift_up(len(self.heap ) - 1 ) def SCREAMING_SNAKE_CASE__ ( self : int ): return len(self.heap ) == 0 def SCREAMING_SNAKE_CASE__ ( self : int , snake_case__ : int , snake_case__ : Dict ): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" lowercase = new_value lowercase = new_value self.sift_up(self.idx_of_element[node] ) __SCREAMING_SNAKE_CASE : Any =Node('''R''', -1) __SCREAMING_SNAKE_CASE : Union[str, Any] =Node('''B''', 6) __SCREAMING_SNAKE_CASE : str =Node('''A''', 3) __SCREAMING_SNAKE_CASE : List[Any] =Node('''X''', 1) __SCREAMING_SNAKE_CASE : str =Node('''E''', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __SCREAMING_SNAKE_CASE : Any =MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('''Min Heap - before decrease key''') for i in my_min_heap.heap: print(i) print('''Min Heap - After decrease key of node [B -> -17]''') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
72
0
import colorsys from PIL import Image # type: ignore def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : int = x lowerCamelCase_ : Dict = y for step in range(lowerCAmelCase_): # noqa: B007 lowerCamelCase_ : Union[str, Any] = a * a - b * b + x lowerCamelCase_ : List[str] = 2 * a * b + y lowerCamelCase_ : Union[str, Any] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(lowerCAmelCase_ , 1 , 1)) def __magic_name__ ( lowerCAmelCase_ = 800 , lowerCAmelCase_ = 600 , lowerCAmelCase_ = -0.6 , lowerCAmelCase_ = 0 , lowerCAmelCase_ = 3.2 , lowerCAmelCase_ = 50 , lowerCAmelCase_ = True , ): '''simple docstring''' lowerCamelCase_ : Tuple = Image.new("RGB" , (image_width, image_height)) lowerCamelCase_ : Optional[int] = img.load() # loop through the image-coordinates for image_x in range(lowerCAmelCase_): for image_y in range(lowerCAmelCase_): # determine the figure-coordinates based on the image-coordinates lowerCamelCase_ : List[str] = figure_width / image_width * image_height lowerCamelCase_ : Optional[Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width lowerCamelCase_ : Tuple = figure_center_y + (image_y / image_height - 0.5) * figure_height lowerCamelCase_ : Any = get_distance(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: lowerCamelCase_ : Optional[int] = get_color_coded_rgb(lowerCAmelCase_) else: lowerCamelCase_ : Union[str, Any] = get_black_and_white_rgb(lowerCAmelCase_) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure __magic_name__ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
73
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = StableDiffusionDiffEditPipeline __UpperCAmelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} __UpperCAmelCase : Any = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} __UpperCAmelCase : List[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __UpperCAmelCase : List[str] = frozenset([] ) def _UpperCamelCase ( self ): torch.manual_seed(0 ) lowerCamelCase_ : str = 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 , attention_head_dim=(2, 4) , use_linear_projection=a_ , ) lowerCamelCase_ : str = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , ) lowerCamelCase_ : Dict = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_zero=a_ , ) torch.manual_seed(0 ) lowerCamelCase_ : List[Any] = 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 ) lowerCamelCase_ : Union[str, 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 , ) lowerCamelCase_ : Optional[Any] = CLIPTextModel(a_ ) lowerCamelCase_ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCamelCase_ : Optional[Any] = { "unet": unet, "scheduler": scheduler, "inverse_scheduler": inverse_scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : str = floats_tensor((1, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : List[Any] = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : List[Any] = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[str] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Tuple = { "prompt": "a dog and a newt", "mask_image": mask, "image_latents": latents, "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Any = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Tuple = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : int = { "image": image, "source_prompt": "a cat and a frog", "target_prompt": "a dog and a newt", "generator": generator, "num_inference_steps": 2, "num_maps_per_mask": 2, "mask_encode_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Optional[int] = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Optional[int] = torch.manual_seed(a_ ) else: lowerCamelCase_ : Tuple = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Union[str, Any] = { "image": image, "prompt": "a cat and a frog", "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "decode_latents": True, "output_type": "numpy", } return inputs def _UpperCamelCase ( self ): if not hasattr(self.pipeline_class , "_optional_components" ): return lowerCamelCase_ : List[Any] = self.get_dummy_components() lowerCamelCase_ : int = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a_ , a_ , a_ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) lowerCamelCase_ : int = self.get_dummy_inputs(a_ ) lowerCamelCase_ : int = pipe(**a_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a_ ) lowerCamelCase_ : Optional[int] = self.pipeline_class.from_pretrained(a_ ) pipe_loaded.to(a_ ) pipe_loaded.set_progress_bar_config(disable=a_ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(a_ , a_ ) is None , F"""`{optional_component}` did not stay set to None after loading.""" , ) lowerCamelCase_ : List[str] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Optional[int] = pipe_loaded(**a_ )[0] lowerCamelCase_ : Optional[int] = np.abs(output - output_loaded ).max() self.assertLess(a_ , 1E-4 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : List[Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = self.get_dummy_mask_inputs(a_ ) lowerCamelCase_ : int = pipe.generate_mask(**a_ ) lowerCamelCase_ : List[Any] = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) lowerCamelCase_ : List[str] = np.array([0] * 9 ) lowerCamelCase_ : Optional[int] = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : Union[str, Any] = self.get_dummy_components() lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Dict = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : Dict = pipe.invert(**a_ ).images lowerCamelCase_ : str = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Dict = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : Any = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) def _UpperCamelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : int = {"beta_start": 0.0_00_85, "beta_end": 0.0_12, "beta_schedule": "scaled_linear"} lowerCamelCase_ : Optional[Any] = DPMSolverMultistepScheduler(**a_ ) lowerCamelCase_ : List[str] = DPMSolverMultistepInverseScheduler(**a_ ) lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : int = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : str = pipe.invert(**a_ ).images lowerCamelCase_ : int = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Union[str, Any] = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def _UpperCamelCase ( cls ): lowerCamelCase_ : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png" ) lowerCamelCase_ : int = raw_image.convert("RGB" ).resize((768, 768) ) lowerCamelCase_ : List[Any] = raw_image def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = torch.manual_seed(0 ) lowerCamelCase_ : Tuple = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : str = DDIMScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : Optional[int] = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : str = "a bowl of fruit" lowerCamelCase_ : Optional[int] = "a bowl of pears" lowerCamelCase_ : List[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ ).latents lowerCamelCase_ : List[str] = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = torch.manual_seed(0 ) lowerCamelCase_ : str = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : str = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = "a bowl of fruit" lowerCamelCase_ : Dict = "a bowl of pears" lowerCamelCase_ : Optional[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ , num_inference_steps=25 , ).latents lowerCamelCase_ : Any = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , num_inference_steps=25 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
73
1
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Tuple = [False] * len(lowerCAmelCase_) lowerCamelCase_ : Any = [-1] * len(lowerCAmelCase_) def dfs(lowerCAmelCase_ , lowerCAmelCase_): lowerCamelCase_ : Dict = True lowerCamelCase_ : Any = c for u in graph[v]: if not visited[u]: dfs(lowerCAmelCase_ , 1 - c) for i in range(len(lowerCAmelCase_)): if not visited[i]: dfs(lowerCAmelCase_ , 0) for i in range(len(lowerCAmelCase_)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph __magic_name__ = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
73
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : int = ["a", "b", "c"] # Defaults to last layer if both are None lowerCamelCase_ ,lowerCamelCase_ : Tuple = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ["c"] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = get_aligned_output_features_output_indices(["a", "c"] , a_ , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices lowerCamelCase_ ,lowerCamelCase_ : Tuple = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices lowerCamelCase_ ,lowerCamelCase_ : Dict = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [-3, -1] ) def _UpperCamelCase ( self ): # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = BackboneMixin() lowerCamelCase_ : List[Any] = ["a", "b", "c"] lowerCamelCase_ : Optional[int] = ["a", "c"] lowerCamelCase_ : Dict = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly lowerCamelCase_ : Union[str, Any] = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) lowerCamelCase_ : str = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
73
1
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : int = len(lowerCAmelCase_) lowerCamelCase_ : List[str] = [] for i in range(len(lowerCAmelCase_) - pat_len + 1): lowerCamelCase_ : Optional[Any] = True for j in range(lowerCAmelCase_): if s[i + j] != pattern[j]: lowerCamelCase_ : Optional[Any] = False break if match_found: position.append(lowerCAmelCase_) return position if __name__ == "__main__": assert naive_pattern_search('''ABCDEFG''', '''DE''') == [3] print(naive_pattern_search('''ABAAABCDBBABCDDEBCABC''', '''ABC'''))
73
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : Union[str, Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Tuple = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : int = '''default_config.yaml''' __UpperCAmelCase : Tuple = config_folder / config_file __UpperCAmelCase : int = config_folder / '''_default_config.yaml''' __UpperCAmelCase : int = Path('''tests/test_configs''' ) @classmethod def _UpperCamelCase ( cls ): if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def _UpperCamelCase ( cls ): if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def _UpperCamelCase ( self ): for config in sorted(self.test_config_path.glob("**/*.yaml" ) ): with self.subTest(config_file=a_ ): execute_subprocess_async( self.base_cmd + ["--config_file", str(a_ ), self.test_file_path] , env=os.environ.copy() ) def _UpperCamelCase ( self ): execute_subprocess_async(["accelerate", "test"] , env=os.environ.copy() ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[Any] = '''test-tpu''' __UpperCAmelCase : Tuple = '''us-central1-a''' __UpperCAmelCase : Tuple = '''ls''' __UpperCAmelCase : str = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : Dict = '''Running gcloud compute tpus tpu-vm ssh''' def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + ["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--debug"] , return_stdout=a_ ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--command", "echo \"Hello World\"", "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command_file", self.command_file, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--accelerate_version", "12.0.0", "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , )
73
1
import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Tuple = 3 lowerCamelCase_ : List[Any] = 250 lowerCamelCase_ : Optional[int] = ids_tensor((batch_size, length) , a_ ) lowerCamelCase_ : List[str] = torch.ones((batch_size, length) , device=a_ , dtype=torch.float ) / length return input_ids, scores def _UpperCamelCase ( self ): lowerCamelCase_ ,lowerCamelCase_ : Dict = self._get_tensors(5 ) lowerCamelCase_ : str = StoppingCriteriaList( [ MaxLengthCriteria(max_length=10 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(a_ , a_ ) ) lowerCamelCase_ ,lowerCamelCase_ : Tuple = self._get_tensors(9 ) self.assertFalse(criteria(a_ , a_ ) ) lowerCamelCase_ ,lowerCamelCase_ : Any = self._get_tensors(10 ) self.assertTrue(criteria(a_ , a_ ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = MaxLengthCriteria(max_length=10 ) lowerCamelCase_ ,lowerCamelCase_ : Tuple = self._get_tensors(5 ) self.assertFalse(criteria(a_ , a_ ) ) lowerCamelCase_ ,lowerCamelCase_ : Any = self._get_tensors(9 ) self.assertFalse(criteria(a_ , a_ ) ) lowerCamelCase_ ,lowerCamelCase_ : Dict = self._get_tensors(10 ) self.assertTrue(criteria(a_ , a_ ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) lowerCamelCase_ ,lowerCamelCase_ : str = self._get_tensors(5 ) self.assertFalse(criteria(a_ , a_ ) ) lowerCamelCase_ ,lowerCamelCase_ : List[Any] = self._get_tensors(9 ) self.assertFalse(criteria(a_ , a_ ) ) lowerCamelCase_ ,lowerCamelCase_ : Union[str, Any] = self._get_tensors(10 ) self.assertTrue(criteria(a_ , a_ ) ) lowerCamelCase_ : List[Any] = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 10 ) def _UpperCamelCase ( self ): lowerCamelCase_ ,lowerCamelCase_ : List[str] = self._get_tensors(5 ) lowerCamelCase_ : Optional[Any] = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(a_ , a_ ) ) lowerCamelCase_ : List[str] = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(a_ , a_ ) ) def _UpperCamelCase ( self ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 ) with self.assertWarns(a_ ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 ) lowerCamelCase_ : Tuple = validate_stopping_criteria(StoppingCriteriaList() , 11 ) self.assertEqual(len(a_ ) , 1 )
73
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ , a_ ): super().__init__() self.register_modules(vqvae=a_ , unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self , a_ = 1 , a_ = None , a_ = 0.0 , a_ = 50 , a_ = "pil" , a_ = True , **a_ , ): lowerCamelCase_ : Optional[Any] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=a_ , ) lowerCamelCase_ : Optional[int] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ : Optional[int] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(a_ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature lowerCamelCase_ : Any = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ : Optional[int] = {} if accepts_eta: lowerCamelCase_ : Optional[int] = eta for t in self.progress_bar(self.scheduler.timesteps ): lowerCamelCase_ : Dict = self.scheduler.scale_model_input(a_ , a_ ) # predict the noise residual lowerCamelCase_ : Optional[Any] = self.unet(a_ , a_ ).sample # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ : List[Any] = self.scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample # decode the image latents with the VAE lowerCamelCase_ : str = self.vqvae.decode(a_ ).sample lowerCamelCase_ : Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) lowerCamelCase_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase_ : Optional[Any] = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
73
1
__magic_name__ = {} def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''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 lowerCamelCase_ : Dict = (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 lowerCamelCase_ : List[Any] = _calculate(days - 1 , lowerCAmelCase_ , late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 lowerCamelCase_ : Dict = _calculate(days - 1 , absent + 1 , 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter lowerCamelCase_ : Optional[int] = _calculate(days - 1 , lowerCAmelCase_ , 0) lowerCamelCase_ : List[str] = state_late + state_absent + state_ontime lowerCamelCase_ : Dict = prizestrings return prizestrings def __magic_name__ ( lowerCAmelCase_ = 30): '''simple docstring''' return _calculate(lowerCAmelCase_ , absent=0 , late=0) if __name__ == "__main__": print(solution())
73
import re def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if len(re.findall("[ATCG]" , lowerCAmelCase_)) != len(lowerCAmelCase_): raise ValueError("Invalid Strand") return dna.translate(dna.maketrans("ATCG" , "TAGC")) if __name__ == "__main__": import doctest doctest.testmod()
73
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = '''encoder-decoder''' __UpperCAmelCase : int = True def __init__( self , **a_ ): super().__init__(**a_ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" lowerCamelCase_ : Tuple = kwargs.pop("encoder" ) lowerCamelCase_ : List[str] = encoder_config.pop("model_type" ) lowerCamelCase_ : List[Any] = kwargs.pop("decoder" ) lowerCamelCase_ : List[str] = decoder_config.pop("model_type" ) from ..auto.configuration_auto import AutoConfig lowerCamelCase_ : Tuple = AutoConfig.for_model(a_ , **a_ ) lowerCamelCase_ : Optional[int] = AutoConfig.for_model(a_ , **a_ ) lowerCamelCase_ : List[Any] = True @classmethod def _UpperCamelCase ( cls , a_ , a_ , **a_ ): logger.info("Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config" ) lowerCamelCase_ : Dict = True lowerCamelCase_ : Optional[int] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : int = copy.deepcopy(self.__dict__ ) lowerCamelCase_ : str = self.encoder.to_dict() lowerCamelCase_ : Any = self.decoder.to_dict() lowerCamelCase_ : List[Any] = self.__class__.model_type return output
73
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False): '''simple docstring''' if radian_mode: return [magnitude * cos(lowerCAmelCase_), magnitude * sin(lowerCAmelCase_)] return [magnitude * cos(radians(lowerCAmelCase_)), magnitude * sin(radians(lowerCAmelCase_))] def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 10**-1): '''simple docstring''' lowerCamelCase_ : NDArray[floataa] = cross(lowerCAmelCase_ , lowerCAmelCase_) lowerCamelCase_ : float = sum(lowerCAmelCase_) return abs(lowerCAmelCase_) < eps if __name__ == "__main__": # Test to check if it works __magic_name__ = array( [ polar_force(7_18.4, 1_8_0 - 3_0), polar_force(8_79.54, 4_5), polar_force(1_0_0, -9_0), ] ) __magic_name__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg __magic_name__ = array( [ polar_force(3_0 * 9.81, 1_5), polar_force(2_1_5, 1_8_0 - 4_5), polar_force(2_6_4, 9_0 - 3_0), ] ) __magic_name__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg __magic_name__ = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]]) __magic_name__ = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
1
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = StableDiffusionDiffEditPipeline __UpperCAmelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} __UpperCAmelCase : Any = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} __UpperCAmelCase : List[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __UpperCAmelCase : List[str] = frozenset([] ) def _UpperCamelCase ( self ): torch.manual_seed(0 ) lowerCamelCase_ : str = 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 , attention_head_dim=(2, 4) , use_linear_projection=a_ , ) lowerCamelCase_ : str = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , ) lowerCamelCase_ : Dict = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_zero=a_ , ) torch.manual_seed(0 ) lowerCamelCase_ : List[Any] = 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 ) lowerCamelCase_ : Union[str, 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 , ) lowerCamelCase_ : Optional[Any] = CLIPTextModel(a_ ) lowerCamelCase_ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCamelCase_ : Optional[Any] = { "unet": unet, "scheduler": scheduler, "inverse_scheduler": inverse_scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : str = floats_tensor((1, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : List[Any] = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : List[Any] = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[str] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Tuple = { "prompt": "a dog and a newt", "mask_image": mask, "image_latents": latents, "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Any = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Tuple = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : int = { "image": image, "source_prompt": "a cat and a frog", "target_prompt": "a dog and a newt", "generator": generator, "num_inference_steps": 2, "num_maps_per_mask": 2, "mask_encode_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Optional[int] = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Optional[int] = torch.manual_seed(a_ ) else: lowerCamelCase_ : Tuple = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Union[str, Any] = { "image": image, "prompt": "a cat and a frog", "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "decode_latents": True, "output_type": "numpy", } return inputs def _UpperCamelCase ( self ): if not hasattr(self.pipeline_class , "_optional_components" ): return lowerCamelCase_ : List[Any] = self.get_dummy_components() lowerCamelCase_ : int = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a_ , a_ , a_ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) lowerCamelCase_ : int = self.get_dummy_inputs(a_ ) lowerCamelCase_ : int = pipe(**a_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a_ ) lowerCamelCase_ : Optional[int] = self.pipeline_class.from_pretrained(a_ ) pipe_loaded.to(a_ ) pipe_loaded.set_progress_bar_config(disable=a_ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(a_ , a_ ) is None , F"""`{optional_component}` did not stay set to None after loading.""" , ) lowerCamelCase_ : List[str] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Optional[int] = pipe_loaded(**a_ )[0] lowerCamelCase_ : Optional[int] = np.abs(output - output_loaded ).max() self.assertLess(a_ , 1E-4 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : List[Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = self.get_dummy_mask_inputs(a_ ) lowerCamelCase_ : int = pipe.generate_mask(**a_ ) lowerCamelCase_ : List[Any] = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) lowerCamelCase_ : List[str] = np.array([0] * 9 ) lowerCamelCase_ : Optional[int] = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : Union[str, Any] = self.get_dummy_components() lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Dict = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : Dict = pipe.invert(**a_ ).images lowerCamelCase_ : str = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Dict = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : Any = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) def _UpperCamelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : int = {"beta_start": 0.0_00_85, "beta_end": 0.0_12, "beta_schedule": "scaled_linear"} lowerCamelCase_ : Optional[Any] = DPMSolverMultistepScheduler(**a_ ) lowerCamelCase_ : List[str] = DPMSolverMultistepInverseScheduler(**a_ ) lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : int = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : str = pipe.invert(**a_ ).images lowerCamelCase_ : int = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Union[str, Any] = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def _UpperCamelCase ( cls ): lowerCamelCase_ : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png" ) lowerCamelCase_ : int = raw_image.convert("RGB" ).resize((768, 768) ) lowerCamelCase_ : List[Any] = raw_image def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = torch.manual_seed(0 ) lowerCamelCase_ : Tuple = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : str = DDIMScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : Optional[int] = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : str = "a bowl of fruit" lowerCamelCase_ : Optional[int] = "a bowl of pears" lowerCamelCase_ : List[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ ).latents lowerCamelCase_ : List[str] = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = torch.manual_seed(0 ) lowerCamelCase_ : str = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : str = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = "a bowl of fruit" lowerCamelCase_ : Dict = "a bowl of pears" lowerCamelCase_ : Optional[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ , num_inference_steps=25 , ).latents lowerCamelCase_ : Any = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , num_inference_steps=25 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
73
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''ClapFeatureExtractor''' __UpperCAmelCase : List[str] = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) def __call__( self , a_=None , a_=None , a_=None , **a_ ): lowerCamelCase_ : Any = kwargs.pop("sampling_rate" , a_ ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: lowerCamelCase_ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if audios is not None: lowerCamelCase_ : List[str] = self.feature_extractor( a_ , sampling_rate=a_ , return_tensors=a_ , **a_ ) if text is not None and audios is not None: lowerCamelCase_ : List[str] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) @property def _UpperCamelCase ( self ): lowerCamelCase_ : int = self.tokenizer.model_input_names lowerCamelCase_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
73
1
import os def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : str = os.path.join(os.path.dirname(lowerCAmelCase_) , "num.txt") with open(lowerCAmelCase_) as file_hand: return str(sum(int(lowerCAmelCase_) for line in file_hand))[:10] if __name__ == "__main__": print(solution())
73
def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : Any = set() # Replace all the whitespace in our sentence lowerCamelCase_ : str = input_str.replace(" " , "") for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(lowerCAmelCase_) == 26 def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : List[Any] = [False] * 26 for char in input_str: if char.islower(): lowerCamelCase_ : List[Any] = True elif char.isupper(): lowerCamelCase_ : Optional[int] = True return all(lowerCAmelCase_) def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()}) == 26 def __magic_name__ ( ): '''simple docstring''' from timeit import timeit lowerCamelCase_ : Optional[int] = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_faster()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_fastest()" , setup=lowerCAmelCase_)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
73
1
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = FunnelTokenizer __UpperCAmelCase : str = FunnelTokenizerFast __UpperCAmelCase : List[Any] = True __UpperCAmelCase : int = True def _UpperCamelCase ( self ): super().setUp() lowerCamelCase_ : Union[str, Any] = [ "<unk>", "<cls>", "<sep>", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] lowerCamelCase_ : str = 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 _UpperCamelCase ( self , **a_ ): return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def _UpperCamelCase ( self , **a_ ): return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Dict = "UNwant\u00E9d,running" lowerCamelCase_ : Any = "unwanted, running" return input_text, output_text def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = self.tokenizer_class(self.vocab_file ) lowerCamelCase_ : Tuple = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(a_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: lowerCamelCase_ : Union[str, Any] = tokenizer("UNwant\u00E9d,running" ) lowerCamelCase_ : Union[str, Any] = len(inputs["input_ids"] ) - 1 self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len ) lowerCamelCase_ : List[str] = tokenizer("UNwant\u00E9d,running" , "UNwant\u00E9d,running" ) self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len + [1] * sentence_len )
73
__magic_name__ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634E-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.35_58_18, } def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: lowerCamelCase_ : List[Any] = ( F"""Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n""" F"""Valid values are: {', '.join(lowerCAmelCase_)}""" ) raise ValueError(lowerCAmelCase_) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
73
1
def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : Any = set() # Replace all the whitespace in our sentence lowerCamelCase_ : str = input_str.replace(" " , "") for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(lowerCAmelCase_) == 26 def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : List[Any] = [False] * 26 for char in input_str: if char.islower(): lowerCamelCase_ : List[Any] = True elif char.isupper(): lowerCamelCase_ : Optional[int] = True return all(lowerCAmelCase_) def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()}) == 26 def __magic_name__ ( ): '''simple docstring''' from timeit import timeit lowerCamelCase_ : Optional[int] = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_faster()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_fastest()" , setup=lowerCAmelCase_)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
73
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 __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'''vocab_file''': '''spiece.model'''} __magic_name__ = { '''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''', } } __magic_name__ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) __magic_name__ = 0 __magic_name__ = 1 __magic_name__ = 2 __magic_name__ = 3 __magic_name__ = 4 class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[int] = '''left''' def __init__( self , a_ , a_=False , a_=True , a_=False , a_="<s>" , a_="</s>" , a_="<unk>" , a_="<sep>" , a_="<pad>" , a_="<cls>" , a_="<mask>" , a_=["<eop>", "<eod>"] , a_ = None , **a_ , ): # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ : str = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token lowerCamelCase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) lowerCamelCase_ : str = 3 lowerCamelCase_ : Dict = do_lower_case lowerCamelCase_ : str = remove_space lowerCamelCase_ : Tuple = keep_accents lowerCamelCase_ : Dict = vocab_file lowerCamelCase_ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) @property def _UpperCamelCase ( self ): return len(self.sp_model ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowerCamelCase_ : Any = self.__dict__.copy() lowerCamelCase_ : Optional[int] = None return state def __setstate__( self , a_ ): lowerCamelCase_ : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase_ : int = {} lowerCamelCase_ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self , a_ ): if self.remove_space: lowerCamelCase_ : Optional[int] = " ".join(inputs.strip().split() ) else: lowerCamelCase_ : str = inputs lowerCamelCase_ : Any = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: lowerCamelCase_ : Dict = unicodedata.normalize("NFKD" , a_ ) lowerCamelCase_ : int = "".join([c for c in outputs if not unicodedata.combining(a_ )] ) if self.do_lower_case: lowerCamelCase_ : Any = outputs.lower() return outputs def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : List[Any] = self.preprocess_text(a_ ) lowerCamelCase_ : Optional[int] = self.sp_model.encode(a_ , out_type=a_ ) lowerCamelCase_ : List[str] = [] for piece in pieces: if len(a_ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): lowerCamelCase_ : Tuple = self.sp_model.EncodeAsPieces(piece[:-1].replace(a_ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase_ : int = cur_pieces[1:] else: lowerCamelCase_ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(a_ ) else: new_pieces.append(a_ ) return new_pieces def _UpperCamelCase ( self , a_ ): return self.sp_model.PieceToId(a_ ) def _UpperCamelCase ( self , a_ ): return self.sp_model.IdToPiece(a_ ) def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Dict = "".join(a_ ).replace(a_ , " " ).strip() return out_string def _UpperCamelCase ( self , a_ , a_ = False , a_ = None , a_ = True , **a_ , ): lowerCamelCase_ : int = kwargs.pop("use_source_tokenizer" , a_ ) lowerCamelCase_ : List[str] = self.convert_ids_to_tokens(a_ , skip_special_tokens=a_ ) # 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 lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : List[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(a_ ) ) lowerCamelCase_ : Union[str, Any] = [] sub_texts.append(a_ ) else: current_sub_text.append(a_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase_ : Union[str, Any] = "".join(a_ ) lowerCamelCase_ : Optional[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase_ : List[Any] = self.clean_up_tokenization(a_ ) return clean_text else: return text def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, 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 _UpperCamelCase ( self , a_ , a_ = None , a_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ ) if token_ids_a is not None: return ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1, 1] return ([0] * len(a_ )) + [1, 1] def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, Any] = [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 _UpperCamelCase ( self , a_ , a_ = None ): if not os.path.isdir(a_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase_ : Any = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , "wb" ) as fi: lowerCamelCase_ : Dict = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
73
1
def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not numbers: return 0 if not isinstance(lowerCAmelCase_ , (list, tuple)) or not all( isinstance(lowerCAmelCase_ , lowerCAmelCase_) for number in numbers): raise ValueError("numbers must be an iterable of integers") lowerCamelCase_ : List[str] = numbers[0] for i in range(1 , len(lowerCAmelCase_)): # update the maximum and minimum subarray products lowerCamelCase_ : List[Any] = numbers[i] if number < 0: lowerCamelCase_ ,lowerCamelCase_ : Optional[Any] = min_till_now, max_till_now lowerCamelCase_ : Dict = max(lowerCAmelCase_ , max_till_now * number) lowerCamelCase_ : Any = min(lowerCAmelCase_ , min_till_now * number) # update the maximum product found till now lowerCamelCase_ : Optional[int] = max(lowerCAmelCase_ , lowerCAmelCase_) return max_prod
73
def __magic_name__ ( lowerCAmelCase_ = 10 , lowerCAmelCase_ = 1000 , lowerCAmelCase_ = True): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)") return min_val if option else max_val def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' return int((number_a + number_a) / 2) def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)") if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value") def answer(lowerCAmelCase_) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started...") lowerCamelCase_ : Optional[int] = lower lowerCamelCase_ : Tuple = higher lowerCamelCase_ : Union[str, Any] = [] while True: lowerCamelCase_ : Optional[int] = get_avg(lowerCAmelCase_ , lowerCAmelCase_) last_numbers.append(lowerCAmelCase_) if answer(lowerCAmelCase_) == "low": lowerCamelCase_ : Any = number elif answer(lowerCAmelCase_) == "high": lowerCamelCase_ : Optional[int] = number else: break print(F"""guess the number : {last_numbers[-1]}""") print(F"""details : {last_numbers!s}""") def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Optional[int] = int(input("Enter lower value : ").strip()) lowerCamelCase_ : List[str] = int(input("Enter high value : ").strip()) lowerCamelCase_ : List[str] = int(input("Enter value to guess : ").strip()) guess_the_number(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) if __name__ == "__main__": main()
73
1
import os from distutils.util import strtobool def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' for e in env_keys: lowerCamelCase_ : Any = int(os.environ.get(lowerCAmelCase_ , -1)) if val >= 0: return val return default def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_=False): '''simple docstring''' lowerCamelCase_ : List[str] = os.environ.get(lowerCAmelCase_ , str(lowerCAmelCase_)) return strtobool(lowerCAmelCase_) == 1 # As its name indicates `strtobool` actually returns an int... def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_="no"): '''simple docstring''' lowerCamelCase_ : Optional[Any] = os.environ.get(lowerCAmelCase_ , str(lowerCAmelCase_)) return value
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[str] = '''cvt''' def __init__( self , a_=3 , a_=[7, 3, 3] , a_=[4, 2, 2] , a_=[2, 1, 1] , a_=[64, 192, 384] , a_=[1, 3, 6] , a_=[1, 2, 10] , a_=[4.0, 4.0, 4.0] , a_=[0.0, 0.0, 0.0] , a_=[0.0, 0.0, 0.0] , a_=[0.0, 0.0, 0.1] , a_=[True, True, True] , a_=[False, False, True] , a_=["dw_bn", "dw_bn", "dw_bn"] , a_=[3, 3, 3] , a_=[1, 1, 1] , a_=[2, 2, 2] , a_=[1, 1, 1] , a_=[1, 1, 1] , a_=0.02 , a_=1E-12 , **a_ , ): super().__init__(**a_ ) lowerCamelCase_ : Optional[Any] = num_channels lowerCamelCase_ : str = patch_sizes lowerCamelCase_ : List[Any] = patch_stride lowerCamelCase_ : str = patch_padding lowerCamelCase_ : str = embed_dim lowerCamelCase_ : Union[str, Any] = num_heads lowerCamelCase_ : Optional[Any] = depth lowerCamelCase_ : int = mlp_ratio lowerCamelCase_ : Union[str, Any] = attention_drop_rate lowerCamelCase_ : Optional[Any] = drop_rate lowerCamelCase_ : Optional[int] = drop_path_rate lowerCamelCase_ : Union[str, Any] = qkv_bias lowerCamelCase_ : int = cls_token lowerCamelCase_ : int = qkv_projection_method lowerCamelCase_ : int = kernel_qkv lowerCamelCase_ : Optional[Any] = padding_kv lowerCamelCase_ : Optional[int] = stride_kv lowerCamelCase_ : Optional[int] = padding_q lowerCamelCase_ : List[Any] = stride_q lowerCamelCase_ : Any = initializer_range lowerCamelCase_ : int = layer_norm_eps
73
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __magic_name__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
73
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __magic_name__ = {'''processing_layoutxlm''': ['''LayoutXLMProcessor''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''LayoutXLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''LayoutXLMTokenizerFast'''] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
73
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 lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. lowerCamelCase_ : List[Any] = [[1, 2, 4], [1, 2, 3, 4]] lowerCamelCase_ : Dict = DisjunctiveConstraint(a_ ) self.assertTrue(isinstance(dc.token_ids , a_ ) ) with self.assertRaises(a_ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(a_ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def _UpperCamelCase ( self ): # 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). lowerCamelCase_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(a_ ): DisjunctiveConstraint(a_ ) # fails here def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] lowerCamelCase_ : Optional[Any] = DisjunctiveConstraint(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Dict = dc.update(1 ) lowerCamelCase_ : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(a_ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[str] = dc.update(2 ) lowerCamelCase_ : List[str] = stepped is True and completed is False and reset is False self.assertTrue(a_ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = dc.update(3 ) lowerCamelCase_ : Union[str, Any] = stepped is True and completed is True and reset is False self.assertTrue(a_ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] lowerCamelCase_ : Union[str, Any] = DisjunctiveConstraint(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Union[str, Any] = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Dict = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
73
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''EncodecFeatureExtractor''' __UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) lowerCamelCase_ : Optional[Any] = self.feature_extractor lowerCamelCase_ : Optional[int] = False def _UpperCamelCase ( self , a_=None , a_=None , a_=True ): return self.tokenizer.get_decoder_prompt_ids(task=a_ , language=a_ , no_timestamps=a_ ) def __call__( self , *a_ , **a_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a_ , **a_ ) lowerCamelCase_ : str = kwargs.pop("audio" , a_ ) lowerCamelCase_ : List[str] = kwargs.pop("sampling_rate" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("text" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : int = args[0] lowerCamelCase_ : str = 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 text is not None: lowerCamelCase_ : Dict = self.tokenizer(a_ , **a_ ) if audio is not None: lowerCamelCase_ : Optional[Any] = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ ) if audio is None: return inputs elif text is None: return audio_inputs else: lowerCamelCase_ : Dict = audio_inputs["input_values"] if "padding_mask" in audio_inputs: lowerCamelCase_ : int = audio_inputs["padding_mask"] return inputs def _UpperCamelCase ( self , *a_ , **a_ ): lowerCamelCase_ : Dict = kwargs.pop("audio" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("padding_mask" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : Optional[int] = args[0] lowerCamelCase_ : Optional[Any] = args[1:] if audio_values is not None: return self._decode_audio(a_ , padding_mask=a_ ) else: return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Any = to_numpy(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[str] = audio_values.shape if padding_mask is None: return list(a_ ) lowerCamelCase_ : Tuple = to_numpy(a_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) lowerCamelCase_ : List[str] = seq_len - padding_mask.shape[-1] lowerCamelCase_ : int = 1 - self.feature_extractor.padding_value lowerCamelCase_ : List[Any] = np.pad(a_ , ((0, 0), (0, difference)) , "constant" , constant_values=a_ ) lowerCamelCase_ : str = audio_values.tolist() for i in range(a_ ): lowerCamelCase_ : Dict = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] lowerCamelCase_ : Dict = sliced_audio.reshape(a_ , -1 ) return audio_values
73
1
import re def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_)] def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Union[str, Any] = split_input(str_) return "".join( ["".join([char.capitalize() for char in sub_str]) for sub_str in string_split]) def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' try: lowerCamelCase_ : List[Any] = split_input(lowerCAmelCase_) if upper: lowerCamelCase_ : Tuple = "".join( [ separator.join([char.upper() for char in sub_str]) for sub_str in string_split ]) else: lowerCamelCase_ : Tuple = "".join( [ separator.join([char.lower() for char in sub_str]) for sub_str in string_split ]) return res_str except IndexError: return "not valid string" def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' return to_simple_case(lowerCAmelCase_) def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: lowerCamelCase_ : int = to_simple_case(lowerCAmelCase_) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' return to_complex_case(lowerCAmelCase_ , lowerCAmelCase_ , "_") def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' return to_complex_case(lowerCAmelCase_ , lowerCAmelCase_ , "-") if __name__ == "__main__": __import__('''doctest''').testmod()
73
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if digit_amount > 0: return round(number - int(lowerCAmelCase_) , lowerCAmelCase_) return number - int(lowerCAmelCase_) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.3_45, 1)) print(decimal_isolate(35.3_45, 2)) print(decimal_isolate(35.3_45, 3)) print(decimal_isolate(-14.7_89, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.1_23, 1)) print(decimal_isolate(-14.1_23, 2)) print(decimal_isolate(-14.1_23, 3))
73
1
import math import flax.linen as nn import jax.numpy as jnp def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 1 , lowerCAmelCase_ = 1 , lowerCAmelCase_ = 1.0E4 , lowerCAmelCase_ = False , lowerCAmelCase_ = 1.0 , ): '''simple docstring''' assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"""Embedding dimension {embedding_dim} should be even""" lowerCamelCase_ : str = float(embedding_dim // 2) lowerCamelCase_ : Dict = math.log(max_timescale / min_timescale) / (num_timescales - freq_shift) lowerCamelCase_ : int = min_timescale * jnp.exp(jnp.arange(lowerCAmelCase_ , dtype=jnp.floataa) * -log_timescale_increment) lowerCamelCase_ : Optional[int] = jnp.expand_dims(lowerCAmelCase_ , 1) * jnp.expand_dims(lowerCAmelCase_ , 0) # scale embeddings lowerCamelCase_ : Tuple = scale * emb if flip_sin_to_cos: lowerCamelCase_ : Union[str, Any] = jnp.concatenate([jnp.cos(lowerCAmelCase_), jnp.sin(lowerCAmelCase_)] , axis=1) else: lowerCamelCase_ : str = jnp.concatenate([jnp.sin(lowerCAmelCase_), jnp.cos(lowerCAmelCase_)] , axis=1) lowerCamelCase_ : Optional[int] = jnp.reshape(lowerCAmelCase_ , [jnp.shape(lowerCAmelCase_)[0], embedding_dim]) return signal class lowerCAmelCase__ ( nn.Module ): """simple docstring""" __UpperCAmelCase : int = 32 __UpperCAmelCase : jnp.dtype = jnp.floataa @nn.compact def __call__( self , a_ ): lowerCamelCase_ : Union[str, Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_1" )(a_ ) lowerCamelCase_ : Dict = nn.silu(a_ ) lowerCamelCase_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_2" )(a_ ) return temb class lowerCAmelCase__ ( nn.Module ): """simple docstring""" __UpperCAmelCase : int = 32 __UpperCAmelCase : bool = False __UpperCAmelCase : float = 1 @nn.compact def __call__( self , a_ ): return get_sinusoidal_embeddings( a_ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
73
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , a_ , a_=7 , a_=3 , a_=18 , a_=30 , a_=400 , a_=True , a_=None , a_=True , ): lowerCamelCase_ : int = size if size is not None else {"height": 18, "width": 18} lowerCamelCase_ : str = parent lowerCamelCase_ : str = batch_size lowerCamelCase_ : Tuple = num_channels lowerCamelCase_ : Optional[int] = image_size lowerCamelCase_ : List[str] = min_resolution lowerCamelCase_ : Tuple = max_resolution lowerCamelCase_ : Tuple = do_resize lowerCamelCase_ : Dict = size lowerCamelCase_ : List[str] = apply_ocr def _UpperCamelCase ( self ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowerCAmelCase__ ( __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = LayoutLMvaImageProcessingTester(self ) @property def _UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , "do_resize" ) ) self.assertTrue(hasattr(a_ , "size" ) ) self.assertTrue(hasattr(a_ , "apply_ocr" ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) lowerCamelCase_ : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def _UpperCamelCase ( self ): pass def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input lowerCamelCase_ : List[str] = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , a_ ) self.assertIsInstance(encoding.boxes , a_ ) # Test batched lowerCamelCase_ : int = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) # Test not batched input lowerCamelCase_ : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCamelCase_ : Any = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input lowerCamelCase_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCamelCase_ : Union[str, Any] = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # with apply_OCR = True lowerCamelCase_ : Any = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCamelCase_ : Optional[Any] = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) lowerCamelCase_ : Optional[Any] = Image.open(ds[0]["file"] ).convert("RGB" ) lowerCamelCase_ : List[Any] = image_processing(a_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCamelCase_ : List[Any] = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 lowerCamelCase_ : Tuple = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , a_ ) self.assertListEqual(encoding.boxes , a_ ) # with apply_OCR = False lowerCamelCase_ : List[str] = LayoutLMvaImageProcessor(apply_ocr=a_ ) lowerCamelCase_ : List[str] = image_processing(a_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
73
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __magic_name__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class lowerCAmelCase__ ( datasets.BuilderConfig ): """simple docstring""" __UpperCAmelCase : Optional[datasets.Features] = None def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' import pyspark def generate_fn(): lowerCamelCase_ : Dict = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id")) for partition_id in partition_order: lowerCamelCase_ : Dict = df_with_partition_id.select("*").where(F"""part_id = {partition_id}""").drop("part_id") lowerCamelCase_ : Dict = partition_df.collect() lowerCamelCase_ : Dict = 0 for row in rows: yield F"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class lowerCAmelCase__ ( _BaseExamplesIterable ): """simple docstring""" def __init__( self , a_ , a_=None , ): lowerCamelCase_ : Dict = df lowerCamelCase_ : Optional[Any] = partition_order or range(self.df.rdd.getNumPartitions() ) lowerCamelCase_ : int = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ): yield from self.generate_examples_fn() def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Optional[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a_ ) return SparkExamplesIterable(self.df , partition_order=a_ ) def _UpperCamelCase ( self , a_ , a_ ): lowerCamelCase_ : Dict = self.split_shard_indices_by_worker(a_ , a_ ) return SparkExamplesIterable(self.df , partition_order=a_ ) @property def _UpperCamelCase ( self ): return len(self.partition_order ) class lowerCAmelCase__ ( datasets.DatasetBuilder ): """simple docstring""" __UpperCAmelCase : Any = SparkConfig def __init__( self , a_ , a_ = None , a_ = None , **a_ , ): import pyspark lowerCamelCase_ : str = pyspark.sql.SparkSession.builder.getOrCreate() lowerCamelCase_ : Optional[Any] = df lowerCamelCase_ : List[Any] = working_dir super().__init__( cache_dir=a_ , config_name=str(self.df.semanticHash() ) , **a_ , ) def _UpperCamelCase ( self ): # Returns the path of the created file. def create_cache_and_write_probe(a_ ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=a_ ) lowerCamelCase_ : Optional[Any] = os.path.join(self._cache_dir , "fs_test" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(a_ , "a" ) return [probe_file] if self._spark.conf.get("spark.master" , "" ).startswith("local" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowerCamelCase_ : List[str] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(a_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir" ) def _UpperCamelCase ( self ): return datasets.DatasetInfo(features=self.config.features ) def _UpperCamelCase ( self , a_ ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def _UpperCamelCase ( self , a_ ): import pyspark def get_arrow_batch_size(a_ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) lowerCamelCase_ : str = self.df.count() lowerCamelCase_ : List[Any] = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowerCamelCase_ : Any = ( self.df.limit(a_ ) .repartition(1 ) .mapInArrow(a_ , "batch_bytes: long" ) .agg(pyspark.sql.functions.sum("batch_bytes" ).alias("sample_bytes" ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowerCamelCase_ : int = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowerCamelCase_ : Union[str, Any] = min(a_ , int(approx_total_size / max_shard_size ) ) lowerCamelCase_ : int = self.df.repartition(a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , ): import pyspark lowerCamelCase_ : str = ParquetWriter if file_format == "parquet" else ArrowWriter lowerCamelCase_ : int = os.path.join(self._working_dir , os.path.basename(a_ ) ) if self._working_dir else fpath lowerCamelCase_ : Optional[Any] = file_format == "parquet" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowerCamelCase_ : int = self.config.features lowerCamelCase_ : Any = self._writer_batch_size lowerCamelCase_ : Tuple = self._fs.storage_options def write_arrow(a_ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowerCamelCase_ : List[Any] = pyspark.TaskContext().taskAttemptId() lowerCamelCase_ : Optional[int] = next(a_ , a_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["task_id", "num_examples", "num_bytes"] , ) lowerCamelCase_ : List[Any] = 0 lowerCamelCase_ : Optional[int] = writer_class( features=a_ , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=a_ , storage_options=a_ , embed_local_files=a_ , ) lowerCamelCase_ : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(a_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowerCamelCase_ ,lowerCamelCase_ : List[str] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) shard_id += 1 lowerCamelCase_ : List[str] = writer_class( features=writer._features , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=a_ , storage_options=a_ , embed_local_files=a_ , ) lowerCamelCase_ : Optional[int] = pa.Table.from_batches([batch] ) writer.write_table(a_ ) if writer._num_bytes > 0: lowerCamelCase_ ,lowerCamelCase_ : Dict = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(a_ ) ): lowerCamelCase_ : str = os.path.join(os.path.dirname(a_ ) , os.path.basename(a_ ) ) shutil.move(a_ , a_ ) lowerCamelCase_ : int = ( self.df.mapInArrow(a_ , "task_id: long, num_examples: long, num_bytes: long" ) .groupBy("task_id" ) .agg( pyspark.sql.functions.sum("num_examples" ).alias("total_num_examples" ) , pyspark.sql.functions.sum("num_bytes" ).alias("total_num_bytes" ) , pyspark.sql.functions.count("num_bytes" ).alias("num_shards" ) , pyspark.sql.functions.collect_list("num_examples" ).alias("shard_lengths" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def _UpperCamelCase ( self , a_ , a_ = "arrow" , a_ = None , a_ = None , **a_ , ): self._validate_cache_dir() lowerCamelCase_ : Union[str, Any] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a_ ) lowerCamelCase_ : Dict = not is_remote_filesystem(self._fs ) lowerCamelCase_ : List[str] = os.path.join if is_local else posixpath.join lowerCamelCase_ : Any = "-TTTTT-SSSSS-of-NNNNN" lowerCamelCase_ : List[Any] = F"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" lowerCamelCase_ : int = path_join(self._output_dir , a_ ) lowerCamelCase_ : int = 0 lowerCamelCase_ : Optional[Any] = 0 lowerCamelCase_ : int = 0 lowerCamelCase_ : Dict = [] lowerCamelCase_ : Any = [] for task_id, content in self._prepare_split_single(a_ , a_ , a_ ): ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) : Tuple = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(a_ ) lowerCamelCase_ : Dict = total_num_examples lowerCamelCase_ : Any = total_num_bytes # should rename everything at the end logger.debug(F"""Renaming {total_shards} shards.""" ) if total_shards > 1: lowerCamelCase_ : List[Any] = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowerCamelCase_ : Any = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a_ , a_ , a_ , ): rename( a_ , fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace("TTTTT-SSSSS" , F"""{global_shard_id:05d}""" ).replace("NNNNN" , F"""{total_shards:05d}""" ) , ) lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : Dict = 0 for i in range(len(a_ ) ): lowerCamelCase_ ,lowerCamelCase_ : Tuple = task_id_and_num_shards[i] for shard_id in range(a_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(a_ , len(a_ ) ).map(lambda a_ : _rename_shard(*a_ ) ).collect() else: # don't use any pattern lowerCamelCase_ : int = 0 lowerCamelCase_ : Optional[int] = task_id_and_num_shards[0][0] self._rename( fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace(a_ , "" ) , ) def _UpperCamelCase ( self , a_ , ): return SparkExamplesIterable(self.df )
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''studio-ousia/luke-base''': '''https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json''', '''studio-ousia/luke-large''': '''https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json''', } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = '''luke''' def __init__( self , a_=5_0267 , a_=50_0000 , a_=768 , a_=256 , a_=12 , a_=12 , a_=3072 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=2 , a_=0.02 , a_=1E-12 , a_=True , a_=None , a_=1 , a_=0 , a_=2 , **a_ , ): super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) lowerCamelCase_ : Tuple = vocab_size lowerCamelCase_ : Optional[int] = entity_vocab_size lowerCamelCase_ : Any = hidden_size lowerCamelCase_ : Dict = entity_emb_size lowerCamelCase_ : List[Any] = num_hidden_layers lowerCamelCase_ : int = num_attention_heads lowerCamelCase_ : Union[str, Any] = hidden_act lowerCamelCase_ : Tuple = intermediate_size lowerCamelCase_ : Optional[Any] = hidden_dropout_prob lowerCamelCase_ : Any = attention_probs_dropout_prob lowerCamelCase_ : Optional[Any] = max_position_embeddings lowerCamelCase_ : str = type_vocab_size lowerCamelCase_ : int = initializer_range lowerCamelCase_ : List[Any] = layer_norm_eps lowerCamelCase_ : Optional[int] = use_entity_aware_attention lowerCamelCase_ : str = classifier_dropout
73
1
import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''vocab_file''': '''vocab.txt''', '''merges_file''': '''bpe.codes''', } __magic_name__ = { '''vocab_file''': { '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt''', '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt''', }, '''merges_file''': { '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes''', '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes''', }, } __magic_name__ = { '''vinai/phobert-base''': 2_5_6, '''vinai/phobert-large''': 2_5_6, } def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Tuple = set() lowerCamelCase_ : Tuple = word[0] for char in word[1:]: pairs.add((prev_char, char)) lowerCamelCase_ : Optional[Any] = char lowerCamelCase_ : Optional[Any] = set(lowerCAmelCase_) return pairs class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , a_ , a_ , a_="<s>" , a_="</s>" , a_="</s>" , a_="<s>" , a_="<unk>" , a_="<pad>" , a_="<mask>" , **a_ , ): super().__init__( bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , cls_token=a_ , pad_token=a_ , mask_token=a_ , **a_ , ) lowerCamelCase_ : Optional[int] = vocab_file lowerCamelCase_ : Any = merges_file lowerCamelCase_ : Any = {} lowerCamelCase_ : Any = 0 lowerCamelCase_ : Union[str, Any] = 1 lowerCamelCase_ : Tuple = 2 lowerCamelCase_ : List[str] = 3 self.add_from_file(a_ ) lowerCamelCase_ : Optional[int] = {v: k for k, v in self.encoder.items()} with open(a_ , encoding="utf-8" ) as merges_handle: lowerCamelCase_ : Optional[Any] = merges_handle.read().split("\n" )[:-1] lowerCamelCase_ : Tuple = [tuple(merge.split()[:-1] ) for merge in merges] lowerCamelCase_ : Tuple = dict(zip(a_ , range(len(a_ ) ) ) ) lowerCamelCase_ : List[str] = {} def _UpperCamelCase ( self , a_ , a_ = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase_ : Any = [self.cls_token_id] lowerCamelCase_ : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _UpperCamelCase ( self , a_ , a_ = None , a_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ ) if token_ids_a is None: return [1] + ([0] * len(a_ )) + [1] return [1] + ([0] * len(a_ )) + [1, 1] + ([0] * len(a_ )) + [1] def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[int] = [self.sep_token_id] lowerCamelCase_ : List[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 + sep + token_ids_a + sep ) * [0] @property def _UpperCamelCase ( self ): return len(self.encoder ) def _UpperCamelCase ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def _UpperCamelCase ( self , a_ ): if token in self.cache: return self.cache[token] lowerCamelCase_ : Tuple = tuple(a_ ) lowerCamelCase_ : int = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) lowerCamelCase_ : List[Any] = get_pairs(a_ ) if not pairs: return token while True: lowerCamelCase_ : Tuple = min(a_ , key=lambda a_ : self.bpe_ranks.get(a_ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break lowerCamelCase_ ,lowerCamelCase_ : Any = bigram lowerCamelCase_ : int = [] lowerCamelCase_ : Optional[Any] = 0 while i < len(a_ ): try: lowerCamelCase_ : Tuple = word.index(a_ , a_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCamelCase_ : Dict = j if word[i] == first and i < len(a_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCamelCase_ : Optional[Any] = tuple(a_ ) lowerCamelCase_ : List[Any] = new_word if len(a_ ) == 1: break else: lowerCamelCase_ : Union[str, Any] = get_pairs(a_ ) lowerCamelCase_ : Tuple = "@@ ".join(a_ ) lowerCamelCase_ : Union[str, Any] = word[:-4] lowerCamelCase_ : Any = word return word def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : str = [] lowerCamelCase_ : Dict = re.findall(R"\S+\n?" , a_ ) for token in words: split_tokens.extend(list(self.bpe(a_ ).split(" " ) ) ) return split_tokens def _UpperCamelCase ( self , a_ ): return self.encoder.get(a_ , self.encoder.get(self.unk_token ) ) def _UpperCamelCase ( self , a_ ): return self.decoder.get(a_ , self.unk_token ) def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Any = " ".join(a_ ).replace("@@ " , "" ).strip() return out_string def _UpperCamelCase ( self , a_ , a_ = None ): if not os.path.isdir(a_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase_ : Optional[int] = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) lowerCamelCase_ : Optional[Any] = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ): copyfile(self.vocab_file , a_ ) if os.path.abspath(self.merges_file ) != os.path.abspath(a_ ): copyfile(self.merges_file , a_ ) return out_vocab_file, out_merge_file def _UpperCamelCase ( self , a_ ): if isinstance(a_ , a_ ): try: with open(a_ , "r" , encoding="utf-8" ) as fd: self.add_from_file(a_ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(F"""Incorrect encoding detected in {f}, please rebuild the dataset""" ) return lowerCamelCase_ : Tuple = f.readlines() for lineTmp in lines: lowerCamelCase_ : Dict = lineTmp.strip() lowerCamelCase_ : Optional[Any] = line.rfind(" " ) if idx == -1: raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'" ) lowerCamelCase_ : Any = line[:idx] lowerCamelCase_ : Optional[Any] = len(self.encoder )
73
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __magic_name__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class lowerCAmelCase__ ( datasets.BuilderConfig ): """simple docstring""" __UpperCAmelCase : Optional[datasets.Features] = None def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' import pyspark def generate_fn(): lowerCamelCase_ : Dict = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id")) for partition_id in partition_order: lowerCamelCase_ : Dict = df_with_partition_id.select("*").where(F"""part_id = {partition_id}""").drop("part_id") lowerCamelCase_ : Dict = partition_df.collect() lowerCamelCase_ : Dict = 0 for row in rows: yield F"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class lowerCAmelCase__ ( _BaseExamplesIterable ): """simple docstring""" def __init__( self , a_ , a_=None , ): lowerCamelCase_ : Dict = df lowerCamelCase_ : Optional[Any] = partition_order or range(self.df.rdd.getNumPartitions() ) lowerCamelCase_ : int = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ): yield from self.generate_examples_fn() def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Optional[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a_ ) return SparkExamplesIterable(self.df , partition_order=a_ ) def _UpperCamelCase ( self , a_ , a_ ): lowerCamelCase_ : Dict = self.split_shard_indices_by_worker(a_ , a_ ) return SparkExamplesIterable(self.df , partition_order=a_ ) @property def _UpperCamelCase ( self ): return len(self.partition_order ) class lowerCAmelCase__ ( datasets.DatasetBuilder ): """simple docstring""" __UpperCAmelCase : Any = SparkConfig def __init__( self , a_ , a_ = None , a_ = None , **a_ , ): import pyspark lowerCamelCase_ : str = pyspark.sql.SparkSession.builder.getOrCreate() lowerCamelCase_ : Optional[Any] = df lowerCamelCase_ : List[Any] = working_dir super().__init__( cache_dir=a_ , config_name=str(self.df.semanticHash() ) , **a_ , ) def _UpperCamelCase ( self ): # Returns the path of the created file. def create_cache_and_write_probe(a_ ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=a_ ) lowerCamelCase_ : Optional[Any] = os.path.join(self._cache_dir , "fs_test" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(a_ , "a" ) return [probe_file] if self._spark.conf.get("spark.master" , "" ).startswith("local" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowerCamelCase_ : List[str] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(a_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir" ) def _UpperCamelCase ( self ): return datasets.DatasetInfo(features=self.config.features ) def _UpperCamelCase ( self , a_ ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def _UpperCamelCase ( self , a_ ): import pyspark def get_arrow_batch_size(a_ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) lowerCamelCase_ : str = self.df.count() lowerCamelCase_ : List[Any] = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowerCamelCase_ : Any = ( self.df.limit(a_ ) .repartition(1 ) .mapInArrow(a_ , "batch_bytes: long" ) .agg(pyspark.sql.functions.sum("batch_bytes" ).alias("sample_bytes" ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowerCamelCase_ : int = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowerCamelCase_ : Union[str, Any] = min(a_ , int(approx_total_size / max_shard_size ) ) lowerCamelCase_ : int = self.df.repartition(a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , ): import pyspark lowerCamelCase_ : str = ParquetWriter if file_format == "parquet" else ArrowWriter lowerCamelCase_ : int = os.path.join(self._working_dir , os.path.basename(a_ ) ) if self._working_dir else fpath lowerCamelCase_ : Optional[Any] = file_format == "parquet" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowerCamelCase_ : int = self.config.features lowerCamelCase_ : Any = self._writer_batch_size lowerCamelCase_ : Tuple = self._fs.storage_options def write_arrow(a_ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowerCamelCase_ : List[Any] = pyspark.TaskContext().taskAttemptId() lowerCamelCase_ : Optional[int] = next(a_ , a_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["task_id", "num_examples", "num_bytes"] , ) lowerCamelCase_ : List[Any] = 0 lowerCamelCase_ : Optional[int] = writer_class( features=a_ , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=a_ , storage_options=a_ , embed_local_files=a_ , ) lowerCamelCase_ : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(a_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowerCamelCase_ ,lowerCamelCase_ : List[str] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) shard_id += 1 lowerCamelCase_ : List[str] = writer_class( features=writer._features , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=a_ , storage_options=a_ , embed_local_files=a_ , ) lowerCamelCase_ : Optional[int] = pa.Table.from_batches([batch] ) writer.write_table(a_ ) if writer._num_bytes > 0: lowerCamelCase_ ,lowerCamelCase_ : Dict = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(a_ ) ): lowerCamelCase_ : str = os.path.join(os.path.dirname(a_ ) , os.path.basename(a_ ) ) shutil.move(a_ , a_ ) lowerCamelCase_ : int = ( self.df.mapInArrow(a_ , "task_id: long, num_examples: long, num_bytes: long" ) .groupBy("task_id" ) .agg( pyspark.sql.functions.sum("num_examples" ).alias("total_num_examples" ) , pyspark.sql.functions.sum("num_bytes" ).alias("total_num_bytes" ) , pyspark.sql.functions.count("num_bytes" ).alias("num_shards" ) , pyspark.sql.functions.collect_list("num_examples" ).alias("shard_lengths" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def _UpperCamelCase ( self , a_ , a_ = "arrow" , a_ = None , a_ = None , **a_ , ): self._validate_cache_dir() lowerCamelCase_ : Union[str, Any] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a_ ) lowerCamelCase_ : Dict = not is_remote_filesystem(self._fs ) lowerCamelCase_ : List[str] = os.path.join if is_local else posixpath.join lowerCamelCase_ : Any = "-TTTTT-SSSSS-of-NNNNN" lowerCamelCase_ : List[Any] = F"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" lowerCamelCase_ : int = path_join(self._output_dir , a_ ) lowerCamelCase_ : int = 0 lowerCamelCase_ : Optional[Any] = 0 lowerCamelCase_ : int = 0 lowerCamelCase_ : Dict = [] lowerCamelCase_ : Any = [] for task_id, content in self._prepare_split_single(a_ , a_ , a_ ): ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) : Tuple = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(a_ ) lowerCamelCase_ : Dict = total_num_examples lowerCamelCase_ : Any = total_num_bytes # should rename everything at the end logger.debug(F"""Renaming {total_shards} shards.""" ) if total_shards > 1: lowerCamelCase_ : List[Any] = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowerCamelCase_ : Any = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a_ , a_ , a_ , ): rename( a_ , fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace("TTTTT-SSSSS" , F"""{global_shard_id:05d}""" ).replace("NNNNN" , F"""{total_shards:05d}""" ) , ) lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : Dict = 0 for i in range(len(a_ ) ): lowerCamelCase_ ,lowerCamelCase_ : Tuple = task_id_and_num_shards[i] for shard_id in range(a_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(a_ , len(a_ ) ).map(lambda a_ : _rename_shard(*a_ ) ).collect() else: # don't use any pattern lowerCamelCase_ : int = 0 lowerCamelCase_ : Optional[int] = task_id_and_num_shards[0][0] self._rename( fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace(a_ , "" ) , ) def _UpperCamelCase ( self , a_ , ): return SparkExamplesIterable(self.df )
73
1
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=1E-12): '''simple docstring''' lowerCamelCase_ : List[str] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(lowerCAmelCase_ , axis=1) , a_min=lowerCAmelCase_)).T lowerCamelCase_ : List[str] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(lowerCAmelCase_ , axis=1) , a_min=lowerCAmelCase_)).T return jnp.matmul(lowerCAmelCase_ , norm_emb_a.T) class lowerCAmelCase__ ( nn.Module ): """simple docstring""" __UpperCAmelCase : CLIPConfig __UpperCAmelCase : jnp.dtype = jnp.floataa def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = FlaxCLIPVisionModule(self.config.vision_config ) lowerCamelCase_ : Optional[int] = nn.Dense(self.config.projection_dim , use_bias=a_ , dtype=self.dtype ) lowerCamelCase_ : Optional[int] = self.param("concept_embeds" , jax.nn.initializers.ones , (17, self.config.projection_dim) ) lowerCamelCase_ : List[str] = self.param( "special_care_embeds" , jax.nn.initializers.ones , (3, self.config.projection_dim) ) lowerCamelCase_ : str = self.param("concept_embeds_weights" , jax.nn.initializers.ones , (17,) ) lowerCamelCase_ : str = self.param("special_care_embeds_weights" , jax.nn.initializers.ones , (3,) ) def __call__( self , a_ ): lowerCamelCase_ : List[str] = self.vision_model(a_ )[1] lowerCamelCase_ : Optional[int] = self.visual_projection(a_ ) lowerCamelCase_ : Any = jax_cosine_distance(a_ , self.special_care_embeds ) lowerCamelCase_ : Union[str, Any] = jax_cosine_distance(a_ , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs lowerCamelCase_ : Dict = 0.0 lowerCamelCase_ : List[str] = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment lowerCamelCase_ : str = jnp.round(a_ , 3 ) lowerCamelCase_ : Any = jnp.any(special_scores > 0 , axis=1 , keepdims=a_ ) # Use a lower threshold if an image has any special care concept lowerCamelCase_ : List[Any] = is_special_care * 0.01 lowerCamelCase_ : Any = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment lowerCamelCase_ : Union[str, Any] = jnp.round(a_ , 3 ) lowerCamelCase_ : Dict = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : int = CLIPConfig __UpperCAmelCase : Union[str, Any] = '''clip_input''' __UpperCAmelCase : Optional[Any] = FlaxStableDiffusionSafetyCheckerModule def __init__( self , a_ , a_ = None , a_ = 0 , a_ = jnp.floataa , a_ = True , **a_ , ): if input_shape is None: lowerCamelCase_ : Any = (1, 224, 224, 3) lowerCamelCase_ : List[Any] = self.module_class(config=a_ , dtype=a_ , **a_ ) super().__init__(a_ , a_ , input_shape=a_ , seed=a_ , dtype=a_ , _do_init=_do_init ) def _UpperCamelCase ( self , a_ , a_ , a_ = None ): # init input tensor lowerCamelCase_ : Optional[int] = jax.random.normal(a_ , a_ ) lowerCamelCase_ ,lowerCamelCase_ : str = jax.random.split(a_ ) lowerCamelCase_ : Optional[int] = {"params": params_rng, "dropout": dropout_rng} lowerCamelCase_ : int = self.module.init(a_ , a_ )["params"] return random_params def __call__( self , a_ , a_ = None , ): lowerCamelCase_ : Tuple = jnp.transpose(a_ , (0, 2, 3, 1) ) return self.module.apply( {"params": params or self.params} , jnp.array(a_ , dtype=jnp.floataa ) , rngs={} , )
73
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue lowerCamelCase_ : List[str] = cst_fwd.get(lowerCAmelCase_ , np.inf) lowerCamelCase_ : Dict = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt)) lowerCamelCase_ : Optional[int] = new_cost_f lowerCamelCase_ : List[str] = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: lowerCamelCase_ : Tuple = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Optional[Any] = -1 lowerCamelCase_ : Tuple = set() lowerCamelCase_ : Dict = set() lowerCamelCase_ : int = {source: 0} lowerCamelCase_ : str = {destination: 0} lowerCamelCase_ : Tuple = {source: None} lowerCamelCase_ : Dict = {destination: None} lowerCamelCase_ : PriorityQueue[Any] = PriorityQueue() lowerCamelCase_ : PriorityQueue[Any] = PriorityQueue() lowerCamelCase_ : List[str] = np.inf queue_forward.put((0, source)) queue_backward.put((0, destination)) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): lowerCamelCase_ ,lowerCamelCase_ : List[Any] = queue_forward.get() visited_forward.add(lowerCAmelCase_) lowerCamelCase_ ,lowerCamelCase_ : str = queue_backward.get() visited_backward.add(lowerCAmelCase_) lowerCamelCase_ : Any = pass_and_relaxation( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) lowerCamelCase_ : Dict = pass_and_relaxation( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: lowerCamelCase_ : Union[str, Any] = shortest_distance return shortest_path_distance __magic_name__ = { '''B''': [['''C''', 1]], '''C''': [['''D''', 1]], '''D''': [['''F''', 1]], '''E''': [['''B''', 1], ['''G''', 2]], '''F''': [], '''G''': [['''F''', 1]], } __magic_name__ = { '''B''': [['''E''', 1]], '''C''': [['''B''', 1]], '''D''': [['''C''', 1]], '''F''': [['''D''', 1], ['''G''', 1]], '''E''': [[None, np.inf]], '''G''': [['''E''', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
73
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Union[List[PIL.Image.Image], np.ndarray] __UpperCAmelCase : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.26.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('''>=''', '''0.0.12''') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : np.ndarray __UpperCAmelCase : List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''ctrl''' __UpperCAmelCase : Dict = ['''past_key_values'''] __UpperCAmelCase : int = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a_=24_6534 , a_=256 , a_=1280 , a_=8192 , a_=48 , a_=16 , a_=0.1 , a_=0.1 , a_=1E-6 , a_=0.02 , a_=True , **a_ , ): lowerCamelCase_ : Dict = vocab_size lowerCamelCase_ : Any = n_positions lowerCamelCase_ : Optional[int] = n_embd lowerCamelCase_ : List[Any] = n_layer lowerCamelCase_ : Union[str, Any] = n_head lowerCamelCase_ : str = dff lowerCamelCase_ : Tuple = resid_pdrop lowerCamelCase_ : Any = embd_pdrop lowerCamelCase_ : Dict = layer_norm_epsilon lowerCamelCase_ : Tuple = initializer_range lowerCamelCase_ : Any = use_cache super().__init__(**a_ )
73
1
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''EncodecFeatureExtractor''' __UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) lowerCamelCase_ : Optional[Any] = self.feature_extractor lowerCamelCase_ : Optional[int] = False def _UpperCamelCase ( self , a_=None , a_=None , a_=True ): return self.tokenizer.get_decoder_prompt_ids(task=a_ , language=a_ , no_timestamps=a_ ) def __call__( self , *a_ , **a_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a_ , **a_ ) lowerCamelCase_ : str = kwargs.pop("audio" , a_ ) lowerCamelCase_ : List[str] = kwargs.pop("sampling_rate" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("text" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : int = args[0] lowerCamelCase_ : str = 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 text is not None: lowerCamelCase_ : Dict = self.tokenizer(a_ , **a_ ) if audio is not None: lowerCamelCase_ : Optional[Any] = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ ) if audio is None: return inputs elif text is None: return audio_inputs else: lowerCamelCase_ : Dict = audio_inputs["input_values"] if "padding_mask" in audio_inputs: lowerCamelCase_ : int = audio_inputs["padding_mask"] return inputs def _UpperCamelCase ( self , *a_ , **a_ ): lowerCamelCase_ : Dict = kwargs.pop("audio" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("padding_mask" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : Optional[int] = args[0] lowerCamelCase_ : Optional[Any] = args[1:] if audio_values is not None: return self._decode_audio(a_ , padding_mask=a_ ) else: return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Any = to_numpy(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[str] = audio_values.shape if padding_mask is None: return list(a_ ) lowerCamelCase_ : Tuple = to_numpy(a_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) lowerCamelCase_ : List[str] = seq_len - padding_mask.shape[-1] lowerCamelCase_ : int = 1 - self.feature_extractor.padding_value lowerCamelCase_ : List[Any] = np.pad(a_ , ((0, 0), (0, difference)) , "constant" , constant_values=a_ ) lowerCamelCase_ : str = audio_values.tolist() for i in range(a_ ): lowerCamelCase_ : Dict = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] lowerCamelCase_ : Dict = sliced_audio.reshape(a_ , -1 ) return audio_values
73
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __magic_name__ = logging.getLogger(__name__) __magic_name__ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __magic_name__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) }, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(__lowerCamelCase )}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) }, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''}, ) __UpperCAmelCase : str = field( default='''main''', metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) }, ) def _UpperCamelCase ( self ): if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can't be used in combination with --config_name or --model_name_or_path" ) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field(default=__lowerCamelCase, metadata={'''help''': '''The input training data file (a text file).'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) __UpperCAmelCase : Optional[int] = field( default=5, metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' }, ) __UpperCAmelCase : Optional[int] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) }, ) __UpperCAmelCase : Optional[int] = field( default=__lowerCamelCase, metadata={'''help''': '''The number of processes to use for the preprocessing.'''}, ) __UpperCAmelCase : float = field( default=0.15, metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) }, ) def _UpperCamelCase ( self ): if self.train_file is not None: lowerCamelCase_ : str = self.train_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: lowerCamelCase_ : Union[str, Any] = self.validation_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' with open(lowerCAmelCase_ , "r" , encoding="utf-8") as f: lowerCamelCase_ : Tuple = [json.loads(lowerCAmelCase_) for line in f.read().splitlines() if (len(lowerCAmelCase_) > 0 and not line.isspace())] assert len(lowerCAmelCase_) == len(lowerCAmelCase_) lowerCamelCase_ : Any = {c: dataset[c] for c in dataset.column_names} lowerCamelCase_ : List[Any] = refs return Dataset.from_dict(lowerCAmelCase_) def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowerCamelCase_ : List[str] = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: lowerCamelCase_ : Dict = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome.") elif last_checkpoint is not None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch.") # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}""") # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowerCamelCase_ : Optional[int] = load_dataset(data_args.dataset_name , data_args.dataset_config_name) if "validation" not in datasets.keys(): lowerCamelCase_ : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[:{data_args.validation_split_percentage}%]""" , ) lowerCamelCase_ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[{data_args.validation_split_percentage}%:]""" , ) else: lowerCamelCase_ : Dict = {} if data_args.train_file is not None: lowerCamelCase_ : str = data_args.train_file if data_args.validation_file is not None: lowerCamelCase_ : Any = data_args.validation_file lowerCamelCase_ : Any = data_args.train_file.split(".")[-1] if extension == "txt": lowerCamelCase_ : List[str] = "text" lowerCamelCase_ : Dict = load_dataset(lowerCAmelCase_ , data_files=lowerCAmelCase_) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase_ : Optional[Any] = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: lowerCamelCase_ : Optional[Any] = AutoConfig.from_pretrained(model_args.config_name , **lowerCAmelCase_) elif model_args.model_name_or_path: lowerCamelCase_ : str = AutoConfig.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase_) else: lowerCamelCase_ : Optional[int] = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch.") if model_args.config_overrides is not None: logger.info(F"""Overriding config: {model_args.config_overrides}""") config.update_from_string(model_args.config_overrides) logger.info(F"""New config: {config}""") lowerCamelCase_ : List[str] = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: lowerCamelCase_ : str = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **lowerCAmelCase_) elif model_args.model_name_or_path: lowerCamelCase_ : Dict = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase_) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name.") if model_args.model_name_or_path: lowerCamelCase_ : Union[str, Any] = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch") lowerCamelCase_ : Dict = AutoModelForMaskedLM.from_config(lowerCAmelCase_) model.resize_token_embeddings(len(lowerCAmelCase_)) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: lowerCamelCase_ : Optional[Any] = datasets["train"].column_names else: lowerCamelCase_ : Dict = datasets["validation"].column_names lowerCamelCase_ : Union[str, Any] = "text" if "text" in column_names else column_names[0] lowerCamelCase_ : Optional[Any] = "max_length" if data_args.pad_to_max_length else False def tokenize_function(lowerCAmelCase_): # Remove empty lines lowerCamelCase_ : str = [line for line in examples["text"] if len(lowerCAmelCase_) > 0 and not line.isspace()] return tokenizer(examples["text"] , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=data_args.max_seq_length) lowerCamelCase_ : str = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: lowerCamelCase_ : List[Any] = add_chinese_references(tokenized_datasets["train"] , data_args.train_ref_file) if data_args.validation_ref_file is not None: lowerCamelCase_ : List[str] = add_chinese_references( tokenized_datasets["validation"] , data_args.validation_ref_file) # If we have ref files, need to avoid it removed by trainer lowerCamelCase_ : Optional[Any] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: lowerCamelCase_ : Union[str, Any] = False # Data collator # This one will take care of randomly masking the tokens. lowerCamelCase_ : Optional[Any] = DataCollatorForWholeWordMask(tokenizer=lowerCAmelCase_ , mlm_probability=data_args.mlm_probability) # Initialize our Trainer lowerCamelCase_ : int = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=tokenized_datasets["train"] if training_args.do_train else None , eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: if last_checkpoint is not None: lowerCamelCase_ : Dict = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path): lowerCamelCase_ : Dict = model_args.model_name_or_path else: lowerCamelCase_ : int = None lowerCamelCase_ : Optional[Any] = trainer.train(resume_from_checkpoint=lowerCAmelCase_) trainer.save_model() # Saves the tokenizer too for easy upload lowerCamelCase_ : Tuple = os.path.join(training_args.output_dir , "train_results.txt") if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w") as writer: logger.info("***** Train results *****") for key, value in sorted(train_result.metrics.items()): logger.info(F""" {key} = {value}""") writer.write(F"""{key} = {value}\n""") # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json")) # Evaluation lowerCamelCase_ : Dict = {} if training_args.do_eval: logger.info("*** Evaluate ***") lowerCamelCase_ : Tuple = trainer.evaluate() lowerCamelCase_ : str = math.exp(eval_output["eval_loss"]) lowerCamelCase_ : Tuple = perplexity lowerCamelCase_ : int = os.path.join(training_args.output_dir , "eval_results_mlm_wwm.txt") if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w") as writer: logger.info("***** Eval results *****") for key, value in sorted(results.items()): logger.info(F""" {key} = {value}""") writer.write(F"""{key} = {value}\n""") return results def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' main() if __name__ == "__main__": main()
73
1
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __magic_name__ = '''\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } ''' __magic_name__ = '''\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper "Evaluating Large Language Models Trained on Code" (https://arxiv.org/abs/2107.03374). ''' __magic_name__ = ''' Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric("code_eval") >>> test_cases = ["assert add(2,3)==5"] >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {\'pass@1\': 0.5, \'pass@2\': 1.0} ''' __magic_name__ = ''' ################################################################################ !!!WARNING!!! ################################################################################ The "code_eval" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper "Evaluating Large Language Models Trained on Code" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this with: >>> import os >>> os.environ["HF_ALLOW_CODE_EVAL"] = "1" ################################################################################\ ''' __magic_name__ = '''The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): """simple docstring""" def _UpperCamelCase ( self ): return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Value("string" ), } ) , homepage="https://github.com/openai/human-eval" , codebase_urls=["https://github.com/openai/human-eval"] , reference_urls=["https://github.com/openai/human-eval"] , license=_LICENSE , ) def _UpperCamelCase ( self , a_ , a_ , a_=[1, 10, 100] , a_=4 , a_=3.0 ): if os.getenv("HF_ALLOW_CODE_EVAL" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("This metric is currently not supported on Windows." ) with ThreadPoolExecutor(max_workers=a_ ) as executor: lowerCamelCase_ : List[Any] = [] lowerCamelCase_ : List[str] = Counter() lowerCamelCase_ : str = 0 lowerCamelCase_ : int = defaultdict(a_ ) for task_id, (candidates, test_case) in enumerate(zip(a_ , a_ ) ): for candidate in candidates: lowerCamelCase_ : str = candidate + "\n" + test_case lowerCamelCase_ : Tuple = (test_program, timeout, task_id, completion_id[task_id]) lowerCamelCase_ : Optional[Any] = executor.submit(a_ , *a_ ) futures.append(a_ ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(a_ ): lowerCamelCase_ : Dict = future.result() results[result["task_id"]].append((result["completion_id"], result) ) lowerCamelCase_ ,lowerCamelCase_ : Optional[Any] = [], [] for result in results.values(): result.sort() lowerCamelCase_ : Optional[Any] = [r[1]["passed"] for r in result] total.append(len(a_ ) ) correct.append(sum(a_ ) ) lowerCamelCase_ : int = np.array(a_ ) lowerCamelCase_ : List[str] = np.array(a_ ) lowerCamelCase_ : List[str] = k lowerCamelCase_ : List[Any] = {F"""pass@{k}""": estimate_pass_at_k(a_ , a_ , a_ ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' def estimator(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1)) if isinstance(lowerCAmelCase_ , lowerCAmelCase_): lowerCamelCase_ : Optional[int] = itertools.repeat(lowerCAmelCase_ , len(lowerCAmelCase_)) else: assert len(lowerCAmelCase_) == len(lowerCAmelCase_) lowerCamelCase_ : Any = iter(lowerCAmelCase_) return np.array([estimator(int(lowerCAmelCase_) , int(lowerCAmelCase_) , lowerCAmelCase_) for n, c in zip(lowerCAmelCase_ , lowerCAmelCase_)])
73
from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class lowerCAmelCase__ : """simple docstring""" # setable values __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[jnp.ndarray] = None __UpperCAmelCase : Optional[jnp.ndarray] = None # sigma(t_i) @classmethod def _UpperCamelCase ( cls ): return cls() @dataclass class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : KarrasVeSchedulerState class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase ): """simple docstring""" @property def _UpperCamelCase ( self ): return True @register_to_config def __init__( self , a_ = 0.02 , a_ = 100 , a_ = 1.0_07 , a_ = 80 , a_ = 0.05 , a_ = 50 , ): pass def _UpperCamelCase ( self ): return KarrasVeSchedulerState.create() def _UpperCamelCase ( self , a_ , a_ , a_ = () ): lowerCamelCase_ : List[Any] = jnp.arange(0 , a_ )[::-1].copy() lowerCamelCase_ : List[str] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=a_ , schedule=jnp.array(a_ , dtype=jnp.floataa ) , timesteps=a_ , ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , ): if self.config.s_min <= sigma <= self.config.s_max: lowerCamelCase_ : Union[str, Any] = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: lowerCamelCase_ : Optional[int] = 0 # sample eps ~ N(0, S_noise^2 * I) lowerCamelCase_ : Union[str, Any] = random.split(a_ , num=1 ) lowerCamelCase_ : str = self.config.s_noise * random.normal(key=a_ , shape=sample.shape ) lowerCamelCase_ : List[str] = sigma + gamma * sigma lowerCamelCase_ : Tuple = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ = True , ): lowerCamelCase_ : List[str] = sample_hat + sigma_hat * model_output lowerCamelCase_ : Union[str, Any] = (sample_hat - pred_original_sample) / sigma_hat lowerCamelCase_ : Union[str, Any] = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=a_ , derivative=a_ , state=a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ = True , ): lowerCamelCase_ : Optional[Any] = sample_prev + sigma_prev * model_output lowerCamelCase_ : Any = (sample_prev - pred_original_sample) / sigma_prev lowerCamelCase_ : Optional[int] = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=a_ , derivative=a_ , state=a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ ): raise NotImplementedError()
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json''', } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''lxmert''' __UpperCAmelCase : int = {} def __init__( self , a_=3_0522 , a_=768 , a_=12 , a_=9500 , a_=1600 , a_=400 , a_=3072 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=2 , a_=0.02 , a_=1E-12 , a_=9 , a_=5 , a_=5 , a_=2048 , a_=4 , a_=6.67 , a_=True , a_=True , a_=True , a_=True , a_=True , a_=True , a_=True , **a_ , ): lowerCamelCase_ : Tuple = vocab_size lowerCamelCase_ : str = hidden_size lowerCamelCase_ : Optional[Any] = num_attention_heads lowerCamelCase_ : int = hidden_act lowerCamelCase_ : Optional[Any] = intermediate_size lowerCamelCase_ : Optional[Any] = hidden_dropout_prob lowerCamelCase_ : List[Any] = attention_probs_dropout_prob lowerCamelCase_ : List[str] = max_position_embeddings lowerCamelCase_ : Union[str, Any] = type_vocab_size lowerCamelCase_ : Dict = initializer_range lowerCamelCase_ : int = layer_norm_eps lowerCamelCase_ : List[str] = num_qa_labels lowerCamelCase_ : List[str] = num_object_labels lowerCamelCase_ : str = num_attr_labels lowerCamelCase_ : Dict = l_layers lowerCamelCase_ : Dict = x_layers lowerCamelCase_ : Any = r_layers lowerCamelCase_ : str = visual_feat_dim lowerCamelCase_ : str = visual_pos_dim lowerCamelCase_ : List[str] = visual_loss_normalizer lowerCamelCase_ : Tuple = task_matched lowerCamelCase_ : Any = task_mask_lm lowerCamelCase_ : List[str] = task_obj_predict lowerCamelCase_ : List[str] = task_qa lowerCamelCase_ : Any = visual_obj_loss lowerCamelCase_ : Dict = visual_attr_loss lowerCamelCase_ : Any = visual_feat_loss lowerCamelCase_ : Any = {"vision": r_layers, "cross_encoder": x_layers, "language": l_layers} super().__init__(**a_ )
73
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = StableDiffusionDiffEditPipeline __UpperCAmelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} __UpperCAmelCase : Any = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} __UpperCAmelCase : List[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __UpperCAmelCase : List[str] = frozenset([] ) def _UpperCamelCase ( self ): torch.manual_seed(0 ) lowerCamelCase_ : str = 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 , attention_head_dim=(2, 4) , use_linear_projection=a_ , ) lowerCamelCase_ : str = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , ) lowerCamelCase_ : Dict = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_zero=a_ , ) torch.manual_seed(0 ) lowerCamelCase_ : List[Any] = 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 ) lowerCamelCase_ : Union[str, 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 , ) lowerCamelCase_ : Optional[Any] = CLIPTextModel(a_ ) lowerCamelCase_ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCamelCase_ : Optional[Any] = { "unet": unet, "scheduler": scheduler, "inverse_scheduler": inverse_scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : str = floats_tensor((1, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : List[Any] = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : List[Any] = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[str] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Tuple = { "prompt": "a dog and a newt", "mask_image": mask, "image_latents": latents, "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Any = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Tuple = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : int = { "image": image, "source_prompt": "a cat and a frog", "target_prompt": "a dog and a newt", "generator": generator, "num_inference_steps": 2, "num_maps_per_mask": 2, "mask_encode_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Optional[int] = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Optional[int] = torch.manual_seed(a_ ) else: lowerCamelCase_ : Tuple = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Union[str, Any] = { "image": image, "prompt": "a cat and a frog", "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "decode_latents": True, "output_type": "numpy", } return inputs def _UpperCamelCase ( self ): if not hasattr(self.pipeline_class , "_optional_components" ): return lowerCamelCase_ : List[Any] = self.get_dummy_components() lowerCamelCase_ : int = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a_ , a_ , a_ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) lowerCamelCase_ : int = self.get_dummy_inputs(a_ ) lowerCamelCase_ : int = pipe(**a_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a_ ) lowerCamelCase_ : Optional[int] = self.pipeline_class.from_pretrained(a_ ) pipe_loaded.to(a_ ) pipe_loaded.set_progress_bar_config(disable=a_ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(a_ , a_ ) is None , F"""`{optional_component}` did not stay set to None after loading.""" , ) lowerCamelCase_ : List[str] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Optional[int] = pipe_loaded(**a_ )[0] lowerCamelCase_ : Optional[int] = np.abs(output - output_loaded ).max() self.assertLess(a_ , 1E-4 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : List[Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = self.get_dummy_mask_inputs(a_ ) lowerCamelCase_ : int = pipe.generate_mask(**a_ ) lowerCamelCase_ : List[Any] = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) lowerCamelCase_ : List[str] = np.array([0] * 9 ) lowerCamelCase_ : Optional[int] = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : Union[str, Any] = self.get_dummy_components() lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Dict = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : Dict = pipe.invert(**a_ ).images lowerCamelCase_ : str = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Dict = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : Any = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) def _UpperCamelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : int = {"beta_start": 0.0_00_85, "beta_end": 0.0_12, "beta_schedule": "scaled_linear"} lowerCamelCase_ : Optional[Any] = DPMSolverMultistepScheduler(**a_ ) lowerCamelCase_ : List[str] = DPMSolverMultistepInverseScheduler(**a_ ) lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : int = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : str = pipe.invert(**a_ ).images lowerCamelCase_ : int = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Union[str, Any] = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def _UpperCamelCase ( cls ): lowerCamelCase_ : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png" ) lowerCamelCase_ : int = raw_image.convert("RGB" ).resize((768, 768) ) lowerCamelCase_ : List[Any] = raw_image def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = torch.manual_seed(0 ) lowerCamelCase_ : Tuple = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : str = DDIMScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : Optional[int] = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : str = "a bowl of fruit" lowerCamelCase_ : Optional[int] = "a bowl of pears" lowerCamelCase_ : List[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ ).latents lowerCamelCase_ : List[str] = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = torch.manual_seed(0 ) lowerCamelCase_ : str = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : str = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = "a bowl of fruit" lowerCamelCase_ : Dict = "a bowl of pears" lowerCamelCase_ : Optional[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ , num_inference_steps=25 , ).latents lowerCamelCase_ : Any = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , num_inference_steps=25 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
73
1
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='''%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s''', datefmt='''%Y-%m-%d %H:%M:%S''', level=os.environ.get('''LOGLEVEL''', '''INFO''').upper(), stream=sys.stdout, ) __magic_name__ = logging.getLogger(__name__) __magic_name__ = {'''facebook/bart-base''': BartForConditionalGeneration} __magic_name__ = {'''facebook/bart-base''': BartTokenizer} def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Tuple = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph.") parser.add_argument( "--validation_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="A csv or a json file containing the validation data.") parser.add_argument( "--max_length" , type=lowerCAmelCase_ , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=lowerCAmelCase_ , help="Path to pretrained model or model identifier from huggingface.co/models." , required=lowerCAmelCase_ , ) parser.add_argument( "--config_name" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=lowerCAmelCase_ , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="Where to store the final ONNX file.") lowerCamelCase_ : List[str] = parser.parse_args() return args def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_="cpu"): '''simple docstring''' lowerCamelCase_ : Any = model_dict[model_name].from_pretrained(lowerCAmelCase_).to(lowerCAmelCase_) lowerCamelCase_ : str = tokenizer_dict[model_name].from_pretrained(lowerCAmelCase_) if model_name in ["facebook/bart-base"]: lowerCamelCase_ : Tuple = 0 lowerCamelCase_ : List[Any] = None lowerCamelCase_ : Tuple = 0 return huggingface_model, tokenizer def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' model.eval() lowerCamelCase_ : str = None lowerCamelCase_ : Union[str, Any] = torch.jit.script(BARTBeamSearchGenerator(lowerCAmelCase_)) with torch.no_grad(): lowerCamelCase_ : int = "My friends are cool but they eat too many carbs." lowerCamelCase_ : Dict = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt").to(model.device) lowerCamelCase_ : Dict = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=lowerCAmelCase_ , max_length=lowerCAmelCase_ , early_stopping=lowerCAmelCase_ , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowerCAmelCase_ , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , lowerCAmelCase_ , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=lowerCAmelCase_ , ) logger.info("Model exported to {}".format(lowerCAmelCase_)) lowerCamelCase_ : str = remove_dup_initializers(os.path.abspath(lowerCAmelCase_)) logger.info("Deduplicated and optimized model written to {}".format(lowerCAmelCase_)) lowerCamelCase_ : Tuple = onnxruntime.InferenceSession(lowerCAmelCase_) lowerCamelCase_ : int = ort_sess.run( lowerCAmelCase_ , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(lowerCAmelCase_), "max_length": np.array(lowerCAmelCase_), "decoder_start_token_id": np.array(model.config.decoder_start_token_id), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3) logger.info("Model outputs from torch and ONNX Runtime are similar.") logger.info("Success.") def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Dict = parse_args() lowerCamelCase_ : Tuple = 5 lowerCamelCase_ : Union[str, Any] = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO) transformers.utils.logging.set_verbosity_error() lowerCamelCase_ : Union[str, Any] = torch.device(args.device) lowerCamelCase_ ,lowerCamelCase_ : int = load_model_tokenizer(args.model_name_or_path , lowerCAmelCase_) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined") model.to(lowerCAmelCase_) if args.max_length: lowerCamelCase_ : int = args.max_length if args.num_beams: lowerCamelCase_ : Optional[Any] = args.num_beams if args.output_file_path: lowerCamelCase_ : Any = args.output_file_path else: lowerCamelCase_ : Optional[int] = "BART.onnx" logger.info("Exporting model to ONNX") export_and_validate_model(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) if __name__ == "__main__": main()
73
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : int = ["a", "b", "c"] # Defaults to last layer if both are None lowerCamelCase_ ,lowerCamelCase_ : Tuple = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ["c"] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = get_aligned_output_features_output_indices(["a", "c"] , a_ , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices lowerCamelCase_ ,lowerCamelCase_ : Tuple = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices lowerCamelCase_ ,lowerCamelCase_ : Dict = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [-3, -1] ) def _UpperCamelCase ( self ): # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = BackboneMixin() lowerCamelCase_ : List[Any] = ["a", "b", "c"] lowerCamelCase_ : Optional[int] = ["a", "c"] lowerCamelCase_ : Dict = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly lowerCamelCase_ : Union[str, Any] = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) lowerCamelCase_ : str = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
73
1
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
73
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : Union[str, Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Tuple = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : int = '''default_config.yaml''' __UpperCAmelCase : Tuple = config_folder / config_file __UpperCAmelCase : int = config_folder / '''_default_config.yaml''' __UpperCAmelCase : int = Path('''tests/test_configs''' ) @classmethod def _UpperCamelCase ( cls ): if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def _UpperCamelCase ( cls ): if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def _UpperCamelCase ( self ): for config in sorted(self.test_config_path.glob("**/*.yaml" ) ): with self.subTest(config_file=a_ ): execute_subprocess_async( self.base_cmd + ["--config_file", str(a_ ), self.test_file_path] , env=os.environ.copy() ) def _UpperCamelCase ( self ): execute_subprocess_async(["accelerate", "test"] , env=os.environ.copy() ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[Any] = '''test-tpu''' __UpperCAmelCase : Tuple = '''us-central1-a''' __UpperCAmelCase : Tuple = '''ls''' __UpperCAmelCase : str = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : Dict = '''Running gcloud compute tpus tpu-vm ssh''' def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + ["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--debug"] , return_stdout=a_ ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--command", "echo \"Hello World\"", "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command_file", self.command_file, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--accelerate_version", "12.0.0", "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , )
73
1
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy __magic_name__ = logging.getLogger(__name__) __magic_name__ = '''pytorch_model.bin''' @dataclasses.dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : str = dataclasses.field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models.'''} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default=__lowerCamelCase, metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co.'''}, ) @dataclasses.dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the training data.'''} ) __UpperCAmelCase : str = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the data to predict on.'''} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default=__lowerCamelCase, metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default=__lowerCamelCase, metadata={'''help''': '''The name of the task to train on.'''}, ) __UpperCAmelCase : Optional[List[str]] = dataclasses.field( default=__lowerCamelCase, metadata={'''help''': '''The list of labels for the task.'''} ) @dataclasses.dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : str = dataclasses.field( metadata={'''help''': '''The output directory where the model predictions and checkpoints will be written.'''} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default='''accuracy''', metadata={'''help''': '''The evaluation metric used for the task.'''} ) __UpperCAmelCase : Optional[str] = dataclasses.field( default='''no''', metadata={ '''help''': '''The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]''' }, ) __UpperCAmelCase : Optional[int] = dataclasses.field( default=10, metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''}, ) __UpperCAmelCase : Optional[float] = dataclasses.field( default=0.0, metadata={ '''help''': '''How much the specified evaluation metric must improve to satisfy early stopping conditions.''' }, ) __UpperCAmelCase : Optional[bool] = dataclasses.field( default=__lowerCamelCase, metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the confidence score.'''}, ) __UpperCAmelCase : Optional[bool] = dataclasses.field( default=__lowerCamelCase, metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the validation performance.'''}, ) __UpperCAmelCase : Optional[bool] = dataclasses.field( default=__lowerCamelCase, metadata={'''help''': '''Whether to fine-tune on labeled data after pseudo training.'''}, ) __UpperCAmelCase : Optional[float] = dataclasses.field( default=0.0, metadata={'''help''': '''Confidence threshold for pseudo-labeled data filtering.'''}, ) __UpperCAmelCase : Optional[int] = dataclasses.field( default=100, metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''}, ) __UpperCAmelCase : Optional[int] = dataclasses.field( default=__lowerCamelCase, metadata={'''help''': '''Random seed for initialization.'''}, ) def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : str = datasets.concatenate_datasets([infer_input, infer_output] , axis=1) if args.do_filter_by_confidence: lowerCamelCase_ : Optional[Any] = dataset.filter(lambda lowerCAmelCase_: example["probability"] > args.confidence_threshold) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 lowerCamelCase_ : Union[str, Any] = int(eval_result * len(lowerCAmelCase_)) print(lowerCAmelCase_) lowerCamelCase_ : Tuple = dataset.sort("probability" , reverse=lowerCAmelCase_) lowerCamelCase_ : Dict = dataset.select(range(lowerCAmelCase_)) lowerCamelCase_ : List[Any] = dataset.remove_columns(["label", "probability"]) lowerCamelCase_ : int = dataset.rename_column("prediction" , "label") lowerCamelCase_ : Dict = dataset.map(lambda lowerCAmelCase_: {"label": idalabel[example["label"]]}) lowerCamelCase_ : List[str] = dataset.shuffle(seed=args.seed) lowerCamelCase_ : Optional[Any] = os.path.join(lowerCAmelCase_ , F"""train_pseudo.{args.data_file_extension}""") if args.data_file_extension == "csv": dataset.to_csv(lowerCAmelCase_ , index=lowerCAmelCase_) else: dataset.to_json(lowerCAmelCase_) def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Union[str, Any] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.info(accelerator.state) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() lowerCamelCase_ : Any = STModelArguments(model_name_or_path=lowerCAmelCase_) lowerCamelCase_ : Tuple = STDataArguments(train_file=lowerCAmelCase_ , infer_file=lowerCAmelCase_) lowerCamelCase_ : Tuple = STTrainingArguments(output_dir=lowerCAmelCase_) lowerCamelCase_ : List[str] = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowerCAmelCase_).items(): setattr(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) for key, value in kwargs.items(): if hasattr(lowerCAmelCase_ , lowerCAmelCase_): setattr(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) # Sanity checks lowerCamelCase_ : Union[str, Any] = {} lowerCamelCase_ : Union[str, Any] = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None lowerCamelCase_ : Optional[Any] = args.train_file lowerCamelCase_ : Optional[Any] = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None lowerCamelCase_ : Union[str, Any] = args.eval_file for key in data_files: lowerCamelCase_ : int = data_files[key].split(".")[-1] assert extension in ["csv", "json"], F"""`{key}_file` should be a csv or a json file.""" if args.data_file_extension is None: lowerCamelCase_ : Optional[int] = extension else: assert extension == args.data_file_extension, F"""`{key}_file` should be a {args.data_file_extension} file`.""" assert ( args.eval_metric in datasets.list_metrics() ), F"""{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.""" # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) logger.info("Creating the initial data directory for self-training...") lowerCamelCase_ : Tuple = F"""{args.output_dir}/self-train_iter-{{}}""".format lowerCamelCase_ : str = data_dir_format(0) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowerCAmelCase_) os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_) accelerator.wait_for_everyone() lowerCamelCase_ : int = None lowerCamelCase_ : str = None lowerCamelCase_ : str = 0 lowerCamelCase_ : int = False # Show the progress bar lowerCamelCase_ : Optional[int] = tqdm(range(args.max_selftrain_iterations) , disable=not accelerator.is_local_main_process) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations)): lowerCamelCase_ : Dict = data_dir_format(lowerCAmelCase_) assert os.path.exists(lowerCAmelCase_) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 lowerCamelCase_ : Any = os.path.join(lowerCAmelCase_ , "stage-1") lowerCamelCase_ : Union[str, Any] = { "accelerator": accelerator, "model_name_or_path": args.model_name_or_path, "cache_dir": args.cache_dir, "do_train": True, "train_file": data_files["train"] if iteration == 0 else data_files["train_pseudo"], "do_eval": True if args.eval_file is not None else False, "eval_file": data_files["eval"], "do_predict": True, "infer_file": data_files["infer"], "task_name": args.task_name, "label_list": args.label_list, "output_dir": current_output_dir, "eval_metric": args.eval_metric, "evaluation_strategy": args.evaluation_strategy, "early_stopping_patience": args.early_stopping_patience, "early_stopping_threshold": args.early_stopping_threshold, "seed": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(lowerCAmelCase_ , lowerCAmelCase_): arguments_dict.update({key: value}) lowerCamelCase_ : Optional[Any] = os.path.join(lowerCAmelCase_ , "best-checkpoint" , lowerCAmelCase_) if os.path.exists(lowerCAmelCase_): logger.info( "Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1." , lowerCAmelCase_ , lowerCAmelCase_ , ) else: logger.info("***** Running self-training: iteration: %d, stage: 1 *****" , lowerCAmelCase_) finetune(**lowerCAmelCase_) accelerator.wait_for_everyone() assert os.path.exists(lowerCAmelCase_) logger.info("Self-training job completed: iteration: %d, stage: 1." , lowerCAmelCase_) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data lowerCamelCase_ : str = os.path.join(lowerCAmelCase_ , "best-checkpoint") lowerCamelCase_ : Optional[Any] = os.path.join(lowerCAmelCase_ , "stage-2") # Update arguments_dict lowerCamelCase_ : Tuple = model_path lowerCamelCase_ : Any = data_files["train"] lowerCamelCase_ : Optional[Any] = current_output_dir lowerCamelCase_ : List[str] = os.path.join(lowerCAmelCase_ , "best-checkpoint" , lowerCAmelCase_) if os.path.exists(lowerCAmelCase_): logger.info( "Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2." , lowerCAmelCase_ , lowerCAmelCase_ , ) else: logger.info("***** Running self-training: iteration: %d, stage: 2 *****" , lowerCAmelCase_) finetune(**lowerCAmelCase_) accelerator.wait_for_everyone() assert os.path.exists(lowerCAmelCase_) logger.info("Self-training job completed: iteration: %d, stage: 2." , lowerCAmelCase_) lowerCamelCase_ : int = iteration lowerCamelCase_ : Any = data_dir_format(iteration + 1) lowerCamelCase_ : Any = AutoConfig.from_pretrained(os.path.join(lowerCAmelCase_ , "best-checkpoint")) lowerCamelCase_ : Tuple = config.idalabel lowerCamelCase_ : Dict = os.path.join(lowerCAmelCase_ , "eval_results_best-checkpoint.json") lowerCamelCase_ : int = os.path.join(lowerCAmelCase_ , "test_results_best-checkpoint.json") assert os.path.exists(lowerCAmelCase_) with open(lowerCAmelCase_ , "r") as f: lowerCamelCase_ : List[str] = float(json.load(lowerCAmelCase_)[args.eval_metric]) lowerCamelCase_ : Union[str, Any] = os.path.join(lowerCAmelCase_ , "infer_output_best-checkpoint.csv") assert os.path.exists(lowerCAmelCase_) # Loading the dataset from local csv or json files. lowerCamelCase_ : Tuple = load_dataset(args.data_file_extension , data_files={"data": data_files["infer"]})["data"] lowerCamelCase_ : Any = load_dataset("csv" , data_files={"data": infer_output_file})["data"] if accelerator.is_main_process: os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_) shutil.copy(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , F"""eval_results_iter-{iteration}.json""")) if os.path.exists(lowerCAmelCase_): shutil.copy(lowerCAmelCase_ , os.path.join(lowerCAmelCase_ , F"""test_results_iter-{iteration}.json""")) create_pseudo_labeled_data(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) accelerator.wait_for_everyone() lowerCamelCase_ : Dict = os.path.join(lowerCAmelCase_ , F"""train_pseudo.{args.data_file_extension}""") if args.evaluation_strategy != IntervalStrategy.NO.value: lowerCamelCase_ : Union[str, Any] = eval_result if best_iteration is None: lowerCamelCase_ : Dict = new_iteration lowerCamelCase_ : Union[str, Any] = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: lowerCamelCase_ : Optional[int] = new_iteration lowerCamelCase_ : Dict = new_eval_result lowerCamelCase_ : Any = 0 else: if new_eval_result == best_eval_result: lowerCamelCase_ : Optional[int] = new_iteration lowerCamelCase_ : int = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: lowerCamelCase_ : Optional[Any] = True progress_bar.update(1) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("Best iteration: %d" , lowerCAmelCase_) logger.info("Best evaluation result: %s = %f" , args.eval_metric , lowerCAmelCase_) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowerCAmelCase_ , F"""eval_results_iter-{iteration}.json""") , os.path.join(lowerCAmelCase_ , "eval_results_best-iteration.json") , ) else: # Assume that the last iteration is the best logger.info("Best iteration: %d" , args.max_selftrain_iterations - 1) logger.info("Best evaluation result: %s = %f" , args.eval_metric , lowerCAmelCase_) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowerCAmelCase_ , F"""eval_results_iter-{args.max_selftrain_iterations - 1}.json""") , os.path.join(lowerCAmelCase_ , "eval_results_best-iteration.json") , )
73
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ , a_ ): super().__init__() self.register_modules(vqvae=a_ , unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self , a_ = 1 , a_ = None , a_ = 0.0 , a_ = 50 , a_ = "pil" , a_ = True , **a_ , ): lowerCamelCase_ : Optional[Any] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=a_ , ) lowerCamelCase_ : Optional[int] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ : Optional[int] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(a_ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature lowerCamelCase_ : Any = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ : Optional[int] = {} if accepts_eta: lowerCamelCase_ : Optional[int] = eta for t in self.progress_bar(self.scheduler.timesteps ): lowerCamelCase_ : Dict = self.scheduler.scale_model_input(a_ , a_ ) # predict the noise residual lowerCamelCase_ : Optional[Any] = self.unet(a_ , a_ ).sample # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ : List[Any] = self.scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample # decode the image latents with the VAE lowerCamelCase_ : str = self.vqvae.decode(a_ ).sample lowerCamelCase_ : Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) lowerCamelCase_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase_ : Optional[Any] = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
73
1
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''ClapFeatureExtractor''' __UpperCAmelCase : List[str] = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) def __call__( self , a_=None , a_=None , a_=None , **a_ ): lowerCamelCase_ : Any = kwargs.pop("sampling_rate" , a_ ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: lowerCamelCase_ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if audios is not None: lowerCamelCase_ : List[str] = self.feature_extractor( a_ , sampling_rate=a_ , return_tensors=a_ , **a_ ) if text is not None and audios is not None: lowerCamelCase_ : List[str] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) @property def _UpperCamelCase ( self ): lowerCamelCase_ : int = self.tokenizer.model_input_names lowerCamelCase_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
73
import re def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if len(re.findall("[ATCG]" , lowerCAmelCase_)) != len(lowerCAmelCase_): raise ValueError("Invalid Strand") return dna.translate(dna.maketrans("ATCG" , "TAGC")) if __name__ == "__main__": import doctest doctest.testmod()
73
1
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: lowerCamelCase_ : Optional[Any] = mf_knapsack(i - 1 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) else: lowerCamelCase_ : List[str] = max( mf_knapsack(i - 1 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) , mf_knapsack(i - 1 , lowerCAmelCase_ , lowerCAmelCase_ , j - wt[i - 1]) + val[i - 1] , ) lowerCamelCase_ : Optional[int] = val return f[i][j] def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Tuple = [[0] * (w + 1) for _ in range(n + 1)] for i in range(1 , n + 1): for w_ in range(1 , w + 1): if wt[i - 1] <= w_: lowerCamelCase_ : int = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_]) else: lowerCamelCase_ : str = dp[i - 1][w_] return dp[n][w_], dp def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if not (isinstance(lowerCAmelCase_ , (list, tuple)) and isinstance(lowerCAmelCase_ , (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples") lowerCamelCase_ : Tuple = len(lowerCAmelCase_) if num_items != len(lowerCAmelCase_): lowerCamelCase_ : str = ( "The number of weights must be the same as the number of values.\n" F"""But got {num_items} weights and {len(lowerCAmelCase_)} values""" ) raise ValueError(lowerCAmelCase_) for i in range(lowerCAmelCase_): if not isinstance(wt[i] , lowerCAmelCase_): lowerCamelCase_ : List[Any] = ( "All weights must be integers but got weight of " F"""type {type(wt[i])} at index {i}""" ) raise TypeError(lowerCAmelCase_) lowerCamelCase_ ,lowerCamelCase_ : Any = knapsack(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) lowerCamelCase_ : set = set() _construct_solution(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) return optimal_val, example_optional_set def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(lowerCAmelCase_ , lowerCAmelCase_ , i - 1 , lowerCAmelCase_ , lowerCAmelCase_) else: optimal_set.add(lowerCAmelCase_) _construct_solution(lowerCAmelCase_ , lowerCAmelCase_ , i - 1 , j - wt[i - 1] , lowerCAmelCase_) if __name__ == "__main__": __magic_name__ = [3, 2, 4, 4] __magic_name__ = [4, 3, 2, 3] __magic_name__ = 4 __magic_name__ = 6 __magic_name__ = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] __magic_name__ , __magic_name__ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 __magic_name__ , __magic_name__ = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('''optimal_value = ''', optimal_solution) print('''An optimal subset corresponding to the optimal value''', optimal_subset)
73
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False): '''simple docstring''' if radian_mode: return [magnitude * cos(lowerCAmelCase_), magnitude * sin(lowerCAmelCase_)] return [magnitude * cos(radians(lowerCAmelCase_)), magnitude * sin(radians(lowerCAmelCase_))] def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 10**-1): '''simple docstring''' lowerCamelCase_ : NDArray[floataa] = cross(lowerCAmelCase_ , lowerCAmelCase_) lowerCamelCase_ : float = sum(lowerCAmelCase_) return abs(lowerCAmelCase_) < eps if __name__ == "__main__": # Test to check if it works __magic_name__ = array( [ polar_force(7_18.4, 1_8_0 - 3_0), polar_force(8_79.54, 4_5), polar_force(1_0_0, -9_0), ] ) __magic_name__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg __magic_name__ = array( [ polar_force(3_0 * 9.81, 1_5), polar_force(2_1_5, 1_8_0 - 4_5), polar_force(2_6_4, 9_0 - 3_0), ] ) __magic_name__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg __magic_name__ = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]]) __magic_name__ = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
1
# limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( '''pipelines_utils''', '''0.22.0''', '''Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.''', standard_warn=False, stacklevel=3, )
73
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''ClapFeatureExtractor''' __UpperCAmelCase : List[str] = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) def __call__( self , a_=None , a_=None , a_=None , **a_ ): lowerCamelCase_ : Any = kwargs.pop("sampling_rate" , a_ ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: lowerCamelCase_ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if audios is not None: lowerCamelCase_ : List[str] = self.feature_extractor( a_ , sampling_rate=a_ , return_tensors=a_ , **a_ ) if text is not None and audios is not None: lowerCamelCase_ : List[str] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) @property def _UpperCamelCase ( self ): lowerCamelCase_ : int = self.tokenizer.model_input_names lowerCamelCase_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
73
1
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging __magic_name__ = '''\ ''' __magic_name__ = ''' Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity ''' __magic_name__ = ''' Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to \'cuda\' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"] >>> results = perplexity.compute(model_id=\'gpt2\', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 78.22 >>> print(round(results["perplexities"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric("perplexity") >>> input_texts = datasets.load_dataset("wikitext", ... "wikitext-2-raw-v1", ... split="test")["text"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=\'\'] >>> results = perplexity.compute(model_id=\'gpt2\', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) [\'perplexities\', \'mean_perplexity\'] >>> print(round(results["mean_perplexity"], 2)) 60.35 >>> print(round(results["perplexities"][0], 2)) 81.12 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): """simple docstring""" def _UpperCamelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "input_texts": datasets.Value("string" ), } ) , reference_urls=["https://huggingface.co/docs/transformers/perplexity"] , ) def _UpperCamelCase ( self , a_ , a_ , a_ = 16 , a_ = True , a_=None ): if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": lowerCamelCase_ : Optional[Any] = "cuda" else: lowerCamelCase_ : Tuple = "cuda" if torch.cuda.is_available() else "cpu" lowerCamelCase_ : Tuple = AutoModelForCausalLM.from_pretrained(a_ ) lowerCamelCase_ : List[str] = model.to(a_ ) lowerCamelCase_ : Any = AutoTokenizer.from_pretrained(a_ ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: lowerCamelCase_ : str = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(a_ ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" lowerCamelCase_ : List[str] = model.config.max_length - 1 else: lowerCamelCase_ : int = model.config.max_length lowerCamelCase_ : Any = tokenizer( a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , return_tensors="pt" , return_attention_mask=a_ , ).to(a_ ) lowerCamelCase_ : Dict = encodings["input_ids"] lowerCamelCase_ : Union[str, Any] = encodings["attention_mask"] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." lowerCamelCase_ : str = [] lowerCamelCase_ : Union[str, Any] = CrossEntropyLoss(reduction="none" ) for start_index in logging.tqdm(range(0 , len(a_ ) , a_ ) ): lowerCamelCase_ : Optional[Any] = min(start_index + batch_size , len(a_ ) ) lowerCamelCase_ : List[str] = encoded_texts[start_index:end_index] lowerCamelCase_ : Optional[Any] = attn_masks[start_index:end_index] if add_start_token: lowerCamelCase_ : Any = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(a_ ) lowerCamelCase_ : List[str] = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) lowerCamelCase_ : Tuple = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(a_ ), attn_mask] , dim=1 ) lowerCamelCase_ : Tuple = encoded_batch with torch.no_grad(): lowerCamelCase_ : Dict = model(a_ , attention_mask=a_ ).logits lowerCamelCase_ : List[str] = out_logits[..., :-1, :].contiguous() lowerCamelCase_ : Any = labels[..., 1:].contiguous() lowerCamelCase_ : int = attn_mask[..., 1:].contiguous() lowerCamelCase_ : Optional[int] = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , a_ ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(a_ )}
73
def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : Any = set() # Replace all the whitespace in our sentence lowerCamelCase_ : str = input_str.replace(" " , "") for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(lowerCAmelCase_) == 26 def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : List[Any] = [False] * 26 for char in input_str: if char.islower(): lowerCamelCase_ : List[Any] = True elif char.isupper(): lowerCamelCase_ : Optional[int] = True return all(lowerCAmelCase_) def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()}) == 26 def __magic_name__ ( ): '''simple docstring''' from timeit import timeit lowerCamelCase_ : Optional[int] = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_faster()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_fastest()" , setup=lowerCAmelCase_)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
73
1
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin __magic_name__ = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class lowerCAmelCase__ : """simple docstring""" def __init__( self , a_ , a_=16 , a_=13 , a_=7 , a_=14 , a_=10 , a_=19 , a_=5 , a_=4 , a_=True , a_=16 , a_=2 , a_=4 , a_=4 , a_="gelu" , a_=0.1 , a_=0.1 , a_=[1, 2, 3, 4, 5] , a_=25 , a_=5 , ): lowerCamelCase_ : int = d_model lowerCamelCase_ : int = parent lowerCamelCase_ : Optional[Any] = batch_size lowerCamelCase_ : str = prediction_length lowerCamelCase_ : Optional[int] = context_length lowerCamelCase_ : Optional[Any] = cardinality lowerCamelCase_ : str = num_time_features lowerCamelCase_ : Tuple = lags_sequence lowerCamelCase_ : Optional[Any] = embedding_dimension lowerCamelCase_ : Optional[Any] = is_training lowerCamelCase_ : Any = hidden_size lowerCamelCase_ : Dict = num_hidden_layers lowerCamelCase_ : List[Any] = num_attention_heads lowerCamelCase_ : Optional[Any] = intermediate_size lowerCamelCase_ : Optional[int] = hidden_act lowerCamelCase_ : int = hidden_dropout_prob lowerCamelCase_ : List[str] = attention_probs_dropout_prob lowerCamelCase_ : Tuple = context_length lowerCamelCase_ : List[str] = prediction_length + label_length lowerCamelCase_ : int = label_length lowerCamelCase_ : List[str] = moving_average lowerCamelCase_ : List[str] = autocorrelation_factor def _UpperCamelCase ( self ): return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Dict = config.context_length + max(config.lags_sequence ) lowerCamelCase_ : Optional[int] = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) lowerCamelCase_ : Any = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) lowerCamelCase_ : Union[str, Any] = floats_tensor([self.batch_size, _past_length] ) lowerCamelCase_ : int = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs lowerCamelCase_ : Union[str, Any] = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) lowerCamelCase_ : List[Any] = floats_tensor([self.batch_size, config.prediction_length] ) lowerCamelCase_ : List[str] = { "past_values": past_values, "static_categorical_features": static_categorical_features, "past_time_features": past_time_features, "past_observed_mask": past_observed_mask, "future_time_features": future_time_features, "future_values": future_values, } return inputs_dict def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = self.get_config() lowerCamelCase_ : Tuple = self.prepare_autoformer_inputs_dict(a_ ) return config, inputs_dict def _UpperCamelCase ( self ): lowerCamelCase_ ,lowerCamelCase_ : List[Any] = self.prepare_config_and_inputs() return config, inputs_dict def _UpperCamelCase ( self , a_ , a_ ): lowerCamelCase_ : List[str] = AutoformerModel(config=a_ ).to(a_ ).eval() lowerCamelCase_ : Union[str, Any] = model(**a_ ) lowerCamelCase_ : List[str] = outputs.encoder_last_hidden_state lowerCamelCase_ : Optional[int] = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ : List[str] = model.get_encoder() encoder.save_pretrained(a_ ) lowerCamelCase_ : Optional[Any] = AutoformerEncoder.from_pretrained(a_ ).to(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : int = model.create_network_inputs(**a_ ) lowerCamelCase_ ,lowerCamelCase_ : Tuple = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) lowerCamelCase_ : List[Any] = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) lowerCamelCase_ : List[Any] = encoder(inputs_embeds=a_ )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) lowerCamelCase_ : Union[str, Any] = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) lowerCamelCase_ : Tuple = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) lowerCamelCase_ : Optional[Any] = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) lowerCamelCase_ : str = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ : Optional[int] = model.get_decoder() decoder.save_pretrained(a_ ) lowerCamelCase_ : List[str] = AutoformerDecoder.from_pretrained(a_ ).to(a_ ) lowerCamelCase_ : Dict = decoder( trend=a_ , inputs_embeds=a_ , encoder_hidden_states=a_ , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Dict = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () __UpperCAmelCase : List[Any] = (AutoformerForPrediction,) if is_torch_available() else () __UpperCAmelCase : Optional[int] = {'''feature-extraction''': AutoformerModel} if is_torch_available() else {} __UpperCAmelCase : int = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : List[str] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : int = False def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = AutoformerModelTester(self ) lowerCamelCase_ : Union[str, Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def _UpperCamelCase ( self ): self.config_tester.run_common_tests() def _UpperCamelCase ( self ): lowerCamelCase_ ,lowerCamelCase_ : int = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: lowerCamelCase_ : Dict = model_class(a_ ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a_ ) lowerCamelCase_ ,lowerCamelCase_ : str = model_class.from_pretrained(a_ , output_loading_info=a_ ) self.assertEqual(info["missing_keys"] , [] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*a_ ) @unittest.skip(reason="Model has no tokens embeddings" ) def _UpperCamelCase ( self ): pass def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = inspect.signature(getattr(a_ , "forward" ) ) # The main input is the name of the argument after `self` lowerCamelCase_ : Optional[int] = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ ,lowerCamelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ : Tuple = model_class(a_ ) lowerCamelCase_ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ : Union[str, Any] = [*signature.parameters.keys()] lowerCamelCase_ : List[Any] = [ "past_values", "past_time_features", "past_observed_mask", "static_categorical_features", "static_real_features", "future_values", "future_time_features", ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append("future_observed_mask" ) expected_arg_names.extend( [ "decoder_attention_mask", "head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs", "past_key_values", "output_hidden_states", "output_attentions", "use_cache", "return_dict", ] ) self.assertListEqual(arg_names[: len(a_ )] , a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ ,lowerCamelCase_ : str = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ : Optional[Any] = True lowerCamelCase_ : Any = getattr(self.model_tester , "seq_length" , a_ ) lowerCamelCase_ : Union[str, Any] = getattr(self.model_tester , "decoder_seq_length" , a_ ) lowerCamelCase_ : Tuple = getattr(self.model_tester , "encoder_seq_length" , a_ ) lowerCamelCase_ : Tuple = getattr(self.model_tester , "d_model" , a_ ) lowerCamelCase_ : Optional[int] = getattr(self.model_tester , "num_attention_heads" , a_ ) lowerCamelCase_ : Dict = d_model // num_attention_heads for model_class in self.all_model_classes: lowerCamelCase_ : Optional[Any] = True lowerCamelCase_ : Dict = False lowerCamelCase_ : Dict = True lowerCamelCase_ : List[Any] = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): lowerCamelCase_ : Tuple = model(**self._prepare_for_class(a_ , a_ ) ) lowerCamelCase_ : Dict = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(a_ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCamelCase_ : List[Any] = True lowerCamelCase_ : Tuple = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): lowerCamelCase_ : Union[str, Any] = model(**self._prepare_for_class(a_ , a_ ) ) lowerCamelCase_ : Optional[Any] = outputs.encoder_attentions self.assertEqual(len(a_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) lowerCamelCase_ : List[str] = len(a_ ) lowerCamelCase_ : List[Any] = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(a_ , a_ ) # decoder attentions lowerCamelCase_ : int = outputs.decoder_attentions self.assertIsInstance(a_ , (list, tuple) ) self.assertEqual(len(a_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions lowerCamelCase_ : Optional[Any] = outputs.cross_attentions self.assertIsInstance(a_ , (list, tuple) ) self.assertEqual(len(a_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine lowerCamelCase_ : Union[str, Any] = True lowerCamelCase_ : Tuple = True lowerCamelCase_ : str = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): lowerCamelCase_ : str = model(**self._prepare_for_class(a_ , a_ ) ) self.assertEqual(out_len + 2 , len(a_ ) ) lowerCamelCase_ : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(a_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def _UpperCamelCase ( self ): super().test_retain_grad_hidden_states_attentions() def __magic_name__ ( lowerCAmelCase_="train-batch.pt"): '''simple docstring''' lowerCamelCase_ : Any = hf_hub_download(repo_id="hf-internal-testing/tourism-monthly-batch" , filename=lowerCAmelCase_ , repo_type="dataset") lowerCamelCase_ : Union[str, Any] = torch.load(lowerCAmelCase_ , map_location=lowerCAmelCase_) return batch @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = AutoformerModel.from_pretrained("huggingface/autoformer-tourism-monthly" ).to(a_ ) lowerCamelCase_ : Union[str, Any] = prepare_batch() with torch.no_grad(): lowerCamelCase_ : str = model( past_values=batch["past_values"] , past_time_features=batch["past_time_features"] , past_observed_mask=batch["past_observed_mask"] , static_categorical_features=batch["static_categorical_features"] , future_values=batch["future_values"] , future_time_features=batch["future_time_features"] , )[0] lowerCamelCase_ : Dict = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , a_ ) lowerCamelCase_ : str = torch.tensor( [[0.35_93, -1.33_98, 0.63_30], [0.22_79, 1.53_96, -0.17_92], [0.04_50, 1.32_25, -0.23_35]] , device=a_ ) self.assertTrue(torch.allclose(output[0, :3, :3] , a_ , atol=a_ ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = AutoformerForPrediction.from_pretrained("huggingface/autoformer-tourism-monthly" ).to(a_ ) lowerCamelCase_ : Union[str, Any] = prepare_batch("val-batch.pt" ) with torch.no_grad(): lowerCamelCase_ : int = model( past_values=batch["past_values"] , past_time_features=batch["past_time_features"] , past_observed_mask=batch["past_observed_mask"] , static_categorical_features=batch["static_categorical_features"] , ).encoder_last_hidden_state lowerCamelCase_ : str = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , a_ ) lowerCamelCase_ : str = torch.tensor( [[-0.07_34, -0.90_36, 0.83_58], [4.71_86, 2.41_13, 1.95_81], [1.79_53, 2.35_58, 1.29_70]] , device=a_ ) self.assertTrue(torch.allclose(output[0, :3, :3] , a_ , atol=a_ ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = AutoformerForPrediction.from_pretrained("huggingface/autoformer-tourism-monthly" ).to(a_ ) lowerCamelCase_ : Optional[int] = prepare_batch("val-batch.pt" ) with torch.no_grad(): lowerCamelCase_ : Dict = model.generate( static_categorical_features=batch["static_categorical_features"] , past_time_features=batch["past_time_features"] , past_values=batch["past_values"] , future_time_features=batch["future_time_features"] , past_observed_mask=batch["past_observed_mask"] , ) lowerCamelCase_ : Union[str, Any] = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , a_ ) lowerCamelCase_ : int = torch.tensor([31_30.67_63, 40_56.52_93, 70_53.07_86] , device=a_ ) lowerCamelCase_ : List[str] = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , a_ , rtol=1E-1 ) )
73
__magic_name__ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634E-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.35_58_18, } def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: lowerCamelCase_ : List[Any] = ( F"""Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n""" F"""Valid values are: {', '.join(lowerCAmelCase_)}""" ) raise ValueError(lowerCAmelCase_) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
73
1
import pickle import numpy as np from matplotlib import pyplot as plt class lowerCAmelCase__ : """simple docstring""" def __init__( self , a_ , a_ , a_ , a_ , a_ , a_=0.2 , a_=0.2 ): lowerCamelCase_ : Optional[Any] = bp_numa lowerCamelCase_ : int = bp_numa lowerCamelCase_ : Tuple = bp_numa lowerCamelCase_ : List[str] = conva_get[:2] lowerCamelCase_ : List[str] = conva_get[2] lowerCamelCase_ : int = size_pa lowerCamelCase_ : Dict = rate_w lowerCamelCase_ : Tuple = rate_t lowerCamelCase_ : Dict = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] lowerCamelCase_ : Dict = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) lowerCamelCase_ : int = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) lowerCamelCase_ : Union[str, Any] = -2 * np.random.rand(self.conva[1] ) + 1 lowerCamelCase_ : Any = -2 * np.random.rand(self.num_bpa ) + 1 lowerCamelCase_ : Optional[Any] = -2 * np.random.rand(self.num_bpa ) + 1 def _UpperCamelCase ( self , a_ ): # save model dict with pickle lowerCamelCase_ : Union[str, Any] = { "num_bp1": self.num_bpa, "num_bp2": self.num_bpa, "num_bp3": self.num_bpa, "conv1": self.conva, "step_conv1": self.step_conva, "size_pooling1": self.size_poolinga, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conva, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conva, "thre_bp2": self.thre_bpa, "thre_bp3": self.thre_bpa, } with open(a_ , "wb" ) as f: pickle.dump(a_ , a_ ) print(F"""Model saved: {save_path}""" ) @classmethod def _UpperCamelCase ( cls , a_ ): # read saved model with open(a_ , "rb" ) as f: lowerCamelCase_ : Tuple = pickle.load(a_ ) # noqa: S301 lowerCamelCase_ : Optional[Any] = model_dic.get("conv1" ) conv_get.append(model_dic.get("step_conv1" ) ) lowerCamelCase_ : Union[str, Any] = model_dic.get("size_pooling1" ) lowerCamelCase_ : Union[str, Any] = model_dic.get("num_bp1" ) lowerCamelCase_ : List[Any] = model_dic.get("num_bp2" ) lowerCamelCase_ : Any = model_dic.get("num_bp3" ) lowerCamelCase_ : int = model_dic.get("rate_weight" ) lowerCamelCase_ : Tuple = model_dic.get("rate_thre" ) # create model instance lowerCamelCase_ : Tuple = CNN(a_ , a_ , a_ , a_ , a_ , a_ , a_ ) # modify model parameter lowerCamelCase_ : Tuple = model_dic.get("w_conv1" ) lowerCamelCase_ : List[str] = model_dic.get("wkj" ) lowerCamelCase_ : Tuple = model_dic.get("vji" ) lowerCamelCase_ : Dict = model_dic.get("thre_conv1" ) lowerCamelCase_ : Optional[int] = model_dic.get("thre_bp2" ) lowerCamelCase_ : List[str] = model_dic.get("thre_bp3" ) return conv_ins def _UpperCamelCase ( self , a_ ): return 1 / (1 + np.exp(-1 * x )) def _UpperCamelCase ( self , a_ ): return round(a_ , 3 ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ ): # convolution process lowerCamelCase_ : Union[str, Any] = convs[0] lowerCamelCase_ : Dict = convs[1] lowerCamelCase_ : Optional[Any] = np.shape(a_ )[0] # get the data slice of original image data, data_focus lowerCamelCase_ : Tuple = [] for i_focus in range(0 , size_data - size_conv + 1 , a_ ): for j_focus in range(0 , size_data - size_conv + 1 , a_ ): lowerCamelCase_ : Optional[Any] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(a_ ) # calculate the feature map of every single kernel, and saved as list of matrix lowerCamelCase_ : List[Any] = [] lowerCamelCase_ : str = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(a_ ): lowerCamelCase_ : List[Any] = [] for i_focus in range(len(a_ ) ): lowerCamelCase_ : Optional[Any] = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(a_ ) ) lowerCamelCase_ : Tuple = np.asmatrix(a_ ).reshape( a_ , a_ ) data_featuremap.append(a_ ) # expanding the data slice to One dimenssion lowerCamelCase_ : int = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(a_ ) ) lowerCamelCase_ : str = np.asarray(a_ ) return focus_list, data_featuremap def _UpperCamelCase ( self , a_ , a_ , a_="average_pool" ): # pooling process lowerCamelCase_ : Any = len(featuremaps[0] ) lowerCamelCase_ : str = int(size_map / size_pooling ) lowerCamelCase_ : Tuple = [] for i_map in range(len(a_ ) ): lowerCamelCase_ : List[Any] = featuremaps[i_map] lowerCamelCase_ : Dict = [] for i_focus in range(0 , a_ , a_ ): for j_focus in range(0 , a_ , a_ ): lowerCamelCase_ : Union[str, Any] = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(a_ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(a_ ) ) lowerCamelCase_ : Tuple = np.asmatrix(a_ ).reshape(a_ , a_ ) featuremap_pooled.append(a_ ) return featuremap_pooled def _UpperCamelCase ( self , a_ ): # expanding three dimension data to one dimension list lowerCamelCase_ : Optional[Any] = [] for i in range(len(a_ ) ): lowerCamelCase_ : Tuple = np.shape(data[i] ) lowerCamelCase_ : Optional[Any] = data[i].reshape(1 , shapes[0] * shapes[1] ) lowerCamelCase_ : Optional[int] = data_listed.getA().tolist()[0] data_expanded.extend(a_ ) lowerCamelCase_ : Optional[int] = np.asarray(a_ ) return data_expanded def _UpperCamelCase ( self , a_ ): # expanding matrix to one dimension list lowerCamelCase_ : Union[str, Any] = np.asarray(a_ ) lowerCamelCase_ : str = np.shape(a_ ) lowerCamelCase_ : int = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ ): lowerCamelCase_ : Union[str, Any] = [] lowerCamelCase_ : List[str] = 0 for i_map in range(a_ ): lowerCamelCase_ : List[Any] = np.ones((size_map, size_map) ) for i in range(0 , a_ , a_ ): for j in range(0 , a_ , a_ ): lowerCamelCase_ : Any = pd_pool[ i_pool ] lowerCamelCase_ : List[Any] = i_pool + 1 lowerCamelCase_ : Optional[int] = np.multiply( a_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(a_ ) return pd_all def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_=bool ): # model traning print("----------------------Start Training-------------------------" ) print((" - - Shape: Train_Data ", np.shape(a_ )) ) print((" - - Shape: Teach_Data ", np.shape(a_ )) ) lowerCamelCase_ : str = 0 lowerCamelCase_ : Tuple = [] lowerCamelCase_ : Optional[Any] = 1_0000 while rp < n_repeat and mse >= error_accuracy: lowerCamelCase_ : Optional[Any] = 0 print(F"""-------------Learning Time {rp}--------------""" ) for p in range(len(a_ ) ): # print('------------Learning Image: %d--------------'%p) lowerCamelCase_ : Optional[int] = np.asmatrix(datas_train[p] ) lowerCamelCase_ : List[Any] = np.asarray(datas_teach[p] ) lowerCamelCase_ ,lowerCamelCase_ : Union[str, Any] = self.convolute( a_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowerCamelCase_ : Dict = self.pooling(a_ , self.size_poolinga ) lowerCamelCase_ : int = np.shape(a_ ) lowerCamelCase_ : Optional[Any] = self._expand(a_ ) lowerCamelCase_ : Optional[Any] = data_bp_input lowerCamelCase_ : Dict = np.dot(a_ , self.vji.T ) - self.thre_bpa lowerCamelCase_ : str = self.sig(a_ ) lowerCamelCase_ : Optional[int] = np.dot(a_ , self.wkj.T ) - self.thre_bpa lowerCamelCase_ : Union[str, Any] = self.sig(a_ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- lowerCamelCase_ : Tuple = np.multiply( (data_teach - bp_outa) , np.multiply(a_ , (1 - bp_outa) ) ) lowerCamelCase_ : Union[str, Any] = np.multiply( np.dot(a_ , self.wkj ) , np.multiply(a_ , (1 - bp_outa) ) ) lowerCamelCase_ : str = np.dot(a_ , self.vji ) lowerCamelCase_ : List[Any] = pd_i_all / (self.size_poolinga * self.size_poolinga) lowerCamelCase_ : List[str] = pd_conva_pooled.T.getA().tolist() lowerCamelCase_ : Union[str, Any] = self._calculate_gradient_from_pool( a_ , a_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): lowerCamelCase_ : Tuple = self._expand_mat(pd_conva_all[k_conv] ) lowerCamelCase_ : Dict = self.rate_weight * np.dot(a_ , a_ ) lowerCamelCase_ : Tuple = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) lowerCamelCase_ : List[Any] = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer lowerCamelCase_ : List[str] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight lowerCamelCase_ : Dict = self.vji + pd_j_all.T * bp_outa * self.rate_weight lowerCamelCase_ : Optional[Any] = self.thre_bpa - pd_k_all * self.rate_thre lowerCamelCase_ : Optional[int] = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image lowerCamelCase_ : int = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) lowerCamelCase_ : Any = rp + 1 lowerCamelCase_ : List[Any] = error_count / patterns all_mse.append(a_ ) def draw_error(): lowerCamelCase_ : str = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(a_ , "+-" ) plt.plot(a_ , "r--" ) plt.xlabel("Learning Times" ) plt.ylabel("All_mse" ) plt.grid(a_ , alpha=0.5 ) plt.show() print("------------------Training Complished---------------------" ) print((" - - Training epoch: ", rp, F""" - - Mse: {mse:.6f}""") ) if draw_e: draw_error() return mse def _UpperCamelCase ( self , a_ ): # model predict lowerCamelCase_ : Optional[Any] = [] print("-------------------Start Testing-------------------------" ) print((" - - Shape: Test_Data ", np.shape(a_ )) ) for p in range(len(a_ ) ): lowerCamelCase_ : Any = np.asmatrix(datas_test[p] ) lowerCamelCase_ ,lowerCamelCase_ : Dict = self.convolute( a_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowerCamelCase_ : int = self.pooling(a_ , self.size_poolinga ) lowerCamelCase_ : Dict = self._expand(a_ ) lowerCamelCase_ : List[str] = data_bp_input lowerCamelCase_ : Optional[Any] = bp_outa * self.vji.T - self.thre_bpa lowerCamelCase_ : List[Any] = self.sig(a_ ) lowerCamelCase_ : int = bp_outa * self.wkj.T - self.thre_bpa lowerCamelCase_ : int = self.sig(a_ ) produce_out.extend(bp_outa.getA().tolist() ) lowerCamelCase_ : str = [list(map(self.do_round , a_ ) ) for each in produce_out] return np.asarray(a_ ) def _UpperCamelCase ( self , a_ ): # return the data of image after convoluting process so we can check it out lowerCamelCase_ : Any = np.asmatrix(a_ ) lowerCamelCase_ ,lowerCamelCase_ : int = self.convolute( a_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowerCamelCase_ : str = self.pooling(a_ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
73
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 __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'''vocab_file''': '''spiece.model'''} __magic_name__ = { '''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''', } } __magic_name__ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) __magic_name__ = 0 __magic_name__ = 1 __magic_name__ = 2 __magic_name__ = 3 __magic_name__ = 4 class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[int] = '''left''' def __init__( self , a_ , a_=False , a_=True , a_=False , a_="<s>" , a_="</s>" , a_="<unk>" , a_="<sep>" , a_="<pad>" , a_="<cls>" , a_="<mask>" , a_=["<eop>", "<eod>"] , a_ = None , **a_ , ): # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ : str = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token lowerCamelCase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) lowerCamelCase_ : str = 3 lowerCamelCase_ : Dict = do_lower_case lowerCamelCase_ : str = remove_space lowerCamelCase_ : Tuple = keep_accents lowerCamelCase_ : Dict = vocab_file lowerCamelCase_ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) @property def _UpperCamelCase ( self ): return len(self.sp_model ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowerCamelCase_ : Any = self.__dict__.copy() lowerCamelCase_ : Optional[int] = None return state def __setstate__( self , a_ ): lowerCamelCase_ : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase_ : int = {} lowerCamelCase_ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self , a_ ): if self.remove_space: lowerCamelCase_ : Optional[int] = " ".join(inputs.strip().split() ) else: lowerCamelCase_ : str = inputs lowerCamelCase_ : Any = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: lowerCamelCase_ : Dict = unicodedata.normalize("NFKD" , a_ ) lowerCamelCase_ : int = "".join([c for c in outputs if not unicodedata.combining(a_ )] ) if self.do_lower_case: lowerCamelCase_ : Any = outputs.lower() return outputs def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : List[Any] = self.preprocess_text(a_ ) lowerCamelCase_ : Optional[int] = self.sp_model.encode(a_ , out_type=a_ ) lowerCamelCase_ : List[str] = [] for piece in pieces: if len(a_ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): lowerCamelCase_ : Tuple = self.sp_model.EncodeAsPieces(piece[:-1].replace(a_ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase_ : int = cur_pieces[1:] else: lowerCamelCase_ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(a_ ) else: new_pieces.append(a_ ) return new_pieces def _UpperCamelCase ( self , a_ ): return self.sp_model.PieceToId(a_ ) def _UpperCamelCase ( self , a_ ): return self.sp_model.IdToPiece(a_ ) def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Dict = "".join(a_ ).replace(a_ , " " ).strip() return out_string def _UpperCamelCase ( self , a_ , a_ = False , a_ = None , a_ = True , **a_ , ): lowerCamelCase_ : int = kwargs.pop("use_source_tokenizer" , a_ ) lowerCamelCase_ : List[str] = self.convert_ids_to_tokens(a_ , skip_special_tokens=a_ ) # 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 lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : List[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(a_ ) ) lowerCamelCase_ : Union[str, Any] = [] sub_texts.append(a_ ) else: current_sub_text.append(a_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase_ : Union[str, Any] = "".join(a_ ) lowerCamelCase_ : Optional[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase_ : List[Any] = self.clean_up_tokenization(a_ ) return clean_text else: return text def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, 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 _UpperCamelCase ( self , a_ , a_ = None , a_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ ) if token_ids_a is not None: return ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1, 1] return ([0] * len(a_ )) + [1, 1] def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, Any] = [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 _UpperCamelCase ( self , a_ , a_ = None ): if not os.path.isdir(a_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase_ : Any = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , "wb" ) as fi: lowerCamelCase_ : Dict = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
73
1
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(lowerCAmelCase_ , n - 1 , lowerCAmelCase_) * a) % mod else: lowerCamelCase_ : Tuple = binary_exponentiation(lowerCAmelCase_ , n / 2 , lowerCAmelCase_) return (b * b) % mod # a prime number __magic_name__ = 7_0_1 __magic_name__ = 1_0_0_0_0_0_0_0_0_0 __magic_name__ = 1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
73
def __magic_name__ ( lowerCAmelCase_ = 10 , lowerCAmelCase_ = 1000 , lowerCAmelCase_ = True): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)") return min_val if option else max_val def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' return int((number_a + number_a) / 2) def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)") if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value") def answer(lowerCAmelCase_) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started...") lowerCamelCase_ : Optional[int] = lower lowerCamelCase_ : Tuple = higher lowerCamelCase_ : Union[str, Any] = [] while True: lowerCamelCase_ : Optional[int] = get_avg(lowerCAmelCase_ , lowerCAmelCase_) last_numbers.append(lowerCAmelCase_) if answer(lowerCAmelCase_) == "low": lowerCamelCase_ : Any = number elif answer(lowerCAmelCase_) == "high": lowerCamelCase_ : Optional[int] = number else: break print(F"""guess the number : {last_numbers[-1]}""") print(F"""details : {last_numbers!s}""") def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Optional[int] = int(input("Enter lower value : ").strip()) lowerCamelCase_ : List[str] = int(input("Enter high value : ").strip()) lowerCamelCase_ : List[str] = int(input("Enter value to guess : ").strip()) guess_the_number(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) if __name__ == "__main__": main()
73
1
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class lowerCAmelCase__ ( ctypes.Structure ): """simple docstring""" # _fields is a specific attr expected by ctypes __UpperCAmelCase : str = [('''size''', ctypes.c_int), ('''visible''', ctypes.c_byte)] def __magic_name__ ( ): '''simple docstring''' if os.name == "nt": lowerCamelCase_ : List[Any] = CursorInfo() lowerCamelCase_ : str = ctypes.windll.kernelaa.GetStdHandle(-11) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowerCAmelCase_ , ctypes.byref(lowerCAmelCase_)) lowerCamelCase_ : Union[str, Any] = False ctypes.windll.kernelaa.SetConsoleCursorInfo(lowerCAmelCase_ , ctypes.byref(lowerCAmelCase_)) elif os.name == "posix": sys.stdout.write("\033[?25l") sys.stdout.flush() def __magic_name__ ( ): '''simple docstring''' if os.name == "nt": lowerCamelCase_ : str = CursorInfo() lowerCamelCase_ : Union[str, Any] = ctypes.windll.kernelaa.GetStdHandle(-11) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowerCAmelCase_ , ctypes.byref(lowerCAmelCase_)) lowerCamelCase_ : Dict = True ctypes.windll.kernelaa.SetConsoleCursorInfo(lowerCAmelCase_ , ctypes.byref(lowerCAmelCase_)) elif os.name == "posix": sys.stdout.write("\033[?25h") sys.stdout.flush() @contextmanager def __magic_name__ ( ): '''simple docstring''' try: hide_cursor() yield finally: show_cursor()
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[str] = '''cvt''' def __init__( self , a_=3 , a_=[7, 3, 3] , a_=[4, 2, 2] , a_=[2, 1, 1] , a_=[64, 192, 384] , a_=[1, 3, 6] , a_=[1, 2, 10] , a_=[4.0, 4.0, 4.0] , a_=[0.0, 0.0, 0.0] , a_=[0.0, 0.0, 0.0] , a_=[0.0, 0.0, 0.1] , a_=[True, True, True] , a_=[False, False, True] , a_=["dw_bn", "dw_bn", "dw_bn"] , a_=[3, 3, 3] , a_=[1, 1, 1] , a_=[2, 2, 2] , a_=[1, 1, 1] , a_=[1, 1, 1] , a_=0.02 , a_=1E-12 , **a_ , ): super().__init__(**a_ ) lowerCamelCase_ : Optional[Any] = num_channels lowerCamelCase_ : str = patch_sizes lowerCamelCase_ : List[Any] = patch_stride lowerCamelCase_ : str = patch_padding lowerCamelCase_ : str = embed_dim lowerCamelCase_ : Union[str, Any] = num_heads lowerCamelCase_ : Optional[Any] = depth lowerCamelCase_ : int = mlp_ratio lowerCamelCase_ : Union[str, Any] = attention_drop_rate lowerCamelCase_ : Optional[Any] = drop_rate lowerCamelCase_ : Optional[int] = drop_path_rate lowerCamelCase_ : Union[str, Any] = qkv_bias lowerCamelCase_ : int = cls_token lowerCamelCase_ : int = qkv_projection_method lowerCamelCase_ : int = kernel_qkv lowerCamelCase_ : Optional[Any] = padding_kv lowerCamelCase_ : Optional[int] = stride_kv lowerCamelCase_ : Optional[int] = padding_q lowerCamelCase_ : List[Any] = stride_q lowerCamelCase_ : Any = initializer_range lowerCamelCase_ : int = layer_norm_eps
73
1
from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ = None , a_ = None , a_ = None , a_ = None , a_ = False , a_ = False , a_ = None , **a_ , ): lowerCamelCase_ : Optional[Any] = path_or_paths lowerCamelCase_ : List[str] = split if split or isinstance(a_ , a_ ) else "train" lowerCamelCase_ : Tuple = features lowerCamelCase_ : List[str] = cache_dir lowerCamelCase_ : Optional[int] = keep_in_memory lowerCamelCase_ : Dict = streaming lowerCamelCase_ : Dict = num_proc lowerCamelCase_ : Any = kwargs @abstractmethod def _UpperCamelCase ( self ): pass class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ = None , a_ = None , a_ = False , a_ = False , a_ = None , **a_ , ): lowerCamelCase_ : Any = features lowerCamelCase_ : Optional[Any] = cache_dir lowerCamelCase_ : Optional[Any] = keep_in_memory lowerCamelCase_ : int = streaming lowerCamelCase_ : Tuple = num_proc lowerCamelCase_ : Optional[Any] = kwargs @abstractmethod def _UpperCamelCase ( self ): pass
73
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __magic_name__ = {'''processing_layoutxlm''': ['''LayoutXLMProcessor''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''LayoutXLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''LayoutXLMTokenizerFast'''] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
73
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''BridgeTower/bridgetower-base''': '''https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json''', '''BridgeTower/bridgetower-base-itm-mlm''': ( '''https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json''' ), } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Any = '''bridgetower_vision_model''' def __init__( self , a_=768 , a_=12 , a_=3 , a_=16 , a_=288 , a_=1 , a_=1E-05 , a_=False , a_=True , a_=False , **a_ , ): super().__init__(**a_ ) lowerCamelCase_ : Optional[int] = hidden_size lowerCamelCase_ : Optional[Any] = num_hidden_layers lowerCamelCase_ : List[str] = num_channels lowerCamelCase_ : Tuple = patch_size lowerCamelCase_ : List[str] = image_size lowerCamelCase_ : Any = initializer_factor lowerCamelCase_ : Any = layer_norm_eps lowerCamelCase_ : Dict = stop_gradient lowerCamelCase_ : Optional[Any] = share_layernorm lowerCamelCase_ : Union[str, Any] = remove_last_layer @classmethod def _UpperCamelCase ( cls , a_ , **a_ ): lowerCamelCase_ ,lowerCamelCase_ : str = cls.get_config_dict(a_ , **a_ ) if config_dict.get("model_type" ) == "bridgetower": lowerCamelCase_ : Union[str, Any] = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(a_ , **a_ ) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = '''bridgetower_text_model''' def __init__( self , a_=5_0265 , a_=768 , a_=12 , a_=12 , a_=1 , a_=3072 , a_="gelu" , a_=0.1 , a_=0.1 , a_=514 , a_=1 , a_=1E-05 , a_=1 , a_=0 , a_=2 , a_="absolute" , a_=True , **a_ , ): super().__init__(**a_ ) lowerCamelCase_ : List[Any] = vocab_size lowerCamelCase_ : List[str] = hidden_size lowerCamelCase_ : str = num_hidden_layers lowerCamelCase_ : Tuple = num_attention_heads lowerCamelCase_ : Union[str, Any] = hidden_act lowerCamelCase_ : Tuple = initializer_factor lowerCamelCase_ : Optional[int] = intermediate_size lowerCamelCase_ : Tuple = hidden_dropout_prob lowerCamelCase_ : Optional[Any] = attention_probs_dropout_prob lowerCamelCase_ : str = max_position_embeddings lowerCamelCase_ : str = type_vocab_size lowerCamelCase_ : Any = layer_norm_eps lowerCamelCase_ : Dict = position_embedding_type lowerCamelCase_ : Optional[int] = use_cache lowerCamelCase_ : Any = pad_token_id lowerCamelCase_ : Optional[int] = bos_token_id lowerCamelCase_ : Tuple = eos_token_id @classmethod def _UpperCamelCase ( cls , a_ , **a_ ): lowerCamelCase_ ,lowerCamelCase_ : int = cls.get_config_dict(a_ , **a_ ) if config_dict.get("model_type" ) == "bridgetower": lowerCamelCase_ : List[Any] = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(a_ , **a_ ) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = '''bridgetower''' def __init__( self , a_=True , a_="gelu" , a_=768 , a_=1 , a_=1E-05 , a_=False , a_="add" , a_=12 , a_=6 , a_=False , a_=False , a_=None , a_=None , **a_ , ): # TODO: remove this once the Hub files are updated. lowerCamelCase_ : Tuple = kwargs.pop("text_config_dict" , a_ ) lowerCamelCase_ : Optional[int] = kwargs.pop("vision_config_dict" , a_ ) super().__init__(**a_ ) lowerCamelCase_ : List[Any] = share_cross_modal_transformer_layers lowerCamelCase_ : List[Any] = hidden_act lowerCamelCase_ : List[Any] = hidden_size lowerCamelCase_ : Union[str, Any] = initializer_factor lowerCamelCase_ : Any = layer_norm_eps lowerCamelCase_ : Optional[Any] = share_link_tower_layers lowerCamelCase_ : Optional[Any] = link_tower_type lowerCamelCase_ : Any = num_attention_heads lowerCamelCase_ : Union[str, Any] = num_hidden_layers lowerCamelCase_ : int = tie_word_embeddings lowerCamelCase_ : Optional[Any] = init_layernorm_from_vision_encoder if text_config is None: lowerCamelCase_ : int = {} logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values." ) if vision_config is None: lowerCamelCase_ : Tuple = {} logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values." ) lowerCamelCase_ : Tuple = BridgeTowerTextConfig(**a_ ) lowerCamelCase_ : Optional[Any] = BridgeTowerVisionConfig(**a_ ) @classmethod def _UpperCamelCase ( cls , a_ , a_ , **a_ ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = copy.deepcopy(self.__dict__ ) lowerCamelCase_ : List[str] = self.text_config.to_dict() lowerCamelCase_ : Dict = self.vision_config.to_dict() lowerCamelCase_ : str = self.__class__.model_type return output
73
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''EncodecFeatureExtractor''' __UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) lowerCamelCase_ : Optional[Any] = self.feature_extractor lowerCamelCase_ : Optional[int] = False def _UpperCamelCase ( self , a_=None , a_=None , a_=True ): return self.tokenizer.get_decoder_prompt_ids(task=a_ , language=a_ , no_timestamps=a_ ) def __call__( self , *a_ , **a_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a_ , **a_ ) lowerCamelCase_ : str = kwargs.pop("audio" , a_ ) lowerCamelCase_ : List[str] = kwargs.pop("sampling_rate" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("text" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : int = args[0] lowerCamelCase_ : str = 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 text is not None: lowerCamelCase_ : Dict = self.tokenizer(a_ , **a_ ) if audio is not None: lowerCamelCase_ : Optional[Any] = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ ) if audio is None: return inputs elif text is None: return audio_inputs else: lowerCamelCase_ : Dict = audio_inputs["input_values"] if "padding_mask" in audio_inputs: lowerCamelCase_ : int = audio_inputs["padding_mask"] return inputs def _UpperCamelCase ( self , *a_ , **a_ ): lowerCamelCase_ : Dict = kwargs.pop("audio" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("padding_mask" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : Optional[int] = args[0] lowerCamelCase_ : Optional[Any] = args[1:] if audio_values is not None: return self._decode_audio(a_ , padding_mask=a_ ) else: return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Any = to_numpy(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[str] = audio_values.shape if padding_mask is None: return list(a_ ) lowerCamelCase_ : Tuple = to_numpy(a_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) lowerCamelCase_ : List[str] = seq_len - padding_mask.shape[-1] lowerCamelCase_ : int = 1 - self.feature_extractor.padding_value lowerCamelCase_ : List[Any] = np.pad(a_ , ((0, 0), (0, difference)) , "constant" , constant_values=a_ ) lowerCamelCase_ : str = audio_values.tolist() for i in range(a_ ): lowerCamelCase_ : Dict = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] lowerCamelCase_ : Dict = sliced_audio.reshape(a_ , -1 ) return audio_values
73
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __magic_name__ = {'''configuration_mra''': ['''MRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MraConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''MRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MraForMaskedLM''', '''MraForMultipleChoice''', '''MraForQuestionAnswering''', '''MraForSequenceClassification''', '''MraForTokenClassification''', '''MraLayer''', '''MraModel''', '''MraPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
73
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if digit_amount > 0: return round(number - int(lowerCAmelCase_) , lowerCAmelCase_) return number - int(lowerCAmelCase_) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.3_45, 1)) print(decimal_isolate(35.3_45, 2)) print(decimal_isolate(35.3_45, 3)) print(decimal_isolate(-14.7_89, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.1_23, 1)) print(decimal_isolate(-14.1_23, 2)) print(decimal_isolate(-14.1_23, 3))
73
1
import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter __magic_name__ = True except ImportError: __magic_name__ = False __magic_name__ = logging.get_logger(__name__) # pylint: disable=invalid-name def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' return AddNewModelCommand(args.testing , args.testing_file , path=args.path) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" @staticmethod def _UpperCamelCase ( a_ ): lowerCamelCase_ : int = parser.add_parser("add-new-model" ) add_new_model_parser.add_argument("--testing" , action="store_true" , help="If in testing mode." ) add_new_model_parser.add_argument("--testing_file" , type=a_ , help="Configuration file on which to run." ) add_new_model_parser.add_argument( "--path" , type=a_ , help="Path to cookiecutter. Should only be used for testing purposes." ) add_new_model_parser.set_defaults(func=a_ ) def __init__( self , a_ , a_ , a_=None , *a_ ): lowerCamelCase_ : Union[str, Any] = testing lowerCamelCase_ : Optional[Any] = testing_file lowerCamelCase_ : List[str] = path def _UpperCamelCase ( self ): warnings.warn( "The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. " "It is not actively maintained anymore, so might give a result that won't pass all tests and quality " "checks, you should use `transformers-cli add-new-model-like` instead." ) if not _has_cookiecutter: raise ImportError( "Model creation dependencies are required to use the `add_new_model` command. Install them by running " "the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n" ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory lowerCamelCase_ : Optional[int] = [directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]] if len(a_ ) > 0: raise ValueError( "Several directories starting with `cookiecutter-template-` in current working directory. " "Please clean your directory by removing all folders starting with `cookiecutter-template-` or " "change your working directory." ) lowerCamelCase_ : List[Any] = ( Path(a_ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) lowerCamelCase_ : List[str] = path_to_transformer_root / "templates" / "adding_a_new_model" # Execute cookiecutter if not self._testing: cookiecutter(str(a_ ) ) else: with open(self._testing_file , "r" ) as configuration_file: lowerCamelCase_ : List[str] = json.load(a_ ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) , no_input=a_ , extra_context=a_ , ) lowerCamelCase_ : Optional[int] = [directory for directory in os.listdir() if "cookiecutter-template-" in directory[:22]][0] # Retrieve configuration with open(directory + "/configuration.json" , "r" ) as configuration_file: lowerCamelCase_ : Any = json.load(a_ ) lowerCamelCase_ : Tuple = configuration["lowercase_modelname"] lowerCamelCase_ : int = configuration["generate_tensorflow_pytorch_and_flax"] os.remove(F"""{directory}/configuration.json""" ) lowerCamelCase_ : Union[str, Any] = "PyTorch" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ : int = "TensorFlow" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ : Dict = "Flax" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ : Tuple = F"""{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}""" os.makedirs(a_ , exist_ok=a_ ) os.makedirs(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}""" , exist_ok=a_ ) # Tests require submodules as they have parent imports with open(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py""" , "w" ): pass shutil.move( F"""{directory}/__init__.py""" , F"""{model_dir}/__init__.py""" , ) shutil.move( F"""{directory}/configuration_{lowercase_model_name}.py""" , F"""{model_dir}/configuration_{lowercase_model_name}.py""" , ) def remove_copy_lines(a_ ): with open(a_ , "r" ) as f: lowerCamelCase_ : Union[str, Any] = f.readlines() with open(a_ , "w" ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(a_ ) if output_pytorch: if not self._testing: remove_copy_lines(F"""{directory}/modeling_{lowercase_model_name}.py""" ) shutil.move( F"""{directory}/modeling_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_{lowercase_model_name}.py""" ) os.remove(F"""{directory}/test_modeling_{lowercase_model_name}.py""" ) if output_tensorflow: if not self._testing: remove_copy_lines(F"""{directory}/modeling_tf_{lowercase_model_name}.py""" ) shutil.move( F"""{directory}/modeling_tf_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_tf_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_tf_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_tf_{lowercase_model_name}.py""" ) os.remove(F"""{directory}/test_modeling_tf_{lowercase_model_name}.py""" ) if output_flax: if not self._testing: remove_copy_lines(F"""{directory}/modeling_flax_{lowercase_model_name}.py""" ) shutil.move( F"""{directory}/modeling_flax_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_flax_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_flax_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_flax_{lowercase_model_name}.py""" ) os.remove(F"""{directory}/test_modeling_flax_{lowercase_model_name}.py""" ) shutil.move( F"""{directory}/{lowercase_model_name}.md""" , F"""{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md""" , ) shutil.move( F"""{directory}/tokenization_{lowercase_model_name}.py""" , F"""{model_dir}/tokenization_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/tokenization_fast_{lowercase_model_name}.py""" , F"""{model_dir}/tokenization_{lowercase_model_name}_fast.py""" , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(a_ , a_ , a_ ): # Create temp file lowerCamelCase_ ,lowerCamelCase_ : Dict = mkstemp() lowerCamelCase_ : Dict = False with fdopen(a_ , "w" ) as new_file: with open(a_ ) as old_file: for line in old_file: new_file.write(a_ ) if line_to_copy_below in line: lowerCamelCase_ : List[Any] = True for line_to_copy in lines_to_copy: new_file.write(a_ ) if not line_found: raise ValueError(F"""Line {line_to_copy_below} was not found in file.""" ) # Copy the file permissions from the old file to the new file copymode(a_ , a_ ) # Remove original file remove(a_ ) # Move new file move(a_ , a_ ) def skip_units(a_ ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(a_ ): with open(a_ ) as datafile: lowerCamelCase_ : Any = [] lowerCamelCase_ : Dict = False lowerCamelCase_ : str = False for line in datafile: if "# To replace in: " in line and "##" not in line: lowerCamelCase_ : List[str] = line.split("\"" )[1] lowerCamelCase_ : Any = skip_units(a_ ) elif "# Below: " in line and "##" not in line: lowerCamelCase_ : str = line.split("\"" )[1] lowerCamelCase_ : str = skip_units(a_ ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(a_ , a_ , a_ ) lowerCamelCase_ : Any = [] elif "# Replace with" in line and "##" not in line: lowerCamelCase_ : Optional[Any] = [] elif "##" not in line: lines_to_copy.append(a_ ) remove(a_ ) replace_in_files(F"""{directory}/to_replace_{lowercase_model_name}.py""" ) os.rmdir(a_ )
73
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , a_ , a_=7 , a_=3 , a_=18 , a_=30 , a_=400 , a_=True , a_=None , a_=True , ): lowerCamelCase_ : int = size if size is not None else {"height": 18, "width": 18} lowerCamelCase_ : str = parent lowerCamelCase_ : str = batch_size lowerCamelCase_ : Tuple = num_channels lowerCamelCase_ : Optional[int] = image_size lowerCamelCase_ : List[str] = min_resolution lowerCamelCase_ : Tuple = max_resolution lowerCamelCase_ : Tuple = do_resize lowerCamelCase_ : Dict = size lowerCamelCase_ : List[str] = apply_ocr def _UpperCamelCase ( self ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowerCAmelCase__ ( __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = LayoutLMvaImageProcessingTester(self ) @property def _UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , "do_resize" ) ) self.assertTrue(hasattr(a_ , "size" ) ) self.assertTrue(hasattr(a_ , "apply_ocr" ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) lowerCamelCase_ : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def _UpperCamelCase ( self ): pass def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input lowerCamelCase_ : List[str] = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , a_ ) self.assertIsInstance(encoding.boxes , a_ ) # Test batched lowerCamelCase_ : int = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) # Test not batched input lowerCamelCase_ : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCamelCase_ : Any = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input lowerCamelCase_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCamelCase_ : Union[str, Any] = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # with apply_OCR = True lowerCamelCase_ : Any = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCamelCase_ : Optional[Any] = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) lowerCamelCase_ : Optional[Any] = Image.open(ds[0]["file"] ).convert("RGB" ) lowerCamelCase_ : List[Any] = image_processing(a_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCamelCase_ : List[Any] = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 lowerCamelCase_ : Tuple = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , a_ ) self.assertListEqual(encoding.boxes , a_ ) # with apply_OCR = False lowerCamelCase_ : List[str] = LayoutLMvaImageProcessor(apply_ocr=a_ ) lowerCamelCase_ : List[str] = image_processing(a_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
73
1
import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger __magic_name__ = '''<<<<<<< This should probably be modified because it mentions: ''' __magic_name__ = '''======= >>>>>>> ''' __magic_name__ = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] __magic_name__ = [ # (pattern, replacement) # Order is important here for some replacements (R'''tfds\.core''', R'''datasets'''), (R'''tf\.io\.gfile\.GFile''', R'''open'''), (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''), (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''), (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''), (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''), (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''), (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (R'''tfds\.''', R'''datasets.'''), (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''), (R'''self\.builder_config''', R'''self.config'''), ] def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' return ConvertCommand(args.tfds_path , args.datasets_directory) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" @staticmethod def _UpperCamelCase ( a_ ): lowerCamelCase_ : str = parser.add_parser( "convert" , help="Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset." , ) train_parser.add_argument( "--tfds_path" , type=a_ , required=a_ , help="Path to a TensorFlow Datasets folder to convert or a single tfds file to convert." , ) train_parser.add_argument( "--datasets_directory" , type=a_ , required=a_ , help="Path to the HuggingFace Datasets folder." ) train_parser.set_defaults(func=a_ ) def __init__( self , a_ , a_ , *a_ ): lowerCamelCase_ : List[str] = get_logger("datasets-cli/converting" ) lowerCamelCase_ : Any = tfds_path lowerCamelCase_ : List[str] = datasets_directory def _UpperCamelCase ( self ): if os.path.isdir(self._tfds_path ): lowerCamelCase_ : Optional[int] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): lowerCamelCase_ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("--tfds_path is neither a directory nor a file. Please check path." ) lowerCamelCase_ : Any = os.path.abspath(self._datasets_directory ) self._logger.info(F"""Converting datasets from {abs_tfds_path} to {abs_datasets_path}""" ) lowerCamelCase_ : str = [] lowerCamelCase_ : Dict = [] lowerCamelCase_ : Any = {} if os.path.isdir(self._tfds_path ): lowerCamelCase_ : Optional[int] = os.listdir(a_ ) else: lowerCamelCase_ : Any = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(F"""Looking at file {f_name}""" ) lowerCamelCase_ : Union[str, Any] = os.path.join(a_ , a_ ) lowerCamelCase_ : List[str] = os.path.join(a_ , a_ ) if not os.path.isfile(a_ ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("Skipping file" ) continue with open(a_ , encoding="utf-8" ) as f: lowerCamelCase_ : Any = f.readlines() lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : List[str] = False lowerCamelCase_ : Union[str, Any] = False lowerCamelCase_ : Optional[Any] = [] for line in lines: lowerCamelCase_ : Tuple = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: lowerCamelCase_ : str = "import datasets\n" elif "import tensorflow" in out_line: # order is important here lowerCamelCase_ : Any = "" continue elif "from absl import logging" in out_line: lowerCamelCase_ : Tuple = "from datasets import logging\n" elif "getLogger" in out_line: lowerCamelCase_ : Tuple = out_line.replace("getLogger" , "get_logger" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): lowerCamelCase_ : List[str] = True lowerCamelCase_ : Tuple = list(filter(lambda a_ : e in out_line , a_ ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(a_ ) + "\n" ) out_lines.append(a_ ) out_lines.append(a_ ) continue else: for pattern, replacement in TO_CONVERT: lowerCamelCase_ : Tuple = re.sub(a_ , a_ , a_ ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: lowerCamelCase_ : int = re.match(R"from\stensorflow_datasets.*import\s([^\.\r\n]+)" , a_ ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split("," ) ) lowerCamelCase_ : List[Any] = "from . import " + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(F"""Error converting {out_line.strip()}""" ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: lowerCamelCase_ : Optional[int] = True out_lines.append(a_ ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset lowerCamelCase_ : str = f_name.replace(".py" , "" ) lowerCamelCase_ : str = os.path.join(a_ , a_ ) lowerCamelCase_ : Any = os.path.join(a_ , a_ ) os.makedirs(a_ , exist_ok=a_ ) self._logger.info(F"""Adding directory {output_dir}""" ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(a_ ) if needs_manual_update: with_manual_update.append(a_ ) with open(a_ , "w" , encoding="utf-8" ) as f: f.writelines(a_ ) self._logger.info(F"""Converted in {output_file}""" ) for utils_file in utils_files: try: lowerCamelCase_ : Any = os.path.basename(a_ ) lowerCamelCase_ : int = imports_to_builder_map[f_name.replace(".py" , "" )] self._logger.info(F"""Moving {dest_folder} to {utils_file}""" ) shutil.copy(a_ , a_ ) except KeyError: self._logger.error(F"""Cannot find destination folder for {utils_file}. Please copy manually.""" ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( F"""You need to manually update file {file_path} to remove configurations using 'TextEncoderConfig'.""" )
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''studio-ousia/luke-base''': '''https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json''', '''studio-ousia/luke-large''': '''https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json''', } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = '''luke''' def __init__( self , a_=5_0267 , a_=50_0000 , a_=768 , a_=256 , a_=12 , a_=12 , a_=3072 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=2 , a_=0.02 , a_=1E-12 , a_=True , a_=None , a_=1 , a_=0 , a_=2 , **a_ , ): super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) lowerCamelCase_ : Tuple = vocab_size lowerCamelCase_ : Optional[int] = entity_vocab_size lowerCamelCase_ : Any = hidden_size lowerCamelCase_ : Dict = entity_emb_size lowerCamelCase_ : List[Any] = num_hidden_layers lowerCamelCase_ : int = num_attention_heads lowerCamelCase_ : Union[str, Any] = hidden_act lowerCamelCase_ : Tuple = intermediate_size lowerCamelCase_ : Optional[Any] = hidden_dropout_prob lowerCamelCase_ : Any = attention_probs_dropout_prob lowerCamelCase_ : Optional[Any] = max_position_embeddings lowerCamelCase_ : str = type_vocab_size lowerCamelCase_ : int = initializer_range lowerCamelCase_ : List[Any] = layer_norm_eps lowerCamelCase_ : Optional[int] = use_entity_aware_attention lowerCamelCase_ : str = classifier_dropout
73
1
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __magic_name__ = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __magic_name__ = '''main''' # Default branch name __magic_name__ = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) __magic_name__ = '''aaaaaaa''' # This commit does not exist, so we should 404. __magic_name__ = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes __magic_name__ = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def __magic_name__ ( ): '''simple docstring''' print("Welcome!") yield print("Bye!") @contextlib.contextmanager def __magic_name__ ( ): '''simple docstring''' print("Bonjour!") yield print("Au revoir!") class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec("transformers" ) is not None class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _UpperCamelCase ( self , a_ ): with ContextManagers([] ): print("Transformers are awesome!" ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , "Transformers are awesome!\n" ) @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _UpperCamelCase ( self , a_ ): with ContextManagers([context_en()] ): print("Transformers are awesome!" ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Welcome!\nTransformers are awesome!\nBye!\n" ) @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _UpperCamelCase ( self , a_ ): with ContextManagers([context_fr(), context_en()] ): print("Transformers are awesome!" ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n" ) @require_torch def _UpperCamelCase ( self ): self.assertEqual(find_labels(a_ ) , ["labels"] ) self.assertEqual(find_labels(a_ ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(a_ ) , ["start_positions", "end_positions"] ) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" pass self.assertEqual(find_labels(a_ ) , ["labels"] ) @require_tf def _UpperCamelCase ( self ): self.assertEqual(find_labels(a_ ) , ["labels"] ) self.assertEqual(find_labels(a_ ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(a_ ) , ["start_positions", "end_positions"] ) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" pass self.assertEqual(find_labels(a_ ) , ["labels"] ) @require_flax def _UpperCamelCase ( self ): # Flax models don't have labels self.assertEqual(find_labels(a_ ) , [] ) self.assertEqual(find_labels(a_ ) , [] ) self.assertEqual(find_labels(a_ ) , [] ) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" pass self.assertEqual(find_labels(a_ ) , [] )
73
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __magic_name__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class lowerCAmelCase__ ( datasets.BuilderConfig ): """simple docstring""" __UpperCAmelCase : Optional[datasets.Features] = None def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' import pyspark def generate_fn(): lowerCamelCase_ : Dict = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id")) for partition_id in partition_order: lowerCamelCase_ : Dict = df_with_partition_id.select("*").where(F"""part_id = {partition_id}""").drop("part_id") lowerCamelCase_ : Dict = partition_df.collect() lowerCamelCase_ : Dict = 0 for row in rows: yield F"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class lowerCAmelCase__ ( _BaseExamplesIterable ): """simple docstring""" def __init__( self , a_ , a_=None , ): lowerCamelCase_ : Dict = df lowerCamelCase_ : Optional[Any] = partition_order or range(self.df.rdd.getNumPartitions() ) lowerCamelCase_ : int = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ): yield from self.generate_examples_fn() def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Optional[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a_ ) return SparkExamplesIterable(self.df , partition_order=a_ ) def _UpperCamelCase ( self , a_ , a_ ): lowerCamelCase_ : Dict = self.split_shard_indices_by_worker(a_ , a_ ) return SparkExamplesIterable(self.df , partition_order=a_ ) @property def _UpperCamelCase ( self ): return len(self.partition_order ) class lowerCAmelCase__ ( datasets.DatasetBuilder ): """simple docstring""" __UpperCAmelCase : Any = SparkConfig def __init__( self , a_ , a_ = None , a_ = None , **a_ , ): import pyspark lowerCamelCase_ : str = pyspark.sql.SparkSession.builder.getOrCreate() lowerCamelCase_ : Optional[Any] = df lowerCamelCase_ : List[Any] = working_dir super().__init__( cache_dir=a_ , config_name=str(self.df.semanticHash() ) , **a_ , ) def _UpperCamelCase ( self ): # Returns the path of the created file. def create_cache_and_write_probe(a_ ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=a_ ) lowerCamelCase_ : Optional[Any] = os.path.join(self._cache_dir , "fs_test" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(a_ , "a" ) return [probe_file] if self._spark.conf.get("spark.master" , "" ).startswith("local" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowerCamelCase_ : List[str] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(a_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir" ) def _UpperCamelCase ( self ): return datasets.DatasetInfo(features=self.config.features ) def _UpperCamelCase ( self , a_ ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def _UpperCamelCase ( self , a_ ): import pyspark def get_arrow_batch_size(a_ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) lowerCamelCase_ : str = self.df.count() lowerCamelCase_ : List[Any] = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowerCamelCase_ : Any = ( self.df.limit(a_ ) .repartition(1 ) .mapInArrow(a_ , "batch_bytes: long" ) .agg(pyspark.sql.functions.sum("batch_bytes" ).alias("sample_bytes" ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowerCamelCase_ : int = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowerCamelCase_ : Union[str, Any] = min(a_ , int(approx_total_size / max_shard_size ) ) lowerCamelCase_ : int = self.df.repartition(a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , ): import pyspark lowerCamelCase_ : str = ParquetWriter if file_format == "parquet" else ArrowWriter lowerCamelCase_ : int = os.path.join(self._working_dir , os.path.basename(a_ ) ) if self._working_dir else fpath lowerCamelCase_ : Optional[Any] = file_format == "parquet" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowerCamelCase_ : int = self.config.features lowerCamelCase_ : Any = self._writer_batch_size lowerCamelCase_ : Tuple = self._fs.storage_options def write_arrow(a_ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowerCamelCase_ : List[Any] = pyspark.TaskContext().taskAttemptId() lowerCamelCase_ : Optional[int] = next(a_ , a_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["task_id", "num_examples", "num_bytes"] , ) lowerCamelCase_ : List[Any] = 0 lowerCamelCase_ : Optional[int] = writer_class( features=a_ , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=a_ , storage_options=a_ , embed_local_files=a_ , ) lowerCamelCase_ : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(a_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowerCamelCase_ ,lowerCamelCase_ : List[str] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) shard_id += 1 lowerCamelCase_ : List[str] = writer_class( features=writer._features , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=a_ , storage_options=a_ , embed_local_files=a_ , ) lowerCamelCase_ : Optional[int] = pa.Table.from_batches([batch] ) writer.write_table(a_ ) if writer._num_bytes > 0: lowerCamelCase_ ,lowerCamelCase_ : Dict = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(a_ ) ): lowerCamelCase_ : str = os.path.join(os.path.dirname(a_ ) , os.path.basename(a_ ) ) shutil.move(a_ , a_ ) lowerCamelCase_ : int = ( self.df.mapInArrow(a_ , "task_id: long, num_examples: long, num_bytes: long" ) .groupBy("task_id" ) .agg( pyspark.sql.functions.sum("num_examples" ).alias("total_num_examples" ) , pyspark.sql.functions.sum("num_bytes" ).alias("total_num_bytes" ) , pyspark.sql.functions.count("num_bytes" ).alias("num_shards" ) , pyspark.sql.functions.collect_list("num_examples" ).alias("shard_lengths" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def _UpperCamelCase ( self , a_ , a_ = "arrow" , a_ = None , a_ = None , **a_ , ): self._validate_cache_dir() lowerCamelCase_ : Union[str, Any] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a_ ) lowerCamelCase_ : Dict = not is_remote_filesystem(self._fs ) lowerCamelCase_ : List[str] = os.path.join if is_local else posixpath.join lowerCamelCase_ : Any = "-TTTTT-SSSSS-of-NNNNN" lowerCamelCase_ : List[Any] = F"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" lowerCamelCase_ : int = path_join(self._output_dir , a_ ) lowerCamelCase_ : int = 0 lowerCamelCase_ : Optional[Any] = 0 lowerCamelCase_ : int = 0 lowerCamelCase_ : Dict = [] lowerCamelCase_ : Any = [] for task_id, content in self._prepare_split_single(a_ , a_ , a_ ): ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) : Tuple = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(a_ ) lowerCamelCase_ : Dict = total_num_examples lowerCamelCase_ : Any = total_num_bytes # should rename everything at the end logger.debug(F"""Renaming {total_shards} shards.""" ) if total_shards > 1: lowerCamelCase_ : List[Any] = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowerCamelCase_ : Any = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a_ , a_ , a_ , ): rename( a_ , fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace("TTTTT-SSSSS" , F"""{global_shard_id:05d}""" ).replace("NNNNN" , F"""{total_shards:05d}""" ) , ) lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : Dict = 0 for i in range(len(a_ ) ): lowerCamelCase_ ,lowerCamelCase_ : Tuple = task_id_and_num_shards[i] for shard_id in range(a_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(a_ , len(a_ ) ).map(lambda a_ : _rename_shard(*a_ ) ).collect() else: # don't use any pattern lowerCamelCase_ : int = 0 lowerCamelCase_ : Optional[int] = task_id_and_num_shards[0][0] self._rename( fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace(a_ , "" ) , ) def _UpperCamelCase ( self , a_ , ): return SparkExamplesIterable(self.df )
73
1
from __future__ import annotations def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : int = 2 lowerCamelCase_ : Any = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(lowerCAmelCase_) if n > 1: factors.append(lowerCAmelCase_) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue lowerCamelCase_ : List[str] = cst_fwd.get(lowerCAmelCase_ , np.inf) lowerCamelCase_ : Dict = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt)) lowerCamelCase_ : Optional[int] = new_cost_f lowerCamelCase_ : List[str] = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: lowerCamelCase_ : Tuple = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Optional[Any] = -1 lowerCamelCase_ : Tuple = set() lowerCamelCase_ : Dict = set() lowerCamelCase_ : int = {source: 0} lowerCamelCase_ : str = {destination: 0} lowerCamelCase_ : Tuple = {source: None} lowerCamelCase_ : Dict = {destination: None} lowerCamelCase_ : PriorityQueue[Any] = PriorityQueue() lowerCamelCase_ : PriorityQueue[Any] = PriorityQueue() lowerCamelCase_ : List[str] = np.inf queue_forward.put((0, source)) queue_backward.put((0, destination)) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): lowerCamelCase_ ,lowerCamelCase_ : List[Any] = queue_forward.get() visited_forward.add(lowerCAmelCase_) lowerCamelCase_ ,lowerCamelCase_ : str = queue_backward.get() visited_backward.add(lowerCAmelCase_) lowerCamelCase_ : Any = pass_and_relaxation( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) lowerCamelCase_ : Dict = pass_and_relaxation( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: lowerCamelCase_ : Union[str, Any] = shortest_distance return shortest_path_distance __magic_name__ = { '''B''': [['''C''', 1]], '''C''': [['''D''', 1]], '''D''': [['''F''', 1]], '''E''': [['''B''', 1], ['''G''', 2]], '''F''': [], '''G''': [['''F''', 1]], } __magic_name__ = { '''B''': [['''E''', 1]], '''C''': [['''B''', 1]], '''D''': [['''C''', 1]], '''F''': [['''D''', 1], ['''G''', 1]], '''E''': [[None, np.inf]], '''G''': [['''E''', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
73
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 DeformableDetrImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , a_ , a_=7 , a_=3 , a_=30 , a_=400 , a_=True , a_=None , a_=True , a_=[0.5, 0.5, 0.5] , a_=[0.5, 0.5, 0.5] , a_=True , a_=1 / 255 , a_=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p lowerCamelCase_ : List[Any] = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} lowerCamelCase_ : Union[str, Any] = parent lowerCamelCase_ : Union[str, Any] = batch_size lowerCamelCase_ : str = num_channels lowerCamelCase_ : str = min_resolution lowerCamelCase_ : Tuple = max_resolution lowerCamelCase_ : List[str] = do_resize lowerCamelCase_ : List[str] = size lowerCamelCase_ : List[str] = do_normalize lowerCamelCase_ : List[Any] = image_mean lowerCamelCase_ : Union[str, Any] = image_std lowerCamelCase_ : Union[str, Any] = do_rescale lowerCamelCase_ : Tuple = rescale_factor lowerCamelCase_ : int = do_pad def _UpperCamelCase ( self ): 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 _UpperCamelCase ( self , a_ , a_=False ): if not batched: lowerCamelCase_ : Optional[Any] = image_inputs[0] if isinstance(a_ , Image.Image ): lowerCamelCase_ ,lowerCamelCase_ : str = image.size else: lowerCamelCase_ ,lowerCamelCase_ : List[Any] = image.shape[1], image.shape[2] if w < h: lowerCamelCase_ : Dict = int(self.size["shortest_edge"] * h / w ) lowerCamelCase_ : Union[str, Any] = self.size["shortest_edge"] elif w > h: lowerCamelCase_ : Dict = self.size["shortest_edge"] lowerCamelCase_ : Union[str, Any] = int(self.size["shortest_edge"] * w / h ) else: lowerCamelCase_ : str = self.size["shortest_edge"] lowerCamelCase_ : Union[str, Any] = self.size["shortest_edge"] else: lowerCamelCase_ : List[Any] = [] for image in image_inputs: lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCamelCase_ : Tuple = max(a_ , key=lambda a_ : item[0] )[0] lowerCamelCase_ : Optional[int] = max(a_ , key=lambda a_ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase__ ( __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Dict = DeformableDetrImageProcessor if is_vision_available() else None def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = DeformableDetrImageProcessingTester(self ) @property def _UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self ): lowerCamelCase_ : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , "image_mean" ) ) self.assertTrue(hasattr(a_ , "image_std" ) ) self.assertTrue(hasattr(a_ , "do_normalize" ) ) self.assertTrue(hasattr(a_ , "do_resize" ) ) self.assertTrue(hasattr(a_ , "do_rescale" ) ) self.assertTrue(hasattr(a_ , "do_pad" ) ) self.assertTrue(hasattr(a_ , "size" ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = 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 , a_ ) lowerCamelCase_ : int = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=a_ ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , a_ ) def _UpperCamelCase ( self ): pass def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input lowerCamelCase_ : Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = self.image_processor_tester.get_expected_values(a_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase_ ,lowerCamelCase_ : int = self.image_processor_tester.get_expected_values(a_ , batched=a_ ) lowerCamelCase_ : Optional[int] = image_processing(a_ , 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 _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) # Test not batched input lowerCamelCase_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCamelCase_ ,lowerCamelCase_ : List[Any] = self.image_processor_tester.get_expected_values(a_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase_ : int = image_processing(a_ , return_tensors="pt" ).pixel_values lowerCamelCase_ ,lowerCamelCase_ : Dict = self.image_processor_tester.get_expected_values(a_ , batched=a_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input lowerCamelCase_ : Any = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = self.image_processor_tester.get_expected_values(a_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase_ : Union[str, Any] = image_processing(a_ , return_tensors="pt" ).pixel_values lowerCamelCase_ ,lowerCamelCase_ : Dict = self.image_processor_tester.get_expected_values(a_ , batched=a_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _UpperCamelCase ( self ): # prepare image and target lowerCamelCase_ : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: lowerCamelCase_ : Optional[int] = json.loads(f.read() ) lowerCamelCase_ : int = {"image_id": 3_9769, "annotations": target} # encode them lowerCamelCase_ : Optional[int] = DeformableDetrImageProcessor() lowerCamelCase_ : Optional[Any] = image_processing(images=a_ , annotations=a_ , return_tensors="pt" ) # verify pixel values lowerCamelCase_ : Dict = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , a_ ) lowerCamelCase_ : Dict = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , a_ , atol=1E-4 ) ) # verify area lowerCamelCase_ : List[Any] = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , a_ ) ) # verify boxes lowerCamelCase_ : Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , a_ ) lowerCamelCase_ : Any = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , a_ , atol=1E-3 ) ) # verify image_id lowerCamelCase_ : int = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , a_ ) ) # verify is_crowd lowerCamelCase_ : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , a_ ) ) # verify class_labels lowerCamelCase_ : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , a_ ) ) # verify orig_size lowerCamelCase_ : Union[str, Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , a_ ) ) # verify size lowerCamelCase_ : Optional[int] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , a_ ) ) @slow def _UpperCamelCase ( self ): # prepare image, target and masks_path lowerCamelCase_ : 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: lowerCamelCase_ : Optional[Any] = json.loads(f.read() ) lowerCamelCase_ : Optional[Any] = {"file_name": "000000039769.png", "image_id": 3_9769, "segments_info": target} lowerCamelCase_ : int = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them lowerCamelCase_ : Tuple = DeformableDetrImageProcessor(format="coco_panoptic" ) lowerCamelCase_ : Optional[int] = image_processing(images=a_ , annotations=a_ , masks_path=a_ , return_tensors="pt" ) # verify pixel values lowerCamelCase_ : str = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , a_ ) lowerCamelCase_ : Dict = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , a_ , atol=1E-4 ) ) # verify area lowerCamelCase_ : Optional[Any] = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , a_ ) ) # verify boxes lowerCamelCase_ : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , a_ ) lowerCamelCase_ : List[str] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , a_ , atol=1E-3 ) ) # verify image_id lowerCamelCase_ : Optional[Any] = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , a_ ) ) # verify is_crowd lowerCamelCase_ : int = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , a_ ) ) # verify class_labels lowerCamelCase_ : Any = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , a_ ) ) # verify masks lowerCamelCase_ : List[str] = 82_2873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , a_ ) # verify orig_size lowerCamelCase_ : Tuple = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , a_ ) ) # verify size lowerCamelCase_ : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , a_ ) )
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''ctrl''' __UpperCAmelCase : Dict = ['''past_key_values'''] __UpperCAmelCase : int = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a_=24_6534 , a_=256 , a_=1280 , a_=8192 , a_=48 , a_=16 , a_=0.1 , a_=0.1 , a_=1E-6 , a_=0.02 , a_=True , **a_ , ): lowerCamelCase_ : Dict = vocab_size lowerCamelCase_ : Any = n_positions lowerCamelCase_ : Optional[int] = n_embd lowerCamelCase_ : List[Any] = n_layer lowerCamelCase_ : Union[str, Any] = n_head lowerCamelCase_ : str = dff lowerCamelCase_ : Tuple = resid_pdrop lowerCamelCase_ : Any = embd_pdrop lowerCamelCase_ : Dict = layer_norm_epsilon lowerCamelCase_ : Tuple = initializer_range lowerCamelCase_ : Any = use_cache super().__init__(**a_ )
73
1
def __magic_name__ ( ): '''simple docstring''' return [ a * b * (1000 - a - b) for a in range(1 , 999) for b in range(lowerCAmelCase_ , 999) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(f'''{solution() = }''')
73
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __magic_name__ = logging.getLogger(__name__) __magic_name__ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __magic_name__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) }, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(__lowerCamelCase )}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) }, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''}, ) __UpperCAmelCase : str = field( default='''main''', metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) }, ) def _UpperCamelCase ( self ): if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can't be used in combination with --config_name or --model_name_or_path" ) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field(default=__lowerCamelCase, metadata={'''help''': '''The input training data file (a text file).'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) __UpperCAmelCase : Optional[int] = field( default=5, metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' }, ) __UpperCAmelCase : Optional[int] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) }, ) __UpperCAmelCase : Optional[int] = field( default=__lowerCamelCase, metadata={'''help''': '''The number of processes to use for the preprocessing.'''}, ) __UpperCAmelCase : float = field( default=0.15, metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) }, ) def _UpperCamelCase ( self ): if self.train_file is not None: lowerCamelCase_ : str = self.train_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: lowerCamelCase_ : Union[str, Any] = self.validation_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' with open(lowerCAmelCase_ , "r" , encoding="utf-8") as f: lowerCamelCase_ : Tuple = [json.loads(lowerCAmelCase_) for line in f.read().splitlines() if (len(lowerCAmelCase_) > 0 and not line.isspace())] assert len(lowerCAmelCase_) == len(lowerCAmelCase_) lowerCamelCase_ : Any = {c: dataset[c] for c in dataset.column_names} lowerCamelCase_ : List[Any] = refs return Dataset.from_dict(lowerCAmelCase_) def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowerCamelCase_ : List[str] = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: lowerCamelCase_ : Dict = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome.") elif last_checkpoint is not None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch.") # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}""") # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowerCamelCase_ : Optional[int] = load_dataset(data_args.dataset_name , data_args.dataset_config_name) if "validation" not in datasets.keys(): lowerCamelCase_ : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[:{data_args.validation_split_percentage}%]""" , ) lowerCamelCase_ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[{data_args.validation_split_percentage}%:]""" , ) else: lowerCamelCase_ : Dict = {} if data_args.train_file is not None: lowerCamelCase_ : str = data_args.train_file if data_args.validation_file is not None: lowerCamelCase_ : Any = data_args.validation_file lowerCamelCase_ : Any = data_args.train_file.split(".")[-1] if extension == "txt": lowerCamelCase_ : List[str] = "text" lowerCamelCase_ : Dict = load_dataset(lowerCAmelCase_ , data_files=lowerCAmelCase_) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase_ : Optional[Any] = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: lowerCamelCase_ : Optional[Any] = AutoConfig.from_pretrained(model_args.config_name , **lowerCAmelCase_) elif model_args.model_name_or_path: lowerCamelCase_ : str = AutoConfig.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase_) else: lowerCamelCase_ : Optional[int] = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch.") if model_args.config_overrides is not None: logger.info(F"""Overriding config: {model_args.config_overrides}""") config.update_from_string(model_args.config_overrides) logger.info(F"""New config: {config}""") lowerCamelCase_ : List[str] = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: lowerCamelCase_ : str = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **lowerCAmelCase_) elif model_args.model_name_or_path: lowerCamelCase_ : Dict = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase_) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name.") if model_args.model_name_or_path: lowerCamelCase_ : Union[str, Any] = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch") lowerCamelCase_ : Dict = AutoModelForMaskedLM.from_config(lowerCAmelCase_) model.resize_token_embeddings(len(lowerCAmelCase_)) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: lowerCamelCase_ : Optional[Any] = datasets["train"].column_names else: lowerCamelCase_ : Dict = datasets["validation"].column_names lowerCamelCase_ : Union[str, Any] = "text" if "text" in column_names else column_names[0] lowerCamelCase_ : Optional[Any] = "max_length" if data_args.pad_to_max_length else False def tokenize_function(lowerCAmelCase_): # Remove empty lines lowerCamelCase_ : str = [line for line in examples["text"] if len(lowerCAmelCase_) > 0 and not line.isspace()] return tokenizer(examples["text"] , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=data_args.max_seq_length) lowerCamelCase_ : str = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: lowerCamelCase_ : List[Any] = add_chinese_references(tokenized_datasets["train"] , data_args.train_ref_file) if data_args.validation_ref_file is not None: lowerCamelCase_ : List[str] = add_chinese_references( tokenized_datasets["validation"] , data_args.validation_ref_file) # If we have ref files, need to avoid it removed by trainer lowerCamelCase_ : Optional[Any] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: lowerCamelCase_ : Union[str, Any] = False # Data collator # This one will take care of randomly masking the tokens. lowerCamelCase_ : Optional[Any] = DataCollatorForWholeWordMask(tokenizer=lowerCAmelCase_ , mlm_probability=data_args.mlm_probability) # Initialize our Trainer lowerCamelCase_ : int = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=tokenized_datasets["train"] if training_args.do_train else None , eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: if last_checkpoint is not None: lowerCamelCase_ : Dict = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path): lowerCamelCase_ : Dict = model_args.model_name_or_path else: lowerCamelCase_ : int = None lowerCamelCase_ : Optional[Any] = trainer.train(resume_from_checkpoint=lowerCAmelCase_) trainer.save_model() # Saves the tokenizer too for easy upload lowerCamelCase_ : Tuple = os.path.join(training_args.output_dir , "train_results.txt") if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w") as writer: logger.info("***** Train results *****") for key, value in sorted(train_result.metrics.items()): logger.info(F""" {key} = {value}""") writer.write(F"""{key} = {value}\n""") # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json")) # Evaluation lowerCamelCase_ : Dict = {} if training_args.do_eval: logger.info("*** Evaluate ***") lowerCamelCase_ : Tuple = trainer.evaluate() lowerCamelCase_ : str = math.exp(eval_output["eval_loss"]) lowerCamelCase_ : Tuple = perplexity lowerCamelCase_ : int = os.path.join(training_args.output_dir , "eval_results_mlm_wwm.txt") if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w") as writer: logger.info("***** Eval results *****") for key, value in sorted(results.items()): logger.info(F""" {key} = {value}""") writer.write(F"""{key} = {value}\n""") return results def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' main() if __name__ == "__main__": main()
73
1
import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('''3.8'''): import importlib_metadata else: import importlib.metadata as importlib_metadata def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_=False): '''simple docstring''' try: lowerCamelCase_ : Any = os.environ[key] except KeyError: # KEY isn't set, default to `default`. lowerCamelCase_ : int = default else: # KEY is set, convert it to True or False. try: lowerCamelCase_ : str = strtobool(lowerCAmelCase_) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F"""If set, {key} must be yes or no.""") return _value __magic_name__ = parse_flag_from_env('''RUN_SLOW''', default=False) __magic_name__ = parse_flag_from_env('''RUN_REMOTE''', default=False) __magic_name__ = parse_flag_from_env('''RUN_LOCAL''', default=True) __magic_name__ = parse_flag_from_env('''RUN_PACKAGED''', default=True) # Compression __magic_name__ = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''') __magic_name__ = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''') __magic_name__ = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''') # Audio __magic_name__ = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''), reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''', ) # Beam __magic_name__ = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''), reason='''test requires apache-beam and a compatible dill version''', ) # Dill-cloudpickle compatibility __magic_name__ = pytest.mark.skipif( config.DILL_VERSION <= version.parse('''0.3.2'''), reason='''test requires dill>0.3.2 for cloudpickle compatibility''', ) # Windows __magic_name__ = pytest.mark.skipif( sys.platform == '''win32''', reason='''test should not be run on Windows''', ) def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import faiss # noqa except ImportError: lowerCamelCase_ : List[Any] = unittest.skip("test requires faiss")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import regex # noqa except ImportError: lowerCamelCase_ : List[Any] = unittest.skip("test requires regex")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import elasticsearch # noqa except ImportError: lowerCamelCase_ : List[str] = unittest.skip("test requires elasticsearch")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import sqlalchemy # noqa except ImportError: lowerCamelCase_ : List[Any] = unittest.skip("test requires sqlalchemy")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not config.TORCH_AVAILABLE: lowerCamelCase_ : int = unittest.skip("test requires PyTorch")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not config.TF_AVAILABLE: lowerCamelCase_ : Optional[int] = unittest.skip("test requires TensorFlow")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not config.JAX_AVAILABLE: lowerCamelCase_ : Union[str, Any] = unittest.skip("test requires JAX")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not config.PIL_AVAILABLE: lowerCamelCase_ : List[Any] = unittest.skip("test requires Pillow")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import transformers # noqa F401 except ImportError: return unittest.skip("test requires transformers")(lowerCAmelCase_) else: return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import tiktoken # noqa F401 except ImportError: return unittest.skip("test requires tiktoken")(lowerCAmelCase_) else: return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import spacy # noqa F401 except ImportError: return unittest.skip("test requires spacy")(lowerCAmelCase_) else: return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' def _require_spacy_model(lowerCAmelCase_): try: import spacy # noqa F401 spacy.load(lowerCAmelCase_) except ImportError: return unittest.skip("test requires spacy")(lowerCAmelCase_) except OSError: return unittest.skip("test requires spacy model '{}'".format(lowerCAmelCase_))(lowerCAmelCase_) else: return test_case return _require_spacy_model def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import pyspark # noqa F401 except ImportError: return unittest.skip("test requires pyspark")(lowerCAmelCase_) else: return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' try: import joblibspark # noqa F401 except ImportError: return unittest.skip("test requires joblibspark")(lowerCAmelCase_) else: return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not _run_slow_tests or _run_slow_tests == 0: lowerCamelCase_ : Union[str, Any] = unittest.skip("test is slow")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not _run_local_tests or _run_local_tests == 0: lowerCamelCase_ : int = unittest.skip("test is local")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not _run_packaged_tests or _run_packaged_tests == 0: lowerCamelCase_ : Tuple = unittest.skip("test is packaged")(lowerCAmelCase_) return test_case def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not _run_remote_tests or _run_remote_tests == 0: lowerCamelCase_ : List[str] = unittest.skip("test requires remote")(lowerCAmelCase_) return test_case def __magic_name__ ( *lowerCAmelCase_): '''simple docstring''' def decorate(cls): for name, fn in cls.__dict__.items(): if callable(lowerCAmelCase_) and name.startswith("test"): for decorator in decorators: lowerCamelCase_ : Dict = decorator(lowerCAmelCase_) setattr(cls , lowerCAmelCase_ , lowerCAmelCase_) return cls return decorate class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" pass class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[str] = 0 __UpperCAmelCase : List[str] = 1 __UpperCAmelCase : List[Any] = 2 @contextmanager def __magic_name__ ( lowerCAmelCase_=OfflineSimulationMode.CONNECTION_FAILS , lowerCAmelCase_=1E-16): '''simple docstring''' lowerCamelCase_ : Optional[Any] = requests.Session().request def timeout_request(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_): # Change the url to an invalid url so that the connection hangs lowerCamelCase_ : Optional[Any] = "https://10.255.255.1" if kwargs.get("timeout") is None: raise RequestWouldHangIndefinitelyError( F"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout.""") lowerCamelCase_ : Dict = timeout try: return online_request(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier lowerCamelCase_ : str = url lowerCamelCase_ : Dict = e.args[0] lowerCamelCase_ : Dict = (max_retry_error.args[0].replace("10.255.255.1" , F"""OfflineMock[{url}]"""),) lowerCamelCase_ : Tuple = (max_retry_error,) raise def raise_connection_error(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_): raise requests.ConnectionError("Offline mode is enabled." , request=lowerCAmelCase_) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("requests.Session.send" , lowerCAmelCase_): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("requests.Session.request" , lowerCAmelCase_): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("datasets.config.HF_DATASETS_OFFLINE" , lowerCAmelCase_): yield else: raise ValueError("Please use a value from the OfflineSimulationMode enum.") @contextmanager def __magic_name__ ( *lowerCAmelCase_ , **lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : List[Any] = str(Path().resolve()) with tempfile.TemporaryDirectory(*lowerCAmelCase_ , **lowerCAmelCase_) as tmp_dir: try: os.chdir(lowerCAmelCase_) yield finally: os.chdir(lowerCAmelCase_) @contextmanager def __magic_name__ ( ): '''simple docstring''' import gc gc.collect() lowerCamelCase_ : Optional[Any] = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def __magic_name__ ( ): '''simple docstring''' import gc gc.collect() lowerCamelCase_ : Any = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' return deepcopy(lowerCAmelCase_).integers(0 , 100 , 10).tolist() == deepcopy(lowerCAmelCase_).integers(0 , 100 , 10).tolist() def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' import decorator from requests.exceptions import HTTPError def _wrapper(lowerCAmelCase_ , *lowerCAmelCase_ , **lowerCAmelCase_): try: return func(*lowerCAmelCase_ , **lowerCAmelCase_) except HTTPError as err: if str(lowerCAmelCase_).startswith("500") or str(lowerCAmelCase_).startswith("502"): pytest.xfail(str(lowerCAmelCase_)) raise err return decorator.decorator(_wrapper , lowerCAmelCase_) class lowerCAmelCase__ : """simple docstring""" def __init__( self , a_ , a_ , a_ ): lowerCamelCase_ : List[str] = returncode lowerCamelCase_ : Dict = stdout lowerCamelCase_ : int = stderr async def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' while True: lowerCamelCase_ : List[Any] = await stream.readline() if line: callback(lowerCAmelCase_) else: break async def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False): '''simple docstring''' if echo: print("\nRunning: " , " ".join(lowerCAmelCase_)) lowerCamelCase_ : str = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=lowerCAmelCase_ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowerCAmelCase_ , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) lowerCamelCase_ : str = [] lowerCamelCase_ : Tuple = [] def tee(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=""): lowerCamelCase_ : Union[str, Any] = line.decode("utf-8").rstrip() sink.append(lowerCAmelCase_) if not quiet: print(lowerCAmelCase_ , lowerCAmelCase_ , file=lowerCAmelCase_) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout , lambda lowerCAmelCase_: tee(lowerCAmelCase_ , lowerCAmelCase_ , sys.stdout , label="stdout:")), _read_stream(p.stderr , lambda lowerCAmelCase_: tee(lowerCAmelCase_ , lowerCAmelCase_ , sys.stderr , label="stderr:")), ] , timeout=lowerCAmelCase_ , ) return _RunOutput(await p.wait() , lowerCAmelCase_ , lowerCAmelCase_) def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=180 , lowerCAmelCase_=False , lowerCAmelCase_=True): '''simple docstring''' lowerCamelCase_ : List[Any] = asyncio.get_event_loop() lowerCamelCase_ : List[str] = loop.run_until_complete( _stream_subprocess(lowerCAmelCase_ , env=lowerCAmelCase_ , stdin=lowerCAmelCase_ , timeout=lowerCAmelCase_ , quiet=lowerCAmelCase_ , echo=lowerCAmelCase_)) lowerCamelCase_ : int = " ".join(lowerCAmelCase_) if result.returncode > 0: lowerCamelCase_ : Any = "\n".join(result.stderr) raise RuntimeError( F"""'{cmd_str}' failed with returncode {result.returncode}\n\n""" F"""The combined stderr from workers follows:\n{stderr}""") # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(F"""'{cmd_str}' produced no output.""") return result def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : int = os.environ.get("PYTEST_XDIST_WORKER" , "gw0") lowerCamelCase_ : Dict = re.sub(R"^gw" , "" , lowerCAmelCase_ , 0 , re.M) return int(lowerCAmelCase_) def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Optional[Any] = 2_9500 lowerCamelCase_ : Optional[Any] = pytest_xdist_worker_id() return port + uniq_delta
73
from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class lowerCAmelCase__ : """simple docstring""" # setable values __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[jnp.ndarray] = None __UpperCAmelCase : Optional[jnp.ndarray] = None # sigma(t_i) @classmethod def _UpperCamelCase ( cls ): return cls() @dataclass class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : KarrasVeSchedulerState class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase ): """simple docstring""" @property def _UpperCamelCase ( self ): return True @register_to_config def __init__( self , a_ = 0.02 , a_ = 100 , a_ = 1.0_07 , a_ = 80 , a_ = 0.05 , a_ = 50 , ): pass def _UpperCamelCase ( self ): return KarrasVeSchedulerState.create() def _UpperCamelCase ( self , a_ , a_ , a_ = () ): lowerCamelCase_ : List[Any] = jnp.arange(0 , a_ )[::-1].copy() lowerCamelCase_ : List[str] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=a_ , schedule=jnp.array(a_ , dtype=jnp.floataa ) , timesteps=a_ , ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , ): if self.config.s_min <= sigma <= self.config.s_max: lowerCamelCase_ : Union[str, Any] = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: lowerCamelCase_ : Optional[int] = 0 # sample eps ~ N(0, S_noise^2 * I) lowerCamelCase_ : Union[str, Any] = random.split(a_ , num=1 ) lowerCamelCase_ : str = self.config.s_noise * random.normal(key=a_ , shape=sample.shape ) lowerCamelCase_ : List[str] = sigma + gamma * sigma lowerCamelCase_ : Tuple = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ = True , ): lowerCamelCase_ : List[str] = sample_hat + sigma_hat * model_output lowerCamelCase_ : Union[str, Any] = (sample_hat - pred_original_sample) / sigma_hat lowerCamelCase_ : Union[str, Any] = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=a_ , derivative=a_ , state=a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ = True , ): lowerCamelCase_ : Optional[Any] = sample_prev + sigma_prev * model_output lowerCamelCase_ : Any = (sample_prev - pred_original_sample) / sigma_prev lowerCamelCase_ : Optional[int] = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=a_ , derivative=a_ , state=a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ ): raise NotImplementedError()
73
1
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class lowerCAmelCase__ ( unittest.TestCase, __lowerCamelCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : Any = load_tool("text-classification" ) self.tool.setup() lowerCamelCase_ : Dict = load_tool("text-classification" , remote=a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a_ , "positive" ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(a_ , "positive" ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a_ , "positive" ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(a_ , "positive" )
73
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = StableDiffusionDiffEditPipeline __UpperCAmelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} __UpperCAmelCase : Any = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} __UpperCAmelCase : List[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __UpperCAmelCase : List[str] = frozenset([] ) def _UpperCamelCase ( self ): torch.manual_seed(0 ) lowerCamelCase_ : str = 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 , attention_head_dim=(2, 4) , use_linear_projection=a_ , ) lowerCamelCase_ : str = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , ) lowerCamelCase_ : Dict = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_zero=a_ , ) torch.manual_seed(0 ) lowerCamelCase_ : List[Any] = 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 ) lowerCamelCase_ : Union[str, 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 , ) lowerCamelCase_ : Optional[Any] = CLIPTextModel(a_ ) lowerCamelCase_ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCamelCase_ : Optional[Any] = { "unet": unet, "scheduler": scheduler, "inverse_scheduler": inverse_scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : str = floats_tensor((1, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : List[Any] = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : List[Any] = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[str] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Tuple = { "prompt": "a dog and a newt", "mask_image": mask, "image_latents": latents, "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Any = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Tuple = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : int = { "image": image, "source_prompt": "a cat and a frog", "target_prompt": "a dog and a newt", "generator": generator, "num_inference_steps": 2, "num_maps_per_mask": 2, "mask_encode_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Optional[int] = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Optional[int] = torch.manual_seed(a_ ) else: lowerCamelCase_ : Tuple = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Union[str, Any] = { "image": image, "prompt": "a cat and a frog", "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "decode_latents": True, "output_type": "numpy", } return inputs def _UpperCamelCase ( self ): if not hasattr(self.pipeline_class , "_optional_components" ): return lowerCamelCase_ : List[Any] = self.get_dummy_components() lowerCamelCase_ : int = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a_ , a_ , a_ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) lowerCamelCase_ : int = self.get_dummy_inputs(a_ ) lowerCamelCase_ : int = pipe(**a_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a_ ) lowerCamelCase_ : Optional[int] = self.pipeline_class.from_pretrained(a_ ) pipe_loaded.to(a_ ) pipe_loaded.set_progress_bar_config(disable=a_ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(a_ , a_ ) is None , F"""`{optional_component}` did not stay set to None after loading.""" , ) lowerCamelCase_ : List[str] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Optional[int] = pipe_loaded(**a_ )[0] lowerCamelCase_ : Optional[int] = np.abs(output - output_loaded ).max() self.assertLess(a_ , 1E-4 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : List[Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = self.get_dummy_mask_inputs(a_ ) lowerCamelCase_ : int = pipe.generate_mask(**a_ ) lowerCamelCase_ : List[Any] = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) lowerCamelCase_ : List[str] = np.array([0] * 9 ) lowerCamelCase_ : Optional[int] = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : Union[str, Any] = self.get_dummy_components() lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Dict = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : Dict = pipe.invert(**a_ ).images lowerCamelCase_ : str = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Dict = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : Any = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) def _UpperCamelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : int = {"beta_start": 0.0_00_85, "beta_end": 0.0_12, "beta_schedule": "scaled_linear"} lowerCamelCase_ : Optional[Any] = DPMSolverMultistepScheduler(**a_ ) lowerCamelCase_ : List[str] = DPMSolverMultistepInverseScheduler(**a_ ) lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : int = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : str = pipe.invert(**a_ ).images lowerCamelCase_ : int = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Union[str, Any] = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def _UpperCamelCase ( cls ): lowerCamelCase_ : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png" ) lowerCamelCase_ : int = raw_image.convert("RGB" ).resize((768, 768) ) lowerCamelCase_ : List[Any] = raw_image def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = torch.manual_seed(0 ) lowerCamelCase_ : Tuple = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : str = DDIMScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : Optional[int] = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : str = "a bowl of fruit" lowerCamelCase_ : Optional[int] = "a bowl of pears" lowerCamelCase_ : List[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ ).latents lowerCamelCase_ : List[str] = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = torch.manual_seed(0 ) lowerCamelCase_ : str = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : str = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = "a bowl of fruit" lowerCamelCase_ : Dict = "a bowl of pears" lowerCamelCase_ : Optional[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ , num_inference_steps=25 , ).latents lowerCamelCase_ : Any = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , num_inference_steps=25 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
73
1
import math import os import sys def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Optional[int] = "" try: with open(lowerCAmelCase_ , "rb") as binary_file: lowerCamelCase_ : Any = binary_file.read() for dat in data: lowerCamelCase_ : Tuple = F"""{dat:08b}""" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lexicon.pop(lowerCAmelCase_) lowerCamelCase_ : int = last_match_id if math.loga(lowerCAmelCase_).is_integer(): for curr_key in lexicon: lowerCamelCase_ : Optional[int] = "0" + lexicon[curr_key] lowerCamelCase_ : int = bin(lowerCAmelCase_)[2:] def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Dict = {"0": "0", "1": "1"} lowerCamelCase_ ,lowerCamelCase_ : Dict = "", "" lowerCamelCase_ : Tuple = len(lowerCAmelCase_) for i in range(len(lowerCAmelCase_)): curr_string += data_bits[i] if curr_string not in lexicon: continue lowerCamelCase_ : Union[str, Any] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) index += 1 lowerCamelCase_ : Tuple = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": lowerCamelCase_ : Optional[int] = lexicon[curr_string] result += last_match_id return result def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : List[Any] = os.path.getsize(lowerCAmelCase_) lowerCamelCase_ : Dict = bin(lowerCAmelCase_)[2:] lowerCamelCase_ : int = len(lowerCAmelCase_) return "0" * (length_length - 1) + file_length_binary + compressed def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Any = 8 try: with open(lowerCAmelCase_ , "wb") as opened_file: lowerCamelCase_ : int = [ to_write[i : i + byte_length] for i in range(0 , len(lowerCAmelCase_) , lowerCAmelCase_) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(lowerCAmelCase_ , 2).to_bytes(1 , byteorder="big")) except OSError: print("File not accessible") sys.exit() def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : List[str] = read_file_binary(lowerCAmelCase_) lowerCamelCase_ : str = compress_data(lowerCAmelCase_) lowerCamelCase_ : Tuple = add_file_length(lowerCAmelCase_ , lowerCAmelCase_) write_file_binary(lowerCAmelCase_ , lowerCAmelCase_) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : int = ["a", "b", "c"] # Defaults to last layer if both are None lowerCamelCase_ ,lowerCamelCase_ : Tuple = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ["c"] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = get_aligned_output_features_output_indices(["a", "c"] , a_ , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices lowerCamelCase_ ,lowerCamelCase_ : Tuple = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices lowerCamelCase_ ,lowerCamelCase_ : Dict = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [-3, -1] ) def _UpperCamelCase ( self ): # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = BackboneMixin() lowerCamelCase_ : List[Any] = ["a", "b", "c"] lowerCamelCase_ : Optional[int] = ["a", "c"] lowerCamelCase_ : Dict = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly lowerCamelCase_ : Union[str, Any] = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) lowerCamelCase_ : str = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
73
1
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def __magic_name__ ( *lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_=True , lowerCAmelCase_=2): '''simple docstring''' from .. import __version__ lowerCamelCase_ : Dict = take_from lowerCamelCase_ : Tuple = () if not isinstance(args[0] , lowerCAmelCase_): lowerCamelCase_ : Optional[int] = (args,) for attribute, version_name, message in args: if version.parse(version.parse(lowerCAmelCase_).base_version) >= version.parse(lowerCAmelCase_): raise ValueError( F"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" F""" version {__version__} is >= {version_name}""") lowerCamelCase_ : int = None if isinstance(lowerCAmelCase_ , lowerCAmelCase_) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowerCAmelCase_),) lowerCamelCase_ : Tuple = F"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(lowerCAmelCase_ , lowerCAmelCase_): values += (getattr(lowerCAmelCase_ , lowerCAmelCase_),) lowerCamelCase_ : Dict = F"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: lowerCamelCase_ : str = F"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: lowerCamelCase_ : Tuple = warning + " " if standard_warn else "" warnings.warn(warning + message , lowerCAmelCase_ , stacklevel=lowerCAmelCase_) if isinstance(lowerCAmelCase_ , lowerCAmelCase_) and len(lowerCAmelCase_) > 0: lowerCamelCase_ : str = inspect.getouterframes(inspect.currentframe())[1] lowerCamelCase_ : Optional[int] = call_frame.filename lowerCamelCase_ : Dict = call_frame.lineno lowerCamelCase_ : Optional[int] = call_frame.function lowerCamelCase_ ,lowerCamelCase_ : Any = next(iter(deprecated_kwargs.items())) raise TypeError(F"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""") if len(lowerCAmelCase_) == 0: return elif len(lowerCAmelCase_) == 1: return values[0] return values
73
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : Union[str, Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Tuple = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : int = '''default_config.yaml''' __UpperCAmelCase : Tuple = config_folder / config_file __UpperCAmelCase : int = config_folder / '''_default_config.yaml''' __UpperCAmelCase : int = Path('''tests/test_configs''' ) @classmethod def _UpperCamelCase ( cls ): if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def _UpperCamelCase ( cls ): if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def _UpperCamelCase ( self ): for config in sorted(self.test_config_path.glob("**/*.yaml" ) ): with self.subTest(config_file=a_ ): execute_subprocess_async( self.base_cmd + ["--config_file", str(a_ ), self.test_file_path] , env=os.environ.copy() ) def _UpperCamelCase ( self ): execute_subprocess_async(["accelerate", "test"] , env=os.environ.copy() ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[Any] = '''test-tpu''' __UpperCAmelCase : Tuple = '''us-central1-a''' __UpperCAmelCase : Tuple = '''ls''' __UpperCAmelCase : str = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : Dict = '''Running gcloud compute tpus tpu-vm ssh''' def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + ["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--debug"] , return_stdout=a_ ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--command", "echo \"Hello World\"", "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command_file", self.command_file, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--accelerate_version", "12.0.0", "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , )
73
1
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): # A mock response for an HTTP head request to emulate server down lowerCamelCase_ : Optional[int] = mock.Mock() lowerCamelCase_ : Union[str, Any] = 500 lowerCamelCase_ : str = {} lowerCamelCase_ : List[str] = HTTPError lowerCamelCase_ : Optional[Any] = {} # Download this model to make sure it's in the cache. lowerCamelCase_ : List[str] = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head: lowerCamelCase_ : Optional[Any] = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _UpperCamelCase ( self ): # A mock response for an HTTP head request to emulate server down lowerCamelCase_ : Union[str, Any] = mock.Mock() lowerCamelCase_ : Any = 500 lowerCamelCase_ : int = {} lowerCamelCase_ : int = HTTPError lowerCamelCase_ : Any = {} # Download this model to make sure it's in the cache. lowerCamelCase_ : List[str] = GPTaTokenizerFast.from_pretrained("gpt2" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head: lowerCamelCase_ : Optional[int] = GPTaTokenizerFast.from_pretrained("gpt2" ) # This check we did call the fake head request mock_head.assert_called() def _UpperCamelCase ( self ): # This test is for deprecated behavior and can be removed in v5 try: lowerCamelCase_ : Union[str, Any] = tempfile.mktemp() with open(a_ , "wb" ) as f: http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ ) lowerCamelCase_ : Dict = AlbertTokenizer.from_pretrained(a_ ) finally: os.remove(a_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile("tokenizer.json" ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open("tokenizer.json" , "wb" ) as f: http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ ) lowerCamelCase_ : Tuple = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove("tokenizer.json" ) def _UpperCamelCase ( self ): # This test is for deprecated behavior and can be removed in v5 lowerCamelCase_ : Tuple = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" ) @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def _UpperCamelCase ( cls ): lowerCamelCase_ : Tuple = TOKEN HfFolder.save_token(a_ ) @classmethod def _UpperCamelCase ( cls ): try: delete_repo(token=cls._token , repo_id="test-tokenizer" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" ) except HTTPError: pass def _UpperCamelCase ( self ): with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ : int = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) lowerCamelCase_ : str = BertTokenizer(a_ ) tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token ) lowerCamelCase_ : List[Any] = BertTokenizer.from_pretrained(F"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="test-tokenizer" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token ) lowerCamelCase_ : str = BertTokenizer.from_pretrained(F"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def _UpperCamelCase ( self ): with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ : List[Any] = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) lowerCamelCase_ : Any = BertTokenizer(a_ ) tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token ) lowerCamelCase_ : Dict = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token ) lowerCamelCase_ : int = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def _UpperCamelCase ( self ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ : Optional[int] = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) lowerCamelCase_ : Tuple = CustomTokenizer(a_ ) # No fast custom tokenizer tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) lowerCamelCase_ : int = AutoTokenizer.from_pretrained(F"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ : Optional[Any] = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) lowerCamelCase_ : List[Any] = BertTokenizerFast.from_pretrained(a_ ) bert_tokenizer.save_pretrained(a_ ) lowerCamelCase_ : List[str] = CustomTokenizerFast.from_pretrained(a_ ) tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) lowerCamelCase_ : Dict = AutoTokenizer.from_pretrained(F"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" ) lowerCamelCase_ : Dict = AutoTokenizer.from_pretrained( F"""{USER}/test-dynamic-tokenizer""" , use_fast=a_ , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = Trie() trie.add("Hello 友達" ) self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} ) trie.add("Hello" ) trie.data self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} ) def _UpperCamelCase ( self ): lowerCamelCase_ : int = Trie() self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] ) trie.add("[CLS]" ) trie.add("extra_id_1" ) trie.add("extra_id_100" ) self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = Trie() trie.add("A" ) self.assertEqual(trie.split("ABC" ) , ["A", "BC"] ) self.assertEqual(trie.split("BCA" ) , ["BC", "A"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = Trie() trie.add("TOKEN]" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = Trie() trie.add("A" ) trie.add("P" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = Trie() trie.add("AB" ) trie.add("B" ) trie.add("C" ) self.assertEqual(trie.split("ABC" ) , ["AB", "C"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = Trie() trie.add("ABC" ) trie.add("B" ) trie.add("CD" ) self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] ) def _UpperCamelCase ( self ): # Even if the offsets are wrong, we necessarily output correct string # parts. lowerCamelCase_ : Dict = Trie() lowerCamelCase_ : str = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] ) self.assertEqual(a_ , ["AB", "C"] )
73
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ , a_ ): super().__init__() self.register_modules(vqvae=a_ , unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self , a_ = 1 , a_ = None , a_ = 0.0 , a_ = 50 , a_ = "pil" , a_ = True , **a_ , ): lowerCamelCase_ : Optional[Any] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=a_ , ) lowerCamelCase_ : Optional[int] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ : Optional[int] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(a_ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature lowerCamelCase_ : Any = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ : Optional[int] = {} if accepts_eta: lowerCamelCase_ : Optional[int] = eta for t in self.progress_bar(self.scheduler.timesteps ): lowerCamelCase_ : Dict = self.scheduler.scale_model_input(a_ , a_ ) # predict the noise residual lowerCamelCase_ : Optional[Any] = self.unet(a_ , a_ ).sample # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ : List[Any] = self.scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample # decode the image latents with the VAE lowerCamelCase_ : str = self.vqvae.decode(a_ ).sample lowerCamelCase_ : Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) lowerCamelCase_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase_ : Optional[Any] = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
73
1
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowerCAmelCase__ ( __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[Any] = BertTokenizer __UpperCAmelCase : Dict = BertTokenizerFast __UpperCAmelCase : Tuple = True __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : Optional[int] = filter_non_english def _UpperCamelCase ( self ): super().setUp() lowerCamelCase_ : Optional[Any] = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] lowerCamelCase_ : Tuple = 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 _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Optional[Any] = "UNwant\u00E9d,running" lowerCamelCase_ : Optional[int] = "unwanted, running" return input_text, output_text def _UpperCamelCase ( self ): lowerCamelCase_ : Any = self.tokenizer_class(self.vocab_file ) lowerCamelCase_ : Union[str, Any] = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(a_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [9, 6, 7, 12, 10, 11] ) def _UpperCamelCase ( self ): if not self.test_rust_tokenizer: return lowerCamelCase_ : str = self.get_tokenizer() lowerCamelCase_ : List[str] = self.get_rust_tokenizer() lowerCamelCase_ : int = "UNwant\u00E9d,running" lowerCamelCase_ : str = tokenizer.tokenize(a_ ) lowerCamelCase_ : List[str] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) lowerCamelCase_ : Dict = tokenizer.encode(a_ , add_special_tokens=a_ ) lowerCamelCase_ : Optional[Any] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) lowerCamelCase_ : Dict = self.get_rust_tokenizer() lowerCamelCase_ : Dict = tokenizer.encode(a_ ) lowerCamelCase_ : str = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) # With lower casing lowerCamelCase_ : int = self.get_tokenizer(do_lower_case=a_ ) lowerCamelCase_ : Tuple = self.get_rust_tokenizer(do_lower_case=a_ ) lowerCamelCase_ : str = "UNwant\u00E9d,running" lowerCamelCase_ : List[Any] = tokenizer.tokenize(a_ ) lowerCamelCase_ : Any = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) lowerCamelCase_ : Union[str, Any] = tokenizer.encode(a_ , add_special_tokens=a_ ) lowerCamelCase_ : Union[str, Any] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) lowerCamelCase_ : List[Any] = self.get_rust_tokenizer() lowerCamelCase_ : Tuple = tokenizer.encode(a_ ) lowerCamelCase_ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = BasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = BasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = BasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = BasicTokenizer(do_lower_case=a_ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = BasicTokenizer() lowerCamelCase_ : Dict = "a\n'll !!to?'d of, can't." lowerCamelCase_ : str = ["a", "'", "ll", "!", "!", "to", "?", "'", "d", "of", ",", "can", "'", "t", "."] self.assertListEqual(tokenizer.tokenize(a_ ) , a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] lowerCamelCase_ : Union[str, Any] = {} for i, token in enumerate(a_ ): lowerCamelCase_ : List[str] = i lowerCamelCase_ : Optional[Any] = WordpieceTokenizer(vocab=a_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def _UpperCamelCase ( self ): self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def _UpperCamelCase ( self ): self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def _UpperCamelCase ( self ): self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = self.get_tokenizer() lowerCamelCase_ : Any = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(a_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) self.assertListEqual( [rust_tokenizer.tokenize(a_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) @slow def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = self.tokenizer_class.from_pretrained("bert-base-uncased" ) lowerCamelCase_ : str = tokenizer.encode("sequence builders" , add_special_tokens=a_ ) lowerCamelCase_ : Dict = tokenizer.encode("multi-sequence build" , add_special_tokens=a_ ) lowerCamelCase_ : Dict = tokenizer.build_inputs_with_special_tokens(a_ ) lowerCamelCase_ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(a_ , a_ ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def _UpperCamelCase ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCamelCase_ : str = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) lowerCamelCase_ : str = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" lowerCamelCase_ : Dict = tokenizer_r.encode_plus( a_ , return_attention_mask=a_ , return_token_type_ids=a_ , return_offsets_mapping=a_ , add_special_tokens=a_ , ) lowerCamelCase_ : Any = tokenizer_r.do_lower_case if hasattr(a_ , "do_lower_case" ) else False lowerCamelCase_ : List[str] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "Allen"), ((21, 23), "##NL"), ((23, 24), "##P"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "allen"), ((21, 23), "##nl"), ((23, 24), "##p"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = ["的", "人", "有"] lowerCamelCase_ : str = "".join(a_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCamelCase_ : Dict = True lowerCamelCase_ : str = self.tokenizer_class.from_pretrained(a_ , **a_ ) lowerCamelCase_ : List[str] = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) lowerCamelCase_ : Optional[Any] = tokenizer_p.encode(a_ , add_special_tokens=a_ ) lowerCamelCase_ : Dict = tokenizer_r.encode(a_ , add_special_tokens=a_ ) lowerCamelCase_ : Tuple = tokenizer_r.convert_ids_to_tokens(a_ ) lowerCamelCase_ : int = tokenizer_p.convert_ids_to_tokens(a_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , a_ ) lowerCamelCase_ : List[Any] = False lowerCamelCase_ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) lowerCamelCase_ : Dict = self.tokenizer_class.from_pretrained(a_ , **a_ ) lowerCamelCase_ : int = tokenizer_r.encode(a_ , add_special_tokens=a_ ) lowerCamelCase_ : Optional[Any] = tokenizer_p.encode(a_ , add_special_tokens=a_ ) lowerCamelCase_ : str = tokenizer_r.convert_ids_to_tokens(a_ ) lowerCamelCase_ : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(a_ ) # it is expected that only the first Chinese character is not preceded by "##". lowerCamelCase_ : Optional[Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(a_ ) ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , a_ )
73
import re def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if len(re.findall("[ATCG]" , lowerCAmelCase_)) != len(lowerCAmelCase_): raise ValueError("Invalid Strand") return dna.translate(dna.maketrans("ATCG" , "TAGC")) if __name__ == "__main__": import doctest doctest.testmod()
73
1
from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(a_ , "embed_dim" ) ) self.parent.assertTrue(hasattr(a_ , "num_heads" ) ) class lowerCAmelCase__ : """simple docstring""" def __init__( self , a_ , a_=13 , a_=64 , a_=3 , a_=[16, 48, 96] , a_=[1, 3, 6] , a_=[1, 2, 10] , a_=[7, 3, 3] , a_=[4, 2, 2] , a_=[2, 1, 1] , a_=[2, 2, 2] , a_=[False, False, True] , a_=[0.0, 0.0, 0.0] , a_=0.02 , a_=1E-12 , a_=True , a_=True , a_=2 , ): lowerCamelCase_ : int = parent lowerCamelCase_ : List[str] = batch_size lowerCamelCase_ : Dict = image_size lowerCamelCase_ : Union[str, Any] = patch_sizes lowerCamelCase_ : str = patch_stride lowerCamelCase_ : Union[str, Any] = patch_padding lowerCamelCase_ : Any = is_training lowerCamelCase_ : int = use_labels lowerCamelCase_ : Tuple = num_labels lowerCamelCase_ : str = num_channels lowerCamelCase_ : Optional[Any] = embed_dim lowerCamelCase_ : Dict = num_heads lowerCamelCase_ : Union[str, Any] = stride_kv lowerCamelCase_ : Union[str, Any] = depth lowerCamelCase_ : Union[str, Any] = cls_token lowerCamelCase_ : Union[str, Any] = attention_drop_rate lowerCamelCase_ : Dict = initializer_range lowerCamelCase_ : Optional[Any] = layer_norm_eps def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ : Dict = None if self.use_labels: # create a random int32 tensor of given shape lowerCamelCase_ : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase_ : Dict = self.get_config() return config, pixel_values, labels def _UpperCamelCase ( self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self , a_ , a_ , a_ ): lowerCamelCase_ : str = TFCvtModel(config=a_ ) lowerCamelCase_ : List[Any] = model(a_ , training=a_ ) lowerCamelCase_ : Tuple = (self.image_size, self.image_size) lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = image_size[0], image_size[1] for i in range(len(self.depth ) ): lowerCamelCase_ : str = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) lowerCamelCase_ : Optional[int] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def _UpperCamelCase ( self , a_ , a_ , a_ ): lowerCamelCase_ : str = self.num_labels lowerCamelCase_ : str = TFCvtForImageClassification(a_ ) lowerCamelCase_ : Optional[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = self.prepare_config_and_inputs() lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = config_and_inputs lowerCamelCase_ : Any = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : int = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () __UpperCAmelCase : Union[str, Any] = ( {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification} if is_tf_available() else {} ) __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Optional[int] = False def _UpperCamelCase ( self ): lowerCamelCase_ : str = TFCvtModelTester(self ) lowerCamelCase_ : Tuple = TFCvtConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def _UpperCamelCase ( self ): self.config_tester.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() @unittest.skip(reason="Cvt does not output attentions" ) def _UpperCamelCase ( self ): pass @unittest.skip(reason="Cvt does not use inputs_embeds" ) def _UpperCamelCase ( self ): pass @unittest.skip(reason="Cvt does not support input and output embeddings" ) def _UpperCamelCase ( self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) def _UpperCamelCase ( self ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) @slow def _UpperCamelCase ( self ): super().test_keras_fit() @unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8" ) def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = tf.keras.mixed_precision.Policy("mixed_float16" ) tf.keras.mixed_precision.set_global_policy(a_ ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("float32" ) def _UpperCamelCase ( self ): lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ : Optional[Any] = model_class(a_ ) lowerCamelCase_ : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ : str = [*signature.parameters.keys()] lowerCamelCase_ : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , a_ ) def _UpperCamelCase ( self ): def check_hidden_states_output(a_ , a_ , a_ ): lowerCamelCase_ : str = model_class(a_ ) lowerCamelCase_ : List[str] = model(**self._prepare_for_class(a_ , a_ ) ) lowerCamelCase_ : List[Any] = outputs.hidden_states lowerCamelCase_ : Any = len(self.model_tester.depth ) self.assertEqual(len(a_ ) , a_ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) lowerCamelCase_ ,lowerCamelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ : Tuple = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ : Dict = True check_hidden_states_output(a_ , a_ , a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def _UpperCamelCase ( self ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ : Any = TFCvtModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_tf @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def _UpperCamelCase ( self ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _UpperCamelCase ( self ): lowerCamelCase_ : Any = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) lowerCamelCase_ : str = self.default_image_processor lowerCamelCase_ : Optional[Any] = prepare_img() lowerCamelCase_ : List[str] = image_processor(images=a_ , return_tensors="tf" ) # forward pass lowerCamelCase_ : Union[str, Any] = model(**a_ ) # verify the logits lowerCamelCase_ : List[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) lowerCamelCase_ : Optional[Any] = tf.constant([0.92_85, 0.90_15, -0.31_50] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a_ , atol=1E-4 ) )
73
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False): '''simple docstring''' if radian_mode: return [magnitude * cos(lowerCAmelCase_), magnitude * sin(lowerCAmelCase_)] return [magnitude * cos(radians(lowerCAmelCase_)), magnitude * sin(radians(lowerCAmelCase_))] def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 10**-1): '''simple docstring''' lowerCamelCase_ : NDArray[floataa] = cross(lowerCAmelCase_ , lowerCAmelCase_) lowerCamelCase_ : float = sum(lowerCAmelCase_) return abs(lowerCAmelCase_) < eps if __name__ == "__main__": # Test to check if it works __magic_name__ = array( [ polar_force(7_18.4, 1_8_0 - 3_0), polar_force(8_79.54, 4_5), polar_force(1_0_0, -9_0), ] ) __magic_name__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg __magic_name__ = array( [ polar_force(3_0 * 9.81, 1_5), polar_force(2_1_5, 1_8_0 - 4_5), polar_force(2_6_4, 9_0 - 3_0), ] ) __magic_name__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg __magic_name__ = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]]) __magic_name__ = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
1
class lowerCAmelCase__ : """simple docstring""" def __init__( self , a_ ): lowerCamelCase_ : List[str] = n lowerCamelCase_ : Any = [None] * self.n lowerCamelCase_ : Dict = 0 # index of the first element lowerCamelCase_ : Union[str, Any] = 0 lowerCamelCase_ : Dict = 0 def __len__( self ): return self.size def _UpperCamelCase ( self ): return self.size == 0 def _UpperCamelCase ( self ): return False if self.is_empty() else self.array[self.front] def _UpperCamelCase ( self , a_ ): if self.size >= self.n: raise Exception("QUEUE IS FULL" ) lowerCamelCase_ : Optional[Any] = data lowerCamelCase_ : Optional[int] = (self.rear + 1) % self.n self.size += 1 return self def _UpperCamelCase ( self ): if self.size == 0: raise Exception("UNDERFLOW" ) lowerCamelCase_ : Optional[Any] = self.array[self.front] lowerCamelCase_ : List[str] = None lowerCamelCase_ : Optional[int] = (self.front + 1) % self.n self.size -= 1 return temp
73
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''ClapFeatureExtractor''' __UpperCAmelCase : List[str] = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) def __call__( self , a_=None , a_=None , a_=None , **a_ ): lowerCamelCase_ : Any = kwargs.pop("sampling_rate" , a_ ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: lowerCamelCase_ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if audios is not None: lowerCamelCase_ : List[str] = self.feature_extractor( a_ , sampling_rate=a_ , return_tensors=a_ , **a_ ) if text is not None and audios is not None: lowerCamelCase_ : List[str] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) @property def _UpperCamelCase ( self ): lowerCamelCase_ : int = self.tokenizer.model_input_names lowerCamelCase_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
73
1
import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): """simple docstring""" @register_to_config def __init__( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ = False , ): super().__init__() lowerCamelCase_ : Optional[int] = nn.Embedding(a_ , a_ ) lowerCamelCase_ : int = nn.Embedding(a_ , a_ ) lowerCamelCase_ : Any = False lowerCamelCase_ : Any = nn.Dropout(p=a_ ) lowerCamelCase_ : Union[str, Any] = TaConfig( vocab_size=a_ , d_model=a_ , num_heads=a_ , d_kv=a_ , d_ff=a_ , dropout_rate=a_ , feed_forward_proj=a_ , is_decoder=a_ , is_encoder_decoder=a_ , ) lowerCamelCase_ : Optional[Any] = nn.ModuleList() for lyr_num in range(a_ ): lowerCamelCase_ : List[str] = TaBlock(a_ ) self.encoders.append(a_ ) lowerCamelCase_ : List[Any] = TaLayerNorm(a_ ) lowerCamelCase_ : Optional[Any] = nn.Dropout(p=a_ ) def _UpperCamelCase ( self , a_ , a_ ): lowerCamelCase_ : Tuple = self.token_embedder(a_ ) lowerCamelCase_ : int = encoder_input_tokens.shape[1] lowerCamelCase_ : int = torch.arange(a_ , device=encoder_input_tokens.device ) x += self.position_encoding(a_ ) lowerCamelCase_ : int = self.dropout_pre(a_ ) # inverted the attention mask lowerCamelCase_ : List[str] = encoder_input_tokens.size() lowerCamelCase_ : Tuple = self.get_extended_attention_mask(a_ , a_ ) for lyr in self.encoders: lowerCamelCase_ : List[Any] = lyr(a_ , a_ )[0] lowerCamelCase_ : str = self.layer_norm(a_ ) return self.dropout_post(a_ ), encoder_inputs_mask
73
def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : Any = set() # Replace all the whitespace in our sentence lowerCamelCase_ : str = input_str.replace(" " , "") for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(lowerCAmelCase_) == 26 def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : List[Any] = [False] * 26 for char in input_str: if char.islower(): lowerCamelCase_ : List[Any] = True elif char.isupper(): lowerCamelCase_ : Optional[int] = True return all(lowerCAmelCase_) def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()}) == 26 def __magic_name__ ( ): '''simple docstring''' from timeit import timeit lowerCamelCase_ : Optional[int] = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_faster()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_fastest()" , setup=lowerCAmelCase_)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __magic_name__ = { '''configuration_owlvit''': [ '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OwlViTConfig''', '''OwlViTOnnxConfig''', '''OwlViTTextConfig''', '''OwlViTVisionConfig''', ], '''processing_owlvit''': ['''OwlViTProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''OwlViTFeatureExtractor'''] __magic_name__ = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OwlViTModel''', '''OwlViTPreTrainedModel''', '''OwlViTTextModel''', '''OwlViTVisionModel''', '''OwlViTForObjectDetection''', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
73
__magic_name__ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634E-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.35_58_18, } def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: lowerCamelCase_ : List[Any] = ( F"""Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n""" F"""Valid values are: {', '.join(lowerCAmelCase_)}""" ) raise ValueError(lowerCAmelCase_) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
73
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __magic_name__ = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
73
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 __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'''vocab_file''': '''spiece.model'''} __magic_name__ = { '''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''', } } __magic_name__ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) __magic_name__ = 0 __magic_name__ = 1 __magic_name__ = 2 __magic_name__ = 3 __magic_name__ = 4 class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[int] = '''left''' def __init__( self , a_ , a_=False , a_=True , a_=False , a_="<s>" , a_="</s>" , a_="<unk>" , a_="<sep>" , a_="<pad>" , a_="<cls>" , a_="<mask>" , a_=["<eop>", "<eod>"] , a_ = None , **a_ , ): # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ : str = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token lowerCamelCase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) lowerCamelCase_ : str = 3 lowerCamelCase_ : Dict = do_lower_case lowerCamelCase_ : str = remove_space lowerCamelCase_ : Tuple = keep_accents lowerCamelCase_ : Dict = vocab_file lowerCamelCase_ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) @property def _UpperCamelCase ( self ): return len(self.sp_model ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowerCamelCase_ : Any = self.__dict__.copy() lowerCamelCase_ : Optional[int] = None return state def __setstate__( self , a_ ): lowerCamelCase_ : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase_ : int = {} lowerCamelCase_ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self , a_ ): if self.remove_space: lowerCamelCase_ : Optional[int] = " ".join(inputs.strip().split() ) else: lowerCamelCase_ : str = inputs lowerCamelCase_ : Any = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: lowerCamelCase_ : Dict = unicodedata.normalize("NFKD" , a_ ) lowerCamelCase_ : int = "".join([c for c in outputs if not unicodedata.combining(a_ )] ) if self.do_lower_case: lowerCamelCase_ : Any = outputs.lower() return outputs def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : List[Any] = self.preprocess_text(a_ ) lowerCamelCase_ : Optional[int] = self.sp_model.encode(a_ , out_type=a_ ) lowerCamelCase_ : List[str] = [] for piece in pieces: if len(a_ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): lowerCamelCase_ : Tuple = self.sp_model.EncodeAsPieces(piece[:-1].replace(a_ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase_ : int = cur_pieces[1:] else: lowerCamelCase_ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(a_ ) else: new_pieces.append(a_ ) return new_pieces def _UpperCamelCase ( self , a_ ): return self.sp_model.PieceToId(a_ ) def _UpperCamelCase ( self , a_ ): return self.sp_model.IdToPiece(a_ ) def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Dict = "".join(a_ ).replace(a_ , " " ).strip() return out_string def _UpperCamelCase ( self , a_ , a_ = False , a_ = None , a_ = True , **a_ , ): lowerCamelCase_ : int = kwargs.pop("use_source_tokenizer" , a_ ) lowerCamelCase_ : List[str] = self.convert_ids_to_tokens(a_ , skip_special_tokens=a_ ) # 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 lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : List[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(a_ ) ) lowerCamelCase_ : Union[str, Any] = [] sub_texts.append(a_ ) else: current_sub_text.append(a_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase_ : Union[str, Any] = "".join(a_ ) lowerCamelCase_ : Optional[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase_ : List[Any] = self.clean_up_tokenization(a_ ) return clean_text else: return text def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, 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 _UpperCamelCase ( self , a_ , a_ = None , a_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ ) if token_ids_a is not None: return ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1, 1] return ([0] * len(a_ )) + [1, 1] def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, Any] = [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 _UpperCamelCase ( self , a_ , a_ = None ): if not os.path.isdir(a_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase_ : Any = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , "wb" ) as fi: lowerCamelCase_ : Dict = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
73
1
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar __magic_name__ = TypeVar('''T''') class lowerCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self , a_ = True ): lowerCamelCase_ : dict[T, list[T]] = {} # dictionary of lists lowerCamelCase_ : Optional[int] = directed def _UpperCamelCase ( self , a_ , a_ ): if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(a_ ) self.adj_list[destination_vertex].append(a_ ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(a_ ) lowerCamelCase_ : List[Any] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(a_ ) lowerCamelCase_ : Tuple = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: lowerCamelCase_ : Any = [destination_vertex] lowerCamelCase_ : int = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(a_ ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(a_ ) lowerCamelCase_ : Dict = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: lowerCamelCase_ : Optional[Any] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: lowerCamelCase_ : List[str] = [destination_vertex] lowerCamelCase_ : Optional[Any] = [] return self def __repr__( self ): return pformat(self.adj_list )
73
def __magic_name__ ( lowerCAmelCase_ = 10 , lowerCAmelCase_ = 1000 , lowerCAmelCase_ = True): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)") return min_val if option else max_val def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' return int((number_a + number_a) / 2) def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)") if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value") def answer(lowerCAmelCase_) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started...") lowerCamelCase_ : Optional[int] = lower lowerCamelCase_ : Tuple = higher lowerCamelCase_ : Union[str, Any] = [] while True: lowerCamelCase_ : Optional[int] = get_avg(lowerCAmelCase_ , lowerCAmelCase_) last_numbers.append(lowerCAmelCase_) if answer(lowerCAmelCase_) == "low": lowerCamelCase_ : Any = number elif answer(lowerCAmelCase_) == "high": lowerCamelCase_ : Optional[int] = number else: break print(F"""guess the number : {last_numbers[-1]}""") print(F"""details : {last_numbers!s}""") def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Optional[int] = int(input("Enter lower value : ").strip()) lowerCamelCase_ : List[str] = int(input("Enter high value : ").strip()) lowerCamelCase_ : List[str] = int(input("Enter value to guess : ").strip()) guess_the_number(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) if __name__ == "__main__": main()
73
1
import math def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' return math.pow(lowerCAmelCase_ , 2) - a def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' return 2 * x def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : int = 2.0 while start <= a: lowerCamelCase_ : List[Any] = math.pow(lowerCAmelCase_ , 2) return start def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ = 9999 , lowerCAmelCase_ = 0.00_00_00_00_00_00_01): '''simple docstring''' if a < 0: raise ValueError("math domain error") lowerCamelCase_ : List[str] = get_initial_point(lowerCAmelCase_) for _ in range(lowerCAmelCase_): lowerCamelCase_ : Tuple = value lowerCamelCase_ : Optional[int] = value - fx(lowerCAmelCase_ , lowerCAmelCase_) / fx_derivative(lowerCAmelCase_) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[str] = '''cvt''' def __init__( self , a_=3 , a_=[7, 3, 3] , a_=[4, 2, 2] , a_=[2, 1, 1] , a_=[64, 192, 384] , a_=[1, 3, 6] , a_=[1, 2, 10] , a_=[4.0, 4.0, 4.0] , a_=[0.0, 0.0, 0.0] , a_=[0.0, 0.0, 0.0] , a_=[0.0, 0.0, 0.1] , a_=[True, True, True] , a_=[False, False, True] , a_=["dw_bn", "dw_bn", "dw_bn"] , a_=[3, 3, 3] , a_=[1, 1, 1] , a_=[2, 2, 2] , a_=[1, 1, 1] , a_=[1, 1, 1] , a_=0.02 , a_=1E-12 , **a_ , ): super().__init__(**a_ ) lowerCamelCase_ : Optional[Any] = num_channels lowerCamelCase_ : str = patch_sizes lowerCamelCase_ : List[Any] = patch_stride lowerCamelCase_ : str = patch_padding lowerCamelCase_ : str = embed_dim lowerCamelCase_ : Union[str, Any] = num_heads lowerCamelCase_ : Optional[Any] = depth lowerCamelCase_ : int = mlp_ratio lowerCamelCase_ : Union[str, Any] = attention_drop_rate lowerCamelCase_ : Optional[Any] = drop_rate lowerCamelCase_ : Optional[int] = drop_path_rate lowerCamelCase_ : Union[str, Any] = qkv_bias lowerCamelCase_ : int = cls_token lowerCamelCase_ : int = qkv_projection_method lowerCamelCase_ : int = kernel_qkv lowerCamelCase_ : Optional[Any] = padding_kv lowerCamelCase_ : Optional[int] = stride_kv lowerCamelCase_ : Optional[int] = padding_q lowerCamelCase_ : List[Any] = stride_q lowerCamelCase_ : Any = initializer_range lowerCamelCase_ : int = layer_norm_eps
73
1
from timeit import timeit __magic_name__ = { '''MALAYALAM''': True, '''String''': False, '''rotor''': True, '''level''': True, '''A''': True, '''BB''': True, '''ABC''': False, '''amanaplanacanalpanama''': True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : List[str] = 0 lowerCamelCase_ : Optional[Any] = len(lowerCAmelCase_) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Optional[int] = len(lowerCAmelCase_) // 2 lowerCamelCase_ : int = len(lowerCAmelCase_) # We need to traverse till half of the length of string # as we can get access of the i'th last element from # i'th index. # eg: [0,1,2,3,4,5] => 4th index can be accessed # with the help of 1st index (i==n-i-1) # where n is length of string return all(s[i] == s[n - i - 1] for i in range(lowerCAmelCase_)) def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if len(lowerCAmelCase_) <= 2: return True if s[0] == s[len(lowerCAmelCase_) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' return s == s[::-1] def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : str = F"""all({name}(key) is value for key, value in test_data.items())""" lowerCamelCase_ : Dict = F"""from __main__ import test_data, {name}""" lowerCamelCase_ : str = 50_0000 lowerCamelCase_ : Any = timeit(stmt=lowerCAmelCase_ , setup=lowerCAmelCase_ , number=lowerCAmelCase_) print(F"""{name:<35} finished {number:,} runs in {result:.5f} seconds""") if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f'''{key:21} {value}''') print('''a man a plan a canal panama''') # finished 500,000 runs in 0.46793 seconds benchmark_function('''is_palindrome_slice''') # finished 500,000 runs in 0.85234 seconds benchmark_function('''is_palindrome''') # finished 500,000 runs in 1.32028 seconds benchmark_function('''is_palindrome_recursive''') # finished 500,000 runs in 2.08679 seconds benchmark_function('''is_palindrome_traversal''')
73
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __magic_name__ = {'''processing_layoutxlm''': ['''LayoutXLMProcessor''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''LayoutXLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''LayoutXLMTokenizerFast'''] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
73
1
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger __magic_name__ = get_logger(__name__) __magic_name__ = R''' Args: input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search kwargs (`Dict[str, Any]`, *optional*): Additional logits processor specific kwargs. Return: `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores. ''' class lowerCAmelCase__ : """simple docstring""" @add_start_docstrings(a_ ) def __call__( self , a_ , a_ ): raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class lowerCAmelCase__ : """simple docstring""" @add_start_docstrings(a_ ) def __call__( self , a_ , a_ ): raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" @add_start_docstrings(a_ ) def __call__( self , a_ , a_ , a_ , **a_ ): for processor in self: lowerCamelCase_ : int = inspect.signature(processor.__call__ ).parameters if len(a_ ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( F"""Make sure that all the required parameters: {list(function_args.keys() )} for """ F"""{processor.__class__} are passed to the logits processor.""" ) lowerCamelCase_ : Union[str, Any] = processor(a_ , a_ , a_ , **a_ ) else: lowerCamelCase_ : List[str] = processor(a_ , a_ , a_ ) return scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ ): if not isinstance(a_ , a_ ) or not (temperature > 0): raise ValueError(F"""`temperature` has to be a strictly positive float, but is {temperature}""" ) lowerCamelCase_ : int = temperature def __call__( self , a_ , a_ , a_ ): lowerCamelCase_ : str = scores / self.temperature return scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ = -float("Inf" ) , a_ = 1 ): if not isinstance(a_ , a_ ) or (top_p < 0 or top_p > 1.0): raise ValueError(F"""`top_p` has to be a float > 0 and < 1, but is {top_p}""" ) if not isinstance(a_ , a_ ) or (min_tokens_to_keep < 1): raise ValueError(F"""`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}""" ) lowerCamelCase_ : Tuple = top_p lowerCamelCase_ : Union[str, Any] = filter_value lowerCamelCase_ : Any = min_tokens_to_keep def __call__( self , a_ , a_ , a_ ): lowerCamelCase_ ,lowerCamelCase_ : str = lax.top_k(a_ , scores.shape[-1] ) lowerCamelCase_ : Optional[Any] = jnp.full_like(a_ , self.filter_value ) lowerCamelCase_ : str = jax.nn.softmax(a_ , axis=-1 ).cumsum(axis=-1 ) lowerCamelCase_ : List[str] = cumulative_probs < self.top_p # include the token that is higher than top_p as well lowerCamelCase_ : Optional[int] = jnp.roll(a_ , 1 ) score_mask |= score_mask.at[:, 0].set(a_ ) # min tokens to keep lowerCamelCase_ : str = score_mask.at[:, : self.min_tokens_to_keep].set(a_ ) lowerCamelCase_ : Union[str, Any] = jnp.where(a_ , a_ , a_ ) lowerCamelCase_ : Any = jax.lax.sort_key_val(a_ , a_ )[-1] return next_scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ = -float("Inf" ) , a_ = 1 ): if not isinstance(a_ , a_ ) or top_k <= 0: raise ValueError(F"""`top_k` has to be a strictly positive integer, but is {top_k}""" ) lowerCamelCase_ : Any = max(a_ , a_ ) lowerCamelCase_ : int = filter_value def __call__( self , a_ , a_ , a_ ): lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = scores.shape lowerCamelCase_ : str = jnp.full(batch_size * vocab_size , self.filter_value ) lowerCamelCase_ : int = min(self.top_k , scores.shape[-1] ) # Safety check lowerCamelCase_ ,lowerCamelCase_ : List[str] = lax.top_k(a_ , a_ ) lowerCamelCase_ : Tuple = jnp.broadcast_to((jnp.arange(a_ ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() lowerCamelCase_ : Optional[int] = topk_scores.flatten() lowerCamelCase_ : Tuple = topk_indices.flatten() + shift lowerCamelCase_ : List[Any] = next_scores_flat.at[topk_indices_flat].set(a_ ) lowerCamelCase_ : List[Any] = next_scores_flat.reshape(a_ , a_ ) return next_scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ ): lowerCamelCase_ : Optional[Any] = bos_token_id def __call__( self , a_ , a_ , a_ ): lowerCamelCase_ : List[str] = jnp.full(scores.shape , -float("inf" ) ) lowerCamelCase_ : Any = 1 - jnp.bool_(cur_len - 1 ) lowerCamelCase_ : Optional[int] = jnp.where(a_ , new_scores.at[:, self.bos_token_id].set(0 ) , a_ ) return scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ ): lowerCamelCase_ : List[Any] = max_length lowerCamelCase_ : int = eos_token_id def __call__( self , a_ , a_ , a_ ): lowerCamelCase_ : List[str] = jnp.full(scores.shape , -float("inf" ) ) lowerCamelCase_ : List[str] = 1 - jnp.bool_(cur_len - self.max_length + 1 ) lowerCamelCase_ : Union[str, Any] = jnp.where(a_ , new_scores.at[:, self.eos_token_id].set(0 ) , a_ ) return scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ ): if not isinstance(a_ , a_ ) or min_length < 0: raise ValueError(F"""`min_length` has to be a positive integer, but is {min_length}""" ) if not isinstance(a_ , a_ ) or eos_token_id < 0: raise ValueError(F"""`eos_token_id` has to be a positive integer, but is {eos_token_id}""" ) lowerCamelCase_ : Dict = min_length lowerCamelCase_ : Tuple = eos_token_id def __call__( self , a_ , a_ , a_ ): # create boolean flag to decide if min length penalty should be applied lowerCamelCase_ : Any = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) lowerCamelCase_ : Optional[int] = jnp.where(a_ , scores.at[:, self.eos_token_id].set(-float("inf" ) ) , a_ ) return scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ ): lowerCamelCase_ : int = list(a_ ) lowerCamelCase_ : List[str] = begin_index def __call__( self , a_ , a_ , a_ ): lowerCamelCase_ : Tuple = 1 - jnp.bool_(cur_len - self.begin_index ) lowerCamelCase_ : List[Any] = jnp.where(a_ , scores.at[:, self.begin_suppress_tokens].set(-float("inf" ) ) , a_ ) return scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ ): lowerCamelCase_ : List[Any] = list(a_ ) def __call__( self , a_ , a_ , a_ ): lowerCamelCase_ : Dict = scores.at[..., self.suppress_tokens].set(-float("inf" ) ) return scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ ): lowerCamelCase_ : Optional[int] = dict(a_ ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. lowerCamelCase_ : List[Any] = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: lowerCamelCase_ : Optional[int] = force_token_array.at[index].set(a_ ) lowerCamelCase_ : Union[str, Any] = jnp.intaa(a_ ) def __call__( self , a_ , a_ , a_ ): def _force_token(a_ ): lowerCamelCase_ : Tuple = scores.shape[0] lowerCamelCase_ : Tuple = self.force_token_array[generation_idx] lowerCamelCase_ : Optional[int] = jnp.ones_like(a_ , dtype=scores.dtype ) * -float("inf" ) lowerCamelCase_ : Any = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) lowerCamelCase_ : int = lax.dynamic_update_slice(a_ , a_ , (0, current_token) ) return new_scores lowerCamelCase_ : str = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(a_ ) , lambda: scores , ) , ) return scores class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ , a_ ): lowerCamelCase_ : List[Any] = generate_config.eos_token_id lowerCamelCase_ : Union[str, Any] = generate_config.no_timestamps_token_id lowerCamelCase_ : str = generate_config.no_timestamps_token_id + 1 lowerCamelCase_ : str = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(a_ , "max_initial_timestamp_index" ): lowerCamelCase_ : Tuple = generate_config.max_initial_timestamp_index else: lowerCamelCase_ : Union[str, Any] = model_config.vocab_size if self.max_initial_timestamp_index is None: lowerCamelCase_ : Optional[int] = model_config.vocab_size def __call__( self , a_ , a_ , a_ ): # suppress <|notimestamps|> which is handled by without_timestamps lowerCamelCase_ : Any = scores.at[:, self.no_timestamps_token_id].set(-float("inf" ) ) def handle_pairs(a_ , a_ ): lowerCamelCase_ : Dict = jnp.where((cur_len - self.begin_index) >= 1 , a_ , a_ ) lowerCamelCase_ : str = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , a_ , ) lowerCamelCase_ : int = jnp.where((cur_len - self.begin_index) < 2 , a_ , a_ ) lowerCamelCase_ : Any = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , a_ , a_ , ) return jnp.where( a_ , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float("inf" ) ) , scores_k.at[: self.eos_token_id].set(-float("inf" ) ) , ) , a_ , ) lowerCamelCase_ : str = jax.vmap(a_ )(a_ , a_ ) lowerCamelCase_ : Optional[int] = jnp.where(cur_len == self.begin_index , a_ , a_ ) lowerCamelCase_ : str = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , a_ , ) lowerCamelCase_ : Optional[int] = self.timestamp_begin + self.max_initial_timestamp_index lowerCamelCase_ : List[Any] = jnp.where( a_ , scores.at[:, last_allowed + 1 :].set(-float("inf" ) ) , a_ , ) # if sum of probability over timestamps is above any other token, sample timestamp lowerCamelCase_ : int = jax.nn.log_softmax(a_ , axis=-1 ) def handle_cumulative_probs(a_ , a_ ): lowerCamelCase_ : Dict = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) lowerCamelCase_ : str = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float("inf" ) ) , a_ , ) lowerCamelCase_ : int = jax.vmap(a_ )(a_ , a_ ) return scores
73
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''EncodecFeatureExtractor''' __UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) lowerCamelCase_ : Optional[Any] = self.feature_extractor lowerCamelCase_ : Optional[int] = False def _UpperCamelCase ( self , a_=None , a_=None , a_=True ): return self.tokenizer.get_decoder_prompt_ids(task=a_ , language=a_ , no_timestamps=a_ ) def __call__( self , *a_ , **a_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a_ , **a_ ) lowerCamelCase_ : str = kwargs.pop("audio" , a_ ) lowerCamelCase_ : List[str] = kwargs.pop("sampling_rate" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("text" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : int = args[0] lowerCamelCase_ : str = 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 text is not None: lowerCamelCase_ : Dict = self.tokenizer(a_ , **a_ ) if audio is not None: lowerCamelCase_ : Optional[Any] = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ ) if audio is None: return inputs elif text is None: return audio_inputs else: lowerCamelCase_ : Dict = audio_inputs["input_values"] if "padding_mask" in audio_inputs: lowerCamelCase_ : int = audio_inputs["padding_mask"] return inputs def _UpperCamelCase ( self , *a_ , **a_ ): lowerCamelCase_ : Dict = kwargs.pop("audio" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("padding_mask" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : Optional[int] = args[0] lowerCamelCase_ : Optional[Any] = args[1:] if audio_values is not None: return self._decode_audio(a_ , padding_mask=a_ ) else: return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Any = to_numpy(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[str] = audio_values.shape if padding_mask is None: return list(a_ ) lowerCamelCase_ : Tuple = to_numpy(a_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) lowerCamelCase_ : List[str] = seq_len - padding_mask.shape[-1] lowerCamelCase_ : int = 1 - self.feature_extractor.padding_value lowerCamelCase_ : List[Any] = np.pad(a_ , ((0, 0), (0, difference)) , "constant" , constant_values=a_ ) lowerCamelCase_ : str = audio_values.tolist() for i in range(a_ ): lowerCamelCase_ : Dict = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] lowerCamelCase_ : Dict = sliced_audio.reshape(a_ , -1 ) return audio_values
73
1
import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : """simple docstring""" def __init__( self , a_ , a_=13 , a_=7 , a_=True , a_=True , a_=True , a_=True , a_=True , a_=False , a_=False , a_=False , a_=2 , a_=99 , a_=0 , a_=32 , a_=5 , a_=4 , a_=0.1 , a_=0.1 , a_=512 , a_=2 , a_=0.02 , a_=2 , a_=4 , a_="last" , a_=True , a_=None , a_=0 , ): lowerCamelCase_ : Optional[int] = parent lowerCamelCase_ : List[Any] = batch_size lowerCamelCase_ : Dict = seq_length lowerCamelCase_ : Any = is_training lowerCamelCase_ : int = use_input_lengths lowerCamelCase_ : Union[str, Any] = use_token_type_ids lowerCamelCase_ : Dict = use_labels lowerCamelCase_ : Tuple = gelu_activation lowerCamelCase_ : Optional[int] = sinusoidal_embeddings lowerCamelCase_ : Optional[int] = causal lowerCamelCase_ : List[Any] = asm lowerCamelCase_ : str = n_langs lowerCamelCase_ : Dict = vocab_size lowerCamelCase_ : Tuple = n_special lowerCamelCase_ : Tuple = hidden_size lowerCamelCase_ : Optional[int] = num_hidden_layers lowerCamelCase_ : str = num_attention_heads lowerCamelCase_ : int = hidden_dropout_prob lowerCamelCase_ : str = attention_probs_dropout_prob lowerCamelCase_ : Any = max_position_embeddings lowerCamelCase_ : Any = type_sequence_label_size lowerCamelCase_ : Optional[Any] = initializer_range lowerCamelCase_ : List[Any] = num_labels lowerCamelCase_ : Optional[int] = num_choices lowerCamelCase_ : Any = summary_type lowerCamelCase_ : List[str] = use_proj lowerCamelCase_ : Optional[int] = scope lowerCamelCase_ : Dict = bos_token_id def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase_ : str = None if self.use_input_lengths: lowerCamelCase_ : int = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length lowerCamelCase_ : Optional[Any] = None if self.use_token_type_ids: lowerCamelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) lowerCamelCase_ : Tuple = None lowerCamelCase_ : Optional[int] = None lowerCamelCase_ : Optional[int] = None if self.use_labels: lowerCamelCase_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ : str = ids_tensor([self.batch_size] , 2 ).float() lowerCamelCase_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ : List[Any] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _UpperCamelCase ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): lowerCamelCase_ : Any = XLMModel(config=a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : str = model(a_ , lengths=a_ , langs=a_ ) lowerCamelCase_ : Union[str, Any] = model(a_ , langs=a_ ) lowerCamelCase_ : str = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): lowerCamelCase_ : List[str] = XLMWithLMHeadModel(a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : Dict = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): lowerCamelCase_ : str = XLMForQuestionAnsweringSimple(a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : Dict = model(a_ ) lowerCamelCase_ : Dict = model(a_ , start_positions=a_ , end_positions=a_ ) lowerCamelCase_ : Optional[int] = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): lowerCamelCase_ : List[Any] = XLMForQuestionAnswering(a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : str = model(a_ ) lowerCamelCase_ : List[Any] = model( a_ , start_positions=a_ , end_positions=a_ , cls_index=a_ , is_impossible=a_ , p_mask=a_ , ) lowerCamelCase_ : str = model( a_ , start_positions=a_ , end_positions=a_ , cls_index=a_ , is_impossible=a_ , ) ((lowerCamelCase_) ,) : int = result_with_labels.to_tuple() lowerCamelCase_ : Any = model(a_ , start_positions=a_ , end_positions=a_ ) ((lowerCamelCase_) ,) : Any = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): lowerCamelCase_ : Optional[int] = XLMForSequenceClassification(a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : List[Any] = model(a_ ) lowerCamelCase_ : Dict = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): lowerCamelCase_ : int = self.num_labels lowerCamelCase_ : Any = XLMForTokenClassification(a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : Optional[int] = model(a_ , attention_mask=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ): lowerCamelCase_ : str = self.num_choices lowerCamelCase_ : Union[str, Any] = XLMForMultipleChoice(config=a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCamelCase_ : Tuple = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCamelCase_ : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCamelCase_ : str = model( a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) : Dict = config_and_inputs lowerCamelCase_ : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[str] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) __UpperCAmelCase : Optional[int] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable __UpperCAmelCase : List[str] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _UpperCamelCase ( self , a_ , a_ , a_=False ): lowerCamelCase_ : int = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": lowerCamelCase_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) lowerCamelCase_ : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) return inputs_dict def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = XLMModelTester(self ) lowerCamelCase_ : Any = ConfigTester(self , config_class=a_ , emb_dim=37 ) def _UpperCamelCase ( self ): self.config_tester.run_common_tests() def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_=False , a_=1 ): self.assertIsInstance(a_ , a_ ) self.assertListEqual( [isinstance(a_ , a_ ) for iter_attentions in attentions] , [True] * len(a_ ) ) self.assertEqual(len(a_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(a_ ): # adds PAD dummy token lowerCamelCase_ : Optional[Any] = min_length + idx + 1 lowerCamelCase_ : Union[str, Any] = min_length + idx + 1 lowerCamelCase_ : Dict = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(a_ ) ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_=False , a_=1 ): self.assertIsInstance(a_ , a_ ) self.assertListEqual( [isinstance(a_ , a_ ) for iter_hidden_states in hidden_states] , [True] * len(a_ ) , ) self.assertEqual(len(a_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(a_ ): # adds PAD dummy token lowerCamelCase_ : Any = min_length + idx + 1 lowerCamelCase_ : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(a_ ) , ) pass @slow def _UpperCamelCase ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ : Union[str, Any] = XLMModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048" ) model.to(a_ ) lowerCamelCase_ : Any = torch.tensor([[14, 447]] , dtype=torch.long , device=a_ ) # the president lowerCamelCase_ : str = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference lowerCamelCase_ : List[str] = model.generate(a_ , do_sample=a_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , a_ )
73
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if digit_amount > 0: return round(number - int(lowerCAmelCase_) , lowerCAmelCase_) return number - int(lowerCAmelCase_) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.3_45, 1)) print(decimal_isolate(35.3_45, 2)) print(decimal_isolate(35.3_45, 3)) print(decimal_isolate(-14.7_89, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.1_23, 1)) print(decimal_isolate(-14.1_23, 2)) print(decimal_isolate(-14.1_23, 3))
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __magic_name__ = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2Config'''], '''feature_extraction_wav2vec2''': ['''Wav2Vec2FeatureExtractor'''], '''processing_wav2vec2''': ['''Wav2Vec2Processor'''], '''tokenization_wav2vec2''': ['''Wav2Vec2CTCTokenizer''', '''Wav2Vec2Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Wav2Vec2ForAudioFrameClassification''', '''Wav2Vec2ForCTC''', '''Wav2Vec2ForMaskedLM''', '''Wav2Vec2ForPreTraining''', '''Wav2Vec2ForSequenceClassification''', '''Wav2Vec2ForXVector''', '''Wav2Vec2Model''', '''Wav2Vec2PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWav2Vec2ForCTC''', '''TFWav2Vec2Model''', '''TFWav2Vec2PreTrainedModel''', '''TFWav2Vec2ForSequenceClassification''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''FlaxWav2Vec2ForCTC''', '''FlaxWav2Vec2ForPreTraining''', '''FlaxWav2Vec2Model''', '''FlaxWav2Vec2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
73
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , a_ , a_=7 , a_=3 , a_=18 , a_=30 , a_=400 , a_=True , a_=None , a_=True , ): lowerCamelCase_ : int = size if size is not None else {"height": 18, "width": 18} lowerCamelCase_ : str = parent lowerCamelCase_ : str = batch_size lowerCamelCase_ : Tuple = num_channels lowerCamelCase_ : Optional[int] = image_size lowerCamelCase_ : List[str] = min_resolution lowerCamelCase_ : Tuple = max_resolution lowerCamelCase_ : Tuple = do_resize lowerCamelCase_ : Dict = size lowerCamelCase_ : List[str] = apply_ocr def _UpperCamelCase ( self ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowerCAmelCase__ ( __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = LayoutLMvaImageProcessingTester(self ) @property def _UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , "do_resize" ) ) self.assertTrue(hasattr(a_ , "size" ) ) self.assertTrue(hasattr(a_ , "apply_ocr" ) ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) lowerCamelCase_ : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def _UpperCamelCase ( self ): pass def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input lowerCamelCase_ : List[str] = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , a_ ) self.assertIsInstance(encoding.boxes , a_ ) # Test batched lowerCamelCase_ : int = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) # Test not batched input lowerCamelCase_ : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCamelCase_ : Any = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # Initialize image_processing lowerCamelCase_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input lowerCamelCase_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched lowerCamelCase_ : Union[str, Any] = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def _UpperCamelCase ( self ): # with apply_OCR = True lowerCamelCase_ : Any = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCamelCase_ : Optional[Any] = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) lowerCamelCase_ : Optional[Any] = Image.open(ds[0]["file"] ).convert("RGB" ) lowerCamelCase_ : List[Any] = image_processing(a_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCamelCase_ : List[Any] = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 lowerCamelCase_ : Tuple = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , a_ ) self.assertListEqual(encoding.boxes , a_ ) # with apply_OCR = False lowerCamelCase_ : List[str] = LayoutLMvaImageProcessor(apply_ocr=a_ ) lowerCamelCase_ : List[str] = image_processing(a_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
73
1
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __magic_name__ = logging.get_logger(__name__) @add_end_docstrings(__lowerCamelCase ) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , **a_ ): super().__init__(**a_ ) requires_backends(self , "vision" ) requires_backends(self , "torch" ) if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) self.check_model_type(a_ ) def _UpperCamelCase ( self , **a_ ): lowerCamelCase_ : List[Any] = {} lowerCamelCase_ : Optional[Any] = {} lowerCamelCase_ : List[Any] = {} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase_ : int = kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase_ : Dict = kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase_ : int = kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase_ : Optional[Any] = kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase_ : Optional[int] = kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase_ : int = kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase_ : Optional[int] = kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase_ : Any = kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase_ : Tuple = kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase_ : Optional[Any] = kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase_ : Union[str, Any] = kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase_ : List[str] = kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , a_ , *a_ , a_=None , a_=None , **a_ ): return super().__call__(a_ , *a_ , num_workers=a_ , batch_size=a_ , **a_ ) def _UpperCamelCase ( self , a_ , a_=64 , a_ = 0 , a_ = 512 / 1500 , a_ = 32 , a_ = 1 , ): lowerCamelCase_ : Tuple = load_image(a_ ) lowerCamelCase_ : List[str] = self.image_processor.size["longest_edge"] lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[str] = self.image_processor.generate_crop_boxes( a_ , a_ , a_ , a_ , a_ , a_ ) lowerCamelCase_ : Tuple = self.image_processor(images=a_ , return_tensors="pt" ) with self.device_placement(): if self.framework == "pt": lowerCamelCase_ : str = self.get_inference_context() with inference_context(): lowerCamelCase_ : int = self._ensure_tensor_on_device(a_ , device=self.device ) lowerCamelCase_ : Tuple = self.model.get_image_embeddings(model_inputs.pop("pixel_values" ) ) lowerCamelCase_ : int = image_embeddings lowerCamelCase_ : Union[str, Any] = grid_points.shape[1] lowerCamelCase_ : Any = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None" ) for i in range(0 , a_ , a_ ): lowerCamelCase_ : List[str] = grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase_ : Any = input_labels[:, i : i + points_per_batch] lowerCamelCase_ : Union[str, Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def _UpperCamelCase ( self , a_ , a_=0.88 , a_=0.95 , a_=0 , a_=1 , ): lowerCamelCase_ : Union[str, Any] = model_inputs.pop("input_boxes" ) lowerCamelCase_ : Optional[Any] = model_inputs.pop("is_last" ) lowerCamelCase_ : List[str] = model_inputs.pop("original_sizes" ).tolist() lowerCamelCase_ : str = model_inputs.pop("reshaped_input_sizes" ).tolist() lowerCamelCase_ : int = self.model(**a_ ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase_ : int = model_outputs["pred_masks"] lowerCamelCase_ : Optional[Any] = self.image_processor.post_process_masks( a_ , a_ , a_ , a_ , binarize=a_ ) lowerCamelCase_ : Dict = model_outputs["iou_scores"] lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[Any] = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , a_ , a_ , a_ , a_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def _UpperCamelCase ( self , a_ , a_=False , a_=False , a_=0.7 , ): lowerCamelCase_ : Union[str, Any] = [] lowerCamelCase_ : List[str] = [] lowerCamelCase_ : str = [] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores" ) ) all_masks.extend(model_output.pop("masks" ) ) all_boxes.append(model_output.pop("boxes" ) ) lowerCamelCase_ : int = torch.cat(a_ ) lowerCamelCase_ : Optional[Any] = torch.cat(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Dict = self.image_processor.post_process_for_mask_generation( a_ , a_ , a_ , a_ ) lowerCamelCase_ : Any = defaultdict(a_ ) for output in model_outputs: for k, v in output.items(): extra[k].append(a_ ) lowerCamelCase_ : Tuple = {} if output_rle_mask: lowerCamelCase_ : Dict = rle_mask if output_bboxes_mask: lowerCamelCase_ : Tuple = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''studio-ousia/luke-base''': '''https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json''', '''studio-ousia/luke-large''': '''https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json''', } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = '''luke''' def __init__( self , a_=5_0267 , a_=50_0000 , a_=768 , a_=256 , a_=12 , a_=12 , a_=3072 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=2 , a_=0.02 , a_=1E-12 , a_=True , a_=None , a_=1 , a_=0 , a_=2 , **a_ , ): super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) lowerCamelCase_ : Tuple = vocab_size lowerCamelCase_ : Optional[int] = entity_vocab_size lowerCamelCase_ : Any = hidden_size lowerCamelCase_ : Dict = entity_emb_size lowerCamelCase_ : List[Any] = num_hidden_layers lowerCamelCase_ : int = num_attention_heads lowerCamelCase_ : Union[str, Any] = hidden_act lowerCamelCase_ : Tuple = intermediate_size lowerCamelCase_ : Optional[Any] = hidden_dropout_prob lowerCamelCase_ : Any = attention_probs_dropout_prob lowerCamelCase_ : Optional[Any] = max_position_embeddings lowerCamelCase_ : str = type_vocab_size lowerCamelCase_ : int = initializer_range lowerCamelCase_ : List[Any] = layer_norm_eps lowerCamelCase_ : Optional[int] = use_entity_aware_attention lowerCamelCase_ : str = classifier_dropout
73
1
def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Optional[Any] = [0] * len(lowerCAmelCase_) lowerCamelCase_ : Union[str, Any] = [] lowerCamelCase_ : str = [1] * len(lowerCAmelCase_) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCAmelCase_)): if indegree[i] == 0: queue.append(lowerCAmelCase_) while queue: lowerCamelCase_ : List[str] = queue.pop(0) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: lowerCamelCase_ : Dict = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(lowerCAmelCase_) print(max(lowerCAmelCase_)) # Adjacency list of Graph __magic_name__ = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
73
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __magic_name__ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class lowerCAmelCase__ ( datasets.BuilderConfig ): """simple docstring""" __UpperCAmelCase : Optional[datasets.Features] = None def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' import pyspark def generate_fn(): lowerCamelCase_ : Dict = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id")) for partition_id in partition_order: lowerCamelCase_ : Dict = df_with_partition_id.select("*").where(F"""part_id = {partition_id}""").drop("part_id") lowerCamelCase_ : Dict = partition_df.collect() lowerCamelCase_ : Dict = 0 for row in rows: yield F"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class lowerCAmelCase__ ( _BaseExamplesIterable ): """simple docstring""" def __init__( self , a_ , a_=None , ): lowerCamelCase_ : Dict = df lowerCamelCase_ : Optional[Any] = partition_order or range(self.df.rdd.getNumPartitions() ) lowerCamelCase_ : int = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ): yield from self.generate_examples_fn() def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Optional[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(a_ ) return SparkExamplesIterable(self.df , partition_order=a_ ) def _UpperCamelCase ( self , a_ , a_ ): lowerCamelCase_ : Dict = self.split_shard_indices_by_worker(a_ , a_ ) return SparkExamplesIterable(self.df , partition_order=a_ ) @property def _UpperCamelCase ( self ): return len(self.partition_order ) class lowerCAmelCase__ ( datasets.DatasetBuilder ): """simple docstring""" __UpperCAmelCase : Any = SparkConfig def __init__( self , a_ , a_ = None , a_ = None , **a_ , ): import pyspark lowerCamelCase_ : str = pyspark.sql.SparkSession.builder.getOrCreate() lowerCamelCase_ : Optional[Any] = df lowerCamelCase_ : List[Any] = working_dir super().__init__( cache_dir=a_ , config_name=str(self.df.semanticHash() ) , **a_ , ) def _UpperCamelCase ( self ): # Returns the path of the created file. def create_cache_and_write_probe(a_ ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=a_ ) lowerCamelCase_ : Optional[Any] = os.path.join(self._cache_dir , "fs_test" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(a_ , "a" ) return [probe_file] if self._spark.conf.get("spark.master" , "" ).startswith("local" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowerCamelCase_ : List[str] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(a_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir" ) def _UpperCamelCase ( self ): return datasets.DatasetInfo(features=self.config.features ) def _UpperCamelCase ( self , a_ ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def _UpperCamelCase ( self , a_ ): import pyspark def get_arrow_batch_size(a_ ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) lowerCamelCase_ : str = self.df.count() lowerCamelCase_ : List[Any] = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowerCamelCase_ : Any = ( self.df.limit(a_ ) .repartition(1 ) .mapInArrow(a_ , "batch_bytes: long" ) .agg(pyspark.sql.functions.sum("batch_bytes" ).alias("sample_bytes" ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowerCamelCase_ : int = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowerCamelCase_ : Union[str, Any] = min(a_ , int(approx_total_size / max_shard_size ) ) lowerCamelCase_ : int = self.df.repartition(a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , ): import pyspark lowerCamelCase_ : str = ParquetWriter if file_format == "parquet" else ArrowWriter lowerCamelCase_ : int = os.path.join(self._working_dir , os.path.basename(a_ ) ) if self._working_dir else fpath lowerCamelCase_ : Optional[Any] = file_format == "parquet" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowerCamelCase_ : int = self.config.features lowerCamelCase_ : Any = self._writer_batch_size lowerCamelCase_ : Tuple = self._fs.storage_options def write_arrow(a_ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowerCamelCase_ : List[Any] = pyspark.TaskContext().taskAttemptId() lowerCamelCase_ : Optional[int] = next(a_ , a_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["task_id", "num_examples", "num_bytes"] , ) lowerCamelCase_ : List[Any] = 0 lowerCamelCase_ : Optional[int] = writer_class( features=a_ , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=a_ , storage_options=a_ , embed_local_files=a_ , ) lowerCamelCase_ : Optional[Any] = pa.Table.from_batches([first_batch] ) writer.write_table(a_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowerCamelCase_ ,lowerCamelCase_ : List[str] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) shard_id += 1 lowerCamelCase_ : List[str] = writer_class( features=writer._features , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=a_ , storage_options=a_ , embed_local_files=a_ , ) lowerCamelCase_ : Optional[int] = pa.Table.from_batches([batch] ) writer.write_table(a_ ) if writer._num_bytes > 0: lowerCamelCase_ ,lowerCamelCase_ : Dict = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(a_ ) ): lowerCamelCase_ : str = os.path.join(os.path.dirname(a_ ) , os.path.basename(a_ ) ) shutil.move(a_ , a_ ) lowerCamelCase_ : int = ( self.df.mapInArrow(a_ , "task_id: long, num_examples: long, num_bytes: long" ) .groupBy("task_id" ) .agg( pyspark.sql.functions.sum("num_examples" ).alias("total_num_examples" ) , pyspark.sql.functions.sum("num_bytes" ).alias("total_num_bytes" ) , pyspark.sql.functions.count("num_bytes" ).alias("num_shards" ) , pyspark.sql.functions.collect_list("num_examples" ).alias("shard_lengths" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def _UpperCamelCase ( self , a_ , a_ = "arrow" , a_ = None , a_ = None , **a_ , ): self._validate_cache_dir() lowerCamelCase_ : Union[str, Any] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(a_ ) lowerCamelCase_ : Dict = not is_remote_filesystem(self._fs ) lowerCamelCase_ : List[str] = os.path.join if is_local else posixpath.join lowerCamelCase_ : Any = "-TTTTT-SSSSS-of-NNNNN" lowerCamelCase_ : List[Any] = F"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" lowerCamelCase_ : int = path_join(self._output_dir , a_ ) lowerCamelCase_ : int = 0 lowerCamelCase_ : Optional[Any] = 0 lowerCamelCase_ : int = 0 lowerCamelCase_ : Dict = [] lowerCamelCase_ : Any = [] for task_id, content in self._prepare_split_single(a_ , a_ , a_ ): ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) : Tuple = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(a_ ) lowerCamelCase_ : Dict = total_num_examples lowerCamelCase_ : Any = total_num_bytes # should rename everything at the end logger.debug(F"""Renaming {total_shards} shards.""" ) if total_shards > 1: lowerCamelCase_ : List[Any] = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowerCamelCase_ : Any = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a_ , a_ , a_ , ): rename( a_ , fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace("TTTTT-SSSSS" , F"""{global_shard_id:05d}""" ).replace("NNNNN" , F"""{total_shards:05d}""" ) , ) lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : Dict = 0 for i in range(len(a_ ) ): lowerCamelCase_ ,lowerCamelCase_ : Tuple = task_id_and_num_shards[i] for shard_id in range(a_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(a_ , len(a_ ) ).map(lambda a_ : _rename_shard(*a_ ) ).collect() else: # don't use any pattern lowerCamelCase_ : int = 0 lowerCamelCase_ : Optional[int] = task_id_and_num_shards[0][0] self._rename( fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace(a_ , "" ) , ) def _UpperCamelCase ( self , a_ , ): return SparkExamplesIterable(self.df )
73
1
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __magic_name__ = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Any = ['''input_values''', '''attention_mask'''] def __init__( self , a_ = 1 , a_ = 1_6000 , a_ = 0.0 , a_ = False , a_ = 80 , a_ = 16 , a_ = 64 , a_ = "hann_window" , a_ = 1.0 , a_ = 80 , a_ = 7600 , a_ = 1E-10 , a_ = 2 , a_ = True , **a_ , ): super().__init__(feature_size=a_ , sampling_rate=a_ , padding_value=a_ , **a_ ) lowerCamelCase_ : Dict = do_normalize lowerCamelCase_ : List[Any] = return_attention_mask lowerCamelCase_ : List[str] = num_mel_bins lowerCamelCase_ : Dict = hop_length lowerCamelCase_ : Union[str, Any] = win_length lowerCamelCase_ : int = win_function lowerCamelCase_ : Tuple = frame_signal_scale lowerCamelCase_ : Tuple = fmin lowerCamelCase_ : Union[str, Any] = fmax lowerCamelCase_ : List[str] = mel_floor lowerCamelCase_ : List[Any] = reduction_factor lowerCamelCase_ : Tuple = win_length * sampling_rate // 1000 lowerCamelCase_ : Optional[int] = hop_length * sampling_rate // 1000 lowerCamelCase_ : Any = optimal_fft_length(self.sample_size ) lowerCamelCase_ : int = (self.n_fft // 2) + 1 lowerCamelCase_ : str = window_function(window_length=self.sample_size , name=self.win_function , periodic=a_ ) lowerCamelCase_ : Any = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.num_mel_bins , min_frequency=self.fmin , max_frequency=self.fmax , sampling_rate=self.sampling_rate , norm="slaney" , mel_scale="slaney" , ) if frame_signal_scale != 1.0: warnings.warn( "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers" , a_ , ) if reduction_factor != 2.0: warnings.warn( "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers" , a_ , ) @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def _UpperCamelCase ( a_ , a_ , a_ = 0.0 ): if attention_mask is not None: lowerCamelCase_ : Optional[int] = np.array(a_ , np.intaa ) lowerCamelCase_ : List[Any] = [] for vector, length in zip(a_ , attention_mask.sum(-1 ) ): lowerCamelCase_ : List[Any] = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7 ) if length < normed_slice.shape[0]: lowerCamelCase_ : Union[str, Any] = padding_value normed_input_values.append(a_ ) else: lowerCamelCase_ : Optional[int] = [(x - x.mean()) / np.sqrt(x.var() + 1E-7 ) for x in input_values] return normed_input_values def _UpperCamelCase ( self , a_ , ): lowerCamelCase_ : Optional[Any] = spectrogram( a_ , window=self.window , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , mel_filters=self.mel_filters , mel_floor=self.mel_floor , log_mel="log10" , ) return log_mel_spec.T def __call__( self , a_ = None , a_ = None , a_ = False , a_ = None , a_ = False , a_ = None , a_ = None , a_ = None , a_ = None , **a_ , ): if audio is None and audio_target is None: raise ValueError("You must provide either `audio` or `audio_target` values." ) if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" F""" {self.sampling_rate}. Please make sure that the provided audio input was sampled with""" F""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( "It is strongly recommended to pass the ``sampling_rate`` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) if audio is not None: lowerCamelCase_ : List[str] = self._process_audio( a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , **a_ , ) else: lowerCamelCase_ : Union[str, Any] = None if audio_target is not None: lowerCamelCase_ : str = self._process_audio( a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , **a_ , ) if inputs is None: return inputs_target else: lowerCamelCase_ : Optional[Any] = inputs_target["input_values"] lowerCamelCase_ : Union[str, Any] = inputs_target.get("attention_mask" ) if decoder_attention_mask is not None: lowerCamelCase_ : Optional[int] = decoder_attention_mask return inputs def _UpperCamelCase ( self , a_ , a_ = False , a_ = False , a_ = None , a_ = False , a_ = None , a_ = None , a_ = None , **a_ , ): lowerCamelCase_ : Optional[int] = isinstance(a_ , np.ndarray ) and len(speech.shape ) > 1 if is_batched_numpy and len(speech.shape ) > 2: raise ValueError(F"""Only mono-channel audio is supported for input to {self}""" ) lowerCamelCase_ : str = is_batched_numpy or ( isinstance(a_ , (list, tuple) ) and (isinstance(speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCamelCase_ : Optional[int] = [np.asarray(a_ , dtype=np.floataa ) for speech in speech] elif not is_batched and not isinstance(a_ , np.ndarray ): lowerCamelCase_ : Any = np.asarray(a_ , dtype=np.floataa ) elif isinstance(a_ , np.ndarray ) and speech.dtype is np.dtype(np.floataa ): lowerCamelCase_ : Optional[Any] = speech.astype(np.floataa ) # always return batch if not is_batched: lowerCamelCase_ : str = [speech] # needed to make pad() work on spectrogram inputs lowerCamelCase_ : Dict = self.feature_size # convert into correct format for padding if is_target: lowerCamelCase_ : Optional[Any] = [self._extract_mel_features(a_ ) for waveform in speech] lowerCamelCase_ : Dict = BatchFeature({"input_values": features} ) lowerCamelCase_ : str = self.num_mel_bins else: lowerCamelCase_ : List[Any] = BatchFeature({"input_values": speech} ) lowerCamelCase_ : Dict = self.pad( a_ , padding=a_ , max_length=a_ , truncation=a_ , pad_to_multiple_of=a_ , return_attention_mask=a_ , **a_ , ) lowerCamelCase_ : Optional[Any] = feature_size_hack # convert input values to correct format lowerCamelCase_ : Union[str, Any] = padded_inputs["input_values"] if not isinstance(input_values[0] , np.ndarray ): lowerCamelCase_ : Any = [np.asarray(a_ , dtype=np.floataa ) for array in input_values] elif ( not isinstance(a_ , np.ndarray ) and isinstance(input_values[0] , np.ndarray ) and input_values[0].dtype is np.dtype(np.floataa ) ): lowerCamelCase_ : List[str] = [array.astype(np.floataa ) for array in input_values] elif isinstance(a_ , np.ndarray ) and input_values.dtype is np.dtype(np.floataa ): lowerCamelCase_ : List[Any] = input_values.astype(np.floataa ) # convert attention_mask to correct format lowerCamelCase_ : Optional[Any] = padded_inputs.get("attention_mask" ) if attention_mask is not None: lowerCamelCase_ : int = [np.asarray(a_ , dtype=np.intaa ) for array in attention_mask] # zero-mean and unit-variance normalization if not is_target and self.do_normalize: lowerCamelCase_ : Any = ( attention_mask if self._get_padding_strategies(a_ , max_length=a_ ) is not PaddingStrategy.DO_NOT_PAD else None ) lowerCamelCase_ : Tuple = self.zero_mean_unit_var_norm( padded_inputs["input_values"] , attention_mask=a_ , padding_value=self.padding_value ) if return_tensors is not None: lowerCamelCase_ : int = padded_inputs.convert_to_tensors(a_ ) return padded_inputs def _UpperCamelCase ( self ): lowerCamelCase_ : int = super().to_dict() # Don't serialize these as they are derived from the other properties. lowerCamelCase_ : Optional[int] = ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"] for name in names: if name in output: del output[name] return output
73
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue lowerCamelCase_ : List[str] = cst_fwd.get(lowerCAmelCase_ , np.inf) lowerCamelCase_ : Dict = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt)) lowerCamelCase_ : Optional[int] = new_cost_f lowerCamelCase_ : List[str] = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: lowerCamelCase_ : Tuple = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : Optional[Any] = -1 lowerCamelCase_ : Tuple = set() lowerCamelCase_ : Dict = set() lowerCamelCase_ : int = {source: 0} lowerCamelCase_ : str = {destination: 0} lowerCamelCase_ : Tuple = {source: None} lowerCamelCase_ : Dict = {destination: None} lowerCamelCase_ : PriorityQueue[Any] = PriorityQueue() lowerCamelCase_ : PriorityQueue[Any] = PriorityQueue() lowerCamelCase_ : List[str] = np.inf queue_forward.put((0, source)) queue_backward.put((0, destination)) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): lowerCamelCase_ ,lowerCamelCase_ : List[Any] = queue_forward.get() visited_forward.add(lowerCAmelCase_) lowerCamelCase_ ,lowerCamelCase_ : str = queue_backward.get() visited_backward.add(lowerCAmelCase_) lowerCamelCase_ : Any = pass_and_relaxation( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) lowerCamelCase_ : Dict = pass_and_relaxation( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: lowerCamelCase_ : Union[str, Any] = shortest_distance return shortest_path_distance __magic_name__ = { '''B''': [['''C''', 1]], '''C''': [['''D''', 1]], '''D''': [['''F''', 1]], '''E''': [['''B''', 1], ['''G''', 2]], '''F''': [], '''G''': [['''F''', 1]], } __magic_name__ = { '''B''': [['''E''', 1]], '''C''': [['''B''', 1]], '''D''': [['''C''', 1]], '''F''': [['''D''', 1], ['''G''', 1]], '''E''': [[None, np.inf]], '''G''': [['''E''', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
73
1
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : int = int(number**0.5) return number == sq * sq def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den lowerCamelCase_ : int = x_den * y_den * z_den lowerCamelCase_ : int = gcd(lowerCAmelCase_ , lowerCAmelCase_) top //= hcf bottom //= hcf return top, bottom def __magic_name__ ( lowerCAmelCase_ = 35): '''simple docstring''' lowerCamelCase_ : set = set() lowerCamelCase_ : int lowerCamelCase_ : Fraction = Fraction(0) lowerCamelCase_ : tuple[int, int] for x_num in range(1 , order + 1): for x_den in range(x_num + 1 , order + 1): for y_num in range(1 , order + 1): for y_den in range(y_num + 1 , order + 1): # n=1 lowerCamelCase_ : Any = x_num * y_den + x_den * y_num lowerCamelCase_ : int = x_den * y_den lowerCamelCase_ : List[Any] = gcd(lowerCAmelCase_ , lowerCAmelCase_) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowerCamelCase_ : str = add_three( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) unique_s.add(lowerCAmelCase_) # n=2 lowerCamelCase_ : int = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) lowerCamelCase_ : Tuple = x_den * x_den * y_den * y_den if is_sq(lowerCAmelCase_) and is_sq(lowerCAmelCase_): lowerCamelCase_ : Union[str, Any] = int(sqrt(lowerCAmelCase_)) lowerCamelCase_ : Any = int(sqrt(lowerCAmelCase_)) lowerCamelCase_ : int = gcd(lowerCAmelCase_ , lowerCAmelCase_) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowerCamelCase_ : Union[str, Any] = add_three( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) unique_s.add(lowerCAmelCase_) # n=-1 lowerCamelCase_ : Optional[int] = x_num * y_num lowerCamelCase_ : str = x_den * y_num + x_num * y_den lowerCamelCase_ : Dict = gcd(lowerCAmelCase_ , lowerCAmelCase_) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowerCamelCase_ : Any = add_three( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) unique_s.add(lowerCAmelCase_) # n=2 lowerCamelCase_ : Any = x_num * x_num * y_num * y_num lowerCamelCase_ : List[str] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(lowerCAmelCase_) and is_sq(lowerCAmelCase_): lowerCamelCase_ : Tuple = int(sqrt(lowerCAmelCase_)) lowerCamelCase_ : str = int(sqrt(lowerCAmelCase_)) lowerCamelCase_ : Any = gcd(lowerCAmelCase_ , lowerCAmelCase_) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowerCamelCase_ : List[str] = add_three( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) unique_s.add(lowerCAmelCase_) for num, den in unique_s: total += Fraction(lowerCAmelCase_ , lowerCAmelCase_) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''ctrl''' __UpperCAmelCase : Dict = ['''past_key_values'''] __UpperCAmelCase : int = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a_=24_6534 , a_=256 , a_=1280 , a_=8192 , a_=48 , a_=16 , a_=0.1 , a_=0.1 , a_=1E-6 , a_=0.02 , a_=True , **a_ , ): lowerCamelCase_ : Dict = vocab_size lowerCamelCase_ : Any = n_positions lowerCamelCase_ : Optional[int] = n_embd lowerCamelCase_ : List[Any] = n_layer lowerCamelCase_ : Union[str, Any] = n_head lowerCamelCase_ : str = dff lowerCamelCase_ : Tuple = resid_pdrop lowerCamelCase_ : Any = embd_pdrop lowerCamelCase_ : Dict = layer_norm_epsilon lowerCamelCase_ : Tuple = initializer_range lowerCamelCase_ : Any = use_cache super().__init__(**a_ )
73
1
from __future__ import annotations def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : list[list[int]] = [] create_all_state(1 , lowerCAmelCase_ , lowerCAmelCase_ , [] , lowerCAmelCase_) return result def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' if level == 0: total_list.append(current_list[:]) return for i in range(lowerCAmelCase_ , total_number - level + 2): current_list.append(lowerCAmelCase_) create_all_state(i + 1 , lowerCAmelCase_ , level - 1 , lowerCAmelCase_ , lowerCAmelCase_) current_list.pop() def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' for i in total_list: print(*lowerCAmelCase_) if __name__ == "__main__": __magic_name__ = 4 __magic_name__ = 2 __magic_name__ = generate_all_combinations(n, k) print_all_state(total_list)
73
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __magic_name__ = logging.getLogger(__name__) __magic_name__ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __magic_name__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) }, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(__lowerCamelCase )}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) }, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''}, ) __UpperCAmelCase : str = field( default='''main''', metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) }, ) def _UpperCamelCase ( self ): if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can't be used in combination with --config_name or --model_name_or_path" ) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field(default=__lowerCamelCase, metadata={'''help''': '''The input training data file (a text file).'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) __UpperCAmelCase : Optional[int] = field( default=5, metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' }, ) __UpperCAmelCase : Optional[int] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) }, ) __UpperCAmelCase : Optional[int] = field( default=__lowerCamelCase, metadata={'''help''': '''The number of processes to use for the preprocessing.'''}, ) __UpperCAmelCase : float = field( default=0.15, metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) }, ) def _UpperCamelCase ( self ): if self.train_file is not None: lowerCamelCase_ : str = self.train_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: lowerCamelCase_ : Union[str, Any] = self.validation_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' with open(lowerCAmelCase_ , "r" , encoding="utf-8") as f: lowerCamelCase_ : Tuple = [json.loads(lowerCAmelCase_) for line in f.read().splitlines() if (len(lowerCAmelCase_) > 0 and not line.isspace())] assert len(lowerCAmelCase_) == len(lowerCAmelCase_) lowerCamelCase_ : Any = {c: dataset[c] for c in dataset.column_names} lowerCamelCase_ : List[Any] = refs return Dataset.from_dict(lowerCAmelCase_) def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowerCamelCase_ : List[str] = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: lowerCamelCase_ : Dict = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome.") elif last_checkpoint is not None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch.") # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}""") # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowerCamelCase_ : Optional[int] = load_dataset(data_args.dataset_name , data_args.dataset_config_name) if "validation" not in datasets.keys(): lowerCamelCase_ : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[:{data_args.validation_split_percentage}%]""" , ) lowerCamelCase_ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[{data_args.validation_split_percentage}%:]""" , ) else: lowerCamelCase_ : Dict = {} if data_args.train_file is not None: lowerCamelCase_ : str = data_args.train_file if data_args.validation_file is not None: lowerCamelCase_ : Any = data_args.validation_file lowerCamelCase_ : Any = data_args.train_file.split(".")[-1] if extension == "txt": lowerCamelCase_ : List[str] = "text" lowerCamelCase_ : Dict = load_dataset(lowerCAmelCase_ , data_files=lowerCAmelCase_) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase_ : Optional[Any] = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: lowerCamelCase_ : Optional[Any] = AutoConfig.from_pretrained(model_args.config_name , **lowerCAmelCase_) elif model_args.model_name_or_path: lowerCamelCase_ : str = AutoConfig.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase_) else: lowerCamelCase_ : Optional[int] = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch.") if model_args.config_overrides is not None: logger.info(F"""Overriding config: {model_args.config_overrides}""") config.update_from_string(model_args.config_overrides) logger.info(F"""New config: {config}""") lowerCamelCase_ : List[str] = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: lowerCamelCase_ : str = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **lowerCAmelCase_) elif model_args.model_name_or_path: lowerCamelCase_ : Dict = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase_) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name.") if model_args.model_name_or_path: lowerCamelCase_ : Union[str, Any] = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch") lowerCamelCase_ : Dict = AutoModelForMaskedLM.from_config(lowerCAmelCase_) model.resize_token_embeddings(len(lowerCAmelCase_)) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: lowerCamelCase_ : Optional[Any] = datasets["train"].column_names else: lowerCamelCase_ : Dict = datasets["validation"].column_names lowerCamelCase_ : Union[str, Any] = "text" if "text" in column_names else column_names[0] lowerCamelCase_ : Optional[Any] = "max_length" if data_args.pad_to_max_length else False def tokenize_function(lowerCAmelCase_): # Remove empty lines lowerCamelCase_ : str = [line for line in examples["text"] if len(lowerCAmelCase_) > 0 and not line.isspace()] return tokenizer(examples["text"] , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=data_args.max_seq_length) lowerCamelCase_ : str = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: lowerCamelCase_ : List[Any] = add_chinese_references(tokenized_datasets["train"] , data_args.train_ref_file) if data_args.validation_ref_file is not None: lowerCamelCase_ : List[str] = add_chinese_references( tokenized_datasets["validation"] , data_args.validation_ref_file) # If we have ref files, need to avoid it removed by trainer lowerCamelCase_ : Optional[Any] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: lowerCamelCase_ : Union[str, Any] = False # Data collator # This one will take care of randomly masking the tokens. lowerCamelCase_ : Optional[Any] = DataCollatorForWholeWordMask(tokenizer=lowerCAmelCase_ , mlm_probability=data_args.mlm_probability) # Initialize our Trainer lowerCamelCase_ : int = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=tokenized_datasets["train"] if training_args.do_train else None , eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: if last_checkpoint is not None: lowerCamelCase_ : Dict = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path): lowerCamelCase_ : Dict = model_args.model_name_or_path else: lowerCamelCase_ : int = None lowerCamelCase_ : Optional[Any] = trainer.train(resume_from_checkpoint=lowerCAmelCase_) trainer.save_model() # Saves the tokenizer too for easy upload lowerCamelCase_ : Tuple = os.path.join(training_args.output_dir , "train_results.txt") if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w") as writer: logger.info("***** Train results *****") for key, value in sorted(train_result.metrics.items()): logger.info(F""" {key} = {value}""") writer.write(F"""{key} = {value}\n""") # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json")) # Evaluation lowerCamelCase_ : Dict = {} if training_args.do_eval: logger.info("*** Evaluate ***") lowerCamelCase_ : Tuple = trainer.evaluate() lowerCamelCase_ : str = math.exp(eval_output["eval_loss"]) lowerCamelCase_ : Tuple = perplexity lowerCamelCase_ : int = os.path.join(training_args.output_dir , "eval_results_mlm_wwm.txt") if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w") as writer: logger.info("***** Eval results *****") for key, value in sorted(results.items()): logger.info(F""" {key} = {value}""") writer.write(F"""{key} = {value}\n""") return results def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' main() if __name__ == "__main__": main()
73
1
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ : """simple docstring""" def __init__( self , a_ , a_=13 , a_=32 , a_=3 , a_=4 , a_=[10, 20, 30, 40] , a_=[2, 2, 3, 2] , a_=True , a_=True , a_=37 , a_="gelu" , a_=10 , a_=0.02 , a_=["stage2", "stage3", "stage4"] , a_=[2, 3, 4] , a_=None , ): lowerCamelCase_ : Optional[Any] = parent lowerCamelCase_ : int = batch_size lowerCamelCase_ : List[str] = image_size lowerCamelCase_ : Optional[Any] = num_channels lowerCamelCase_ : Optional[int] = num_stages lowerCamelCase_ : List[Any] = hidden_sizes lowerCamelCase_ : Optional[Any] = depths lowerCamelCase_ : int = is_training lowerCamelCase_ : Any = use_labels lowerCamelCase_ : Optional[Any] = intermediate_size lowerCamelCase_ : List[str] = hidden_act lowerCamelCase_ : List[Any] = num_labels lowerCamelCase_ : List[str] = initializer_range lowerCamelCase_ : str = out_features lowerCamelCase_ : Dict = out_indices lowerCamelCase_ : Any = scope def _UpperCamelCase ( self ): lowerCamelCase_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ : List[Any] = None if self.use_labels: lowerCamelCase_ : int = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase_ : List[str] = self.get_config() return config, pixel_values, labels def _UpperCamelCase ( self ): return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=a_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def _UpperCamelCase ( self , a_ , a_ , a_ ): lowerCamelCase_ : int = ConvNextModel(config=a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : Optional[Any] = model(a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _UpperCamelCase ( self , a_ , a_ , a_ ): lowerCamelCase_ : List[str] = ConvNextForImageClassification(a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self , a_ , a_ , a_ ): lowerCamelCase_ : Optional[int] = ConvNextBackbone(config=a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : Optional[Any] = model(a_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None lowerCamelCase_ : Tuple = None lowerCamelCase_ : List[Any] = ConvNextBackbone(config=a_ ) model.to(a_ ) model.eval() lowerCamelCase_ : Optional[int] = model(a_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = self.prepare_config_and_inputs() lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Union[str, Any] = config_and_inputs lowerCamelCase_ : Union[str, Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[str] = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase : int = True __UpperCAmelCase : List[str] = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Tuple = False __UpperCAmelCase : Optional[Any] = False def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = ConvNextModelTester(self ) lowerCamelCase_ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def _UpperCamelCase ( self ): 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 _UpperCamelCase ( self ): return @unittest.skip(reason="ConvNext does not use inputs_embeds" ) def _UpperCamelCase ( self ): pass @unittest.skip(reason="ConvNext does not support input and output embeddings" ) def _UpperCamelCase ( self ): pass @unittest.skip(reason="ConvNext does not use feedforward chunking" ) def _UpperCamelCase ( self ): pass def _UpperCamelCase ( self ): lowerCamelCase_ ,lowerCamelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ : Union[str, Any] = model_class(a_ ) lowerCamelCase_ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ : Union[str, Any] = [*signature.parameters.keys()] lowerCamelCase_ : Any = ["pixel_values"] self.assertListEqual(arg_names[:1] , a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*a_ ) def _UpperCamelCase ( self ): def check_hidden_states_output(a_ , a_ , a_ ): lowerCamelCase_ : Optional[Any] = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): lowerCamelCase_ : Tuple = model(**self._prepare_for_class(a_ , a_ ) ) lowerCamelCase_ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ : int = self.model_tester.num_stages self.assertEqual(len(a_ ) , 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] , ) lowerCamelCase_ ,lowerCamelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ : List[str] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ : Dict = True check_hidden_states_output(a_ , a_ , a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def _UpperCamelCase ( self ): for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ : Any = ConvNextModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def _UpperCamelCase ( self ): return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224" ) if is_vision_available() else None @slow def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224" ).to(a_ ) lowerCamelCase_ : Optional[int] = self.default_image_processor lowerCamelCase_ : Tuple = prepare_img() lowerCamelCase_ : List[str] = image_processor(images=a_ , return_tensors="pt" ).to(a_ ) # forward pass with torch.no_grad(): lowerCamelCase_ : str = model(**a_ ) # verify the logits lowerCamelCase_ : Tuple = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) lowerCamelCase_ : List[str] = torch.tensor([-0.02_60, -0.47_39, 0.19_11] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1E-4 ) ) @require_torch class lowerCAmelCase__ ( unittest.TestCase, __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = (ConvNextBackbone,) if is_torch_available() else () __UpperCAmelCase : Dict = ConvNextConfig __UpperCAmelCase : List[Any] = False def _UpperCamelCase ( self ): lowerCamelCase_ : Any = ConvNextModelTester(self )
73
from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class lowerCAmelCase__ : """simple docstring""" # setable values __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[jnp.ndarray] = None __UpperCAmelCase : Optional[jnp.ndarray] = None # sigma(t_i) @classmethod def _UpperCamelCase ( cls ): return cls() @dataclass class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : KarrasVeSchedulerState class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase ): """simple docstring""" @property def _UpperCamelCase ( self ): return True @register_to_config def __init__( self , a_ = 0.02 , a_ = 100 , a_ = 1.0_07 , a_ = 80 , a_ = 0.05 , a_ = 50 , ): pass def _UpperCamelCase ( self ): return KarrasVeSchedulerState.create() def _UpperCamelCase ( self , a_ , a_ , a_ = () ): lowerCamelCase_ : List[Any] = jnp.arange(0 , a_ )[::-1].copy() lowerCamelCase_ : List[str] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=a_ , schedule=jnp.array(a_ , dtype=jnp.floataa ) , timesteps=a_ , ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , ): if self.config.s_min <= sigma <= self.config.s_max: lowerCamelCase_ : Union[str, Any] = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: lowerCamelCase_ : Optional[int] = 0 # sample eps ~ N(0, S_noise^2 * I) lowerCamelCase_ : Union[str, Any] = random.split(a_ , num=1 ) lowerCamelCase_ : str = self.config.s_noise * random.normal(key=a_ , shape=sample.shape ) lowerCamelCase_ : List[str] = sigma + gamma * sigma lowerCamelCase_ : Tuple = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ = True , ): lowerCamelCase_ : List[str] = sample_hat + sigma_hat * model_output lowerCamelCase_ : Union[str, Any] = (sample_hat - pred_original_sample) / sigma_hat lowerCamelCase_ : Union[str, Any] = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=a_ , derivative=a_ , state=a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ = True , ): lowerCamelCase_ : Optional[Any] = sample_prev + sigma_prev * model_output lowerCamelCase_ : Any = (sample_prev - pred_original_sample) / sigma_prev lowerCamelCase_ : Optional[int] = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=a_ , derivative=a_ , state=a_ ) def _UpperCamelCase ( self , a_ , a_ , a_ , a_ ): raise NotImplementedError()
73
1
from __future__ import annotations __magic_name__ = 1_0 def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : int = 1 lowerCamelCase_ : Dict = max(lowerCAmelCase_) while placement <= max_digit: # declare and initialize empty buckets lowerCamelCase_ : list[list] = [[] for _ in range(lowerCAmelCase_)] # split list_of_ints between the buckets for i in list_of_ints: lowerCamelCase_ : int = int((i / placement) % RADIX) buckets[tmp].append(lowerCAmelCase_) # put each buckets' contents into list_of_ints lowerCamelCase_ : int = 0 for b in range(lowerCAmelCase_): for i in buckets[b]: lowerCamelCase_ : str = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
73
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = StableDiffusionDiffEditPipeline __UpperCAmelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} __UpperCAmelCase : Any = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} __UpperCAmelCase : List[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __UpperCAmelCase : List[str] = frozenset([] ) def _UpperCamelCase ( self ): torch.manual_seed(0 ) lowerCamelCase_ : str = 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 , attention_head_dim=(2, 4) , use_linear_projection=a_ , ) lowerCamelCase_ : str = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , ) lowerCamelCase_ : Dict = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_zero=a_ , ) torch.manual_seed(0 ) lowerCamelCase_ : List[Any] = 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 ) lowerCamelCase_ : Union[str, 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 , ) lowerCamelCase_ : Optional[Any] = CLIPTextModel(a_ ) lowerCamelCase_ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCamelCase_ : Optional[Any] = { "unet": unet, "scheduler": scheduler, "inverse_scheduler": inverse_scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : str = floats_tensor((1, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : List[Any] = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a_ ) ).to(a_ ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : List[Any] = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[str] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Tuple = { "prompt": "a dog and a newt", "mask_image": mask, "image_latents": latents, "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Any = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Tuple = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : int = { "image": image, "source_prompt": "a cat and a frog", "target_prompt": "a dog and a newt", "generator": generator, "num_inference_steps": 2, "num_maps_per_mask": 2, "mask_encode_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _UpperCamelCase ( self , a_ , a_=0 ): lowerCamelCase_ : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) lowerCamelCase_ : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ : Optional[int] = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ) if str(a_ ).startswith("mps" ): lowerCamelCase_ : Optional[int] = torch.manual_seed(a_ ) else: lowerCamelCase_ : Tuple = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Union[str, Any] = { "image": image, "prompt": "a cat and a frog", "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "decode_latents": True, "output_type": "numpy", } return inputs def _UpperCamelCase ( self ): if not hasattr(self.pipeline_class , "_optional_components" ): return lowerCamelCase_ : List[Any] = self.get_dummy_components() lowerCamelCase_ : int = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a_ , a_ , a_ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) lowerCamelCase_ : int = self.get_dummy_inputs(a_ ) lowerCamelCase_ : int = pipe(**a_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a_ ) lowerCamelCase_ : Optional[int] = self.pipeline_class.from_pretrained(a_ ) pipe_loaded.to(a_ ) pipe_loaded.set_progress_bar_config(disable=a_ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(a_ , a_ ) is None , F"""`{optional_component}` did not stay set to None after loading.""" , ) lowerCamelCase_ : List[str] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Optional[int] = pipe_loaded(**a_ )[0] lowerCamelCase_ : Optional[int] = np.abs(output - output_loaded ).max() self.assertLess(a_ , 1E-4 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : List[Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = self.get_dummy_mask_inputs(a_ ) lowerCamelCase_ : int = pipe.generate_mask(**a_ ) lowerCamelCase_ : List[Any] = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) lowerCamelCase_ : List[str] = np.array([0] * 9 ) lowerCamelCase_ : Optional[int] = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" lowerCamelCase_ : Union[str, Any] = self.get_dummy_components() lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Dict = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : Dict = pipe.invert(**a_ ).images lowerCamelCase_ : str = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Dict = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : Any = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) def _UpperCamelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = "cpu" lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : int = {"beta_start": 0.0_00_85, "beta_end": 0.0_12, "beta_schedule": "scaled_linear"} lowerCamelCase_ : Optional[Any] = DPMSolverMultistepScheduler(**a_ ) lowerCamelCase_ : List[str] = DPMSolverMultistepInverseScheduler(**a_ ) lowerCamelCase_ : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : int = self.get_dummy_inversion_inputs(a_ ) lowerCamelCase_ : str = pipe.invert(**a_ ).images lowerCamelCase_ : int = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) lowerCamelCase_ : Union[str, Any] = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) lowerCamelCase_ : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1E-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def _UpperCamelCase ( cls ): lowerCamelCase_ : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png" ) lowerCamelCase_ : int = raw_image.convert("RGB" ).resize((768, 768) ) lowerCamelCase_ : List[Any] = raw_image def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = torch.manual_seed(0 ) lowerCamelCase_ : Tuple = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : str = DDIMScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : Optional[int] = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : str = "a bowl of fruit" lowerCamelCase_ : Optional[int] = "a bowl of pears" lowerCamelCase_ : List[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ ).latents lowerCamelCase_ : List[str] = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[Any] = torch.manual_seed(0 ) lowerCamelCase_ : str = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=a_ , torch_dtype=torch.floataa ) lowerCamelCase_ : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) lowerCamelCase_ : str = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Any = "a bowl of fruit" lowerCamelCase_ : Dict = "a bowl of pears" lowerCamelCase_ : Optional[Any] = pipe.generate_mask( image=self.raw_image , source_prompt=a_ , target_prompt=a_ , generator=a_ , ) lowerCamelCase_ : str = pipe.invert( prompt=a_ , image=self.raw_image , inpaint_strength=0.7 , generator=a_ , num_inference_steps=25 , ).latents lowerCamelCase_ : Any = pipe( prompt=a_ , mask_image=a_ , image_latents=a_ , generator=a_ , negative_prompt=a_ , inpaint_strength=0.7 , num_inference_steps=25 , output_type="numpy" , ).images[0] lowerCamelCase_ : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''google/canine-s''': '''https://huggingface.co/google/canine-s/resolve/main/config.json''', # See all CANINE models at https://huggingface.co/models?filter=canine } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''canine''' def __init__( self , a_=768 , a_=12 , a_=12 , a_=3072 , a_="gelu" , a_=0.1 , a_=0.1 , a_=1_6384 , a_=16 , a_=0.02 , a_=1E-12 , a_=0 , a_=0Xe000 , a_=0Xe001 , a_=4 , a_=4 , a_=8 , a_=1_6384 , a_=128 , **a_ , ): super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) lowerCamelCase_ : Dict = max_position_embeddings lowerCamelCase_ : List[Any] = hidden_size lowerCamelCase_ : str = num_hidden_layers lowerCamelCase_ : Optional[int] = num_attention_heads lowerCamelCase_ : List[str] = intermediate_size lowerCamelCase_ : Tuple = hidden_act lowerCamelCase_ : Any = hidden_dropout_prob lowerCamelCase_ : Any = attention_probs_dropout_prob lowerCamelCase_ : List[Any] = initializer_range lowerCamelCase_ : Union[str, Any] = type_vocab_size lowerCamelCase_ : List[str] = layer_norm_eps # Character config: lowerCamelCase_ : List[Any] = downsampling_rate lowerCamelCase_ : Union[str, Any] = upsampling_kernel_size lowerCamelCase_ : Optional[Any] = num_hash_functions lowerCamelCase_ : str = num_hash_buckets lowerCamelCase_ : int = local_transformer_stride
73
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : int = ["a", "b", "c"] # Defaults to last layer if both are None lowerCamelCase_ ,lowerCamelCase_ : Tuple = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ["c"] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = get_aligned_output_features_output_indices(["a", "c"] , a_ , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices lowerCamelCase_ ,lowerCamelCase_ : Tuple = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices lowerCamelCase_ ,lowerCamelCase_ : Dict = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [-3, -1] ) def _UpperCamelCase ( self ): # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = BackboneMixin() lowerCamelCase_ : List[Any] = ["a", "b", "c"] lowerCamelCase_ : Optional[int] = ["a", "c"] lowerCamelCase_ : Dict = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly lowerCamelCase_ : Union[str, Any] = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) lowerCamelCase_ : str = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
73
1
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ , a_ ): super().__init__() self.register_modules(vqvae=a_ , unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self , a_ = 1 , a_ = None , a_ = 0.0 , a_ = 50 , a_ = "pil" , a_ = True , **a_ , ): lowerCamelCase_ : Optional[Any] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=a_ , ) lowerCamelCase_ : Optional[int] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ : Optional[int] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(a_ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature lowerCamelCase_ : Any = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ : Optional[int] = {} if accepts_eta: lowerCamelCase_ : Optional[int] = eta for t in self.progress_bar(self.scheduler.timesteps ): lowerCamelCase_ : Dict = self.scheduler.scale_model_input(a_ , a_ ) # predict the noise residual lowerCamelCase_ : Optional[Any] = self.unet(a_ , a_ ).sample # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ : List[Any] = self.scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample # decode the image latents with the VAE lowerCamelCase_ : str = self.vqvae.decode(a_ ).sample lowerCamelCase_ : Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) lowerCamelCase_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase_ : Optional[Any] = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
73
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase : Union[str, Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase : Tuple = ['''accelerate''', '''launch'''] __UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase : int = '''default_config.yaml''' __UpperCAmelCase : Tuple = config_folder / config_file __UpperCAmelCase : int = config_folder / '''_default_config.yaml''' __UpperCAmelCase : int = Path('''tests/test_configs''' ) @classmethod def _UpperCamelCase ( cls ): if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def _UpperCamelCase ( cls ): if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def _UpperCamelCase ( self ): for config in sorted(self.test_config_path.glob("**/*.yaml" ) ): with self.subTest(config_file=a_ ): execute_subprocess_async( self.base_cmd + ["--config_file", str(a_ ), self.test_file_path] , env=os.environ.copy() ) def _UpperCamelCase ( self ): execute_subprocess_async(["accelerate", "test"] , env=os.environ.copy() ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[Any] = '''test-tpu''' __UpperCAmelCase : Tuple = '''us-central1-a''' __UpperCAmelCase : Tuple = '''ls''' __UpperCAmelCase : str = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase : Dict = '''cd /usr/share''' __UpperCAmelCase : Any = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase : Dict = '''Running gcloud compute tpus tpu-vm ssh''' def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + ["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Union[str, Any] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--debug"] , return_stdout=a_ ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--command", "echo \"Hello World\"", "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Dict = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command_file", self.command_file, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : str = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , ) def _UpperCamelCase ( self ): lowerCamelCase_ : Any = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--accelerate_version", "12.0.0", "--debug", ] , return_stdout=a_ , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , a_ , )
73
1
__magic_name__ = '''Alexander Joslin''' import operator as op from .stack import Stack def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : str = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} lowerCamelCase_ : Stack[int] = Stack() lowerCamelCase_ : Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(lowerCAmelCase_)) elif i in operators: # RULE 2 operator_stack.push(lowerCAmelCase_) elif i == ")": # RULE 4 lowerCamelCase_ : Any = operator_stack.peek() operator_stack.pop() lowerCamelCase_ : Dict = operand_stack.peek() operand_stack.pop() lowerCamelCase_ : Dict = operand_stack.peek() operand_stack.pop() lowerCamelCase_ : Optional[Any] = operators[opr](lowerCAmelCase_ , lowerCAmelCase_) operand_stack.push(lowerCAmelCase_) # RULE 5 return operand_stack.peek() if __name__ == "__main__": __magic_name__ = '''(5 + ((4 * 2) * (2 + 3)))''' # answer = 45 print(f'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
73
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , a_ , a_ , a_ ): super().__init__() self.register_modules(vqvae=a_ , unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self , a_ = 1 , a_ = None , a_ = 0.0 , a_ = 50 , a_ = "pil" , a_ = True , **a_ , ): lowerCamelCase_ : Optional[Any] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=a_ , ) lowerCamelCase_ : Optional[int] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ : Optional[int] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(a_ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature lowerCamelCase_ : Any = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ : Optional[int] = {} if accepts_eta: lowerCamelCase_ : Optional[int] = eta for t in self.progress_bar(self.scheduler.timesteps ): lowerCamelCase_ : Dict = self.scheduler.scale_model_input(a_ , a_ ) # predict the noise residual lowerCamelCase_ : Optional[Any] = self.unet(a_ , a_ ).sample # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ : List[Any] = self.scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample # decode the image latents with the VAE lowerCamelCase_ : str = self.vqvae.decode(a_ ).sample lowerCamelCase_ : Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) lowerCamelCase_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase_ : Optional[Any] = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
73
1
def __magic_name__ ( lowerCAmelCase_ = 50): '''simple docstring''' lowerCamelCase_ : Union[str, Any] = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2 , 5): for tile_start in range(row_length - tile_length + 1): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length]) if __name__ == "__main__": print(f'''{solution() = }''')
73
import re def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if len(re.findall("[ATCG]" , lowerCAmelCase_)) != len(lowerCAmelCase_): raise ValueError("Invalid Strand") return dna.translate(dna.maketrans("ATCG" , "TAGC")) if __name__ == "__main__": import doctest doctest.testmod()
73
1
__magic_name__ = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/''' def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_): lowerCamelCase_ : Optional[int] = F"""a bytes-like object is required, not '{data.__class__.__name__}'""" raise TypeError(lowerCAmelCase_) lowerCamelCase_ : Optional[Any] = "".join(bin(lowerCAmelCase_)[2:].zfill(8) for byte in data) lowerCamelCase_ : int = len(lowerCAmelCase_) % 6 != 0 if padding_needed: # The padding that will be added later lowerCamelCase_ : int = b"=" * ((6 - len(lowerCAmelCase_) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase_) % 6) else: lowerCamelCase_ : Any = b"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2)] for index in range(0 , len(lowerCAmelCase_) , 6)).encode() + padding ) def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_) and not isinstance(lowerCAmelCase_ , lowerCAmelCase_): lowerCamelCase_ : List[str] = ( "argument should be a bytes-like object or ASCII string, " F"""not '{encoded_data.__class__.__name__}'""" ) raise TypeError(lowerCAmelCase_) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase_ , lowerCAmelCase_): try: lowerCamelCase_ : Optional[int] = encoded_data.decode("utf-8") except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters") lowerCamelCase_ : int = encoded_data.count("=") # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding]), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase_) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one lowerCamelCase_ : List[str] = encoded_data[:-padding] lowerCamelCase_ : List[Any] = "".join( bin(B64_CHARSET.index(lowerCAmelCase_))[2:].zfill(6) for char in encoded_data)[: -padding * 2] else: lowerCamelCase_ : List[str] = "".join( bin(B64_CHARSET.index(lowerCAmelCase_))[2:].zfill(6) for char in encoded_data) lowerCamelCase_ : List[Any] = [ int(binary_stream[index : index + 8] , 2) for index in range(0 , len(lowerCAmelCase_) , 8) ] return bytes(lowerCAmelCase_) if __name__ == "__main__": import doctest doctest.testmod()
73
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False): '''simple docstring''' if radian_mode: return [magnitude * cos(lowerCAmelCase_), magnitude * sin(lowerCAmelCase_)] return [magnitude * cos(radians(lowerCAmelCase_)), magnitude * sin(radians(lowerCAmelCase_))] def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 10**-1): '''simple docstring''' lowerCamelCase_ : NDArray[floataa] = cross(lowerCAmelCase_ , lowerCAmelCase_) lowerCamelCase_ : float = sum(lowerCAmelCase_) return abs(lowerCAmelCase_) < eps if __name__ == "__main__": # Test to check if it works __magic_name__ = array( [ polar_force(7_18.4, 1_8_0 - 3_0), polar_force(8_79.54, 4_5), polar_force(1_0_0, -9_0), ] ) __magic_name__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg __magic_name__ = array( [ polar_force(3_0 * 9.81, 1_5), polar_force(2_1_5, 1_8_0 - 4_5), polar_force(2_6_4, 9_0 - 3_0), ] ) __magic_name__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg __magic_name__ = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]]) __magic_name__ = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
1
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __magic_name__ = logging.getLogger(__name__) __magic_name__ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __magic_name__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) }, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(__lowerCamelCase )}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) }, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''}, ) __UpperCAmelCase : str = field( default='''main''', metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) }, ) def _UpperCamelCase ( self ): if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can't be used in combination with --config_name or --model_name_or_path" ) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field(default=__lowerCamelCase, metadata={'''help''': '''The input training data file (a text file).'''} ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''}, ) __UpperCAmelCase : Optional[str] = field( default=__lowerCamelCase, metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''}, ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) __UpperCAmelCase : Optional[int] = field( default=5, metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' }, ) __UpperCAmelCase : Optional[int] = field( default=__lowerCamelCase, metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) }, ) __UpperCAmelCase : Optional[int] = field( default=__lowerCamelCase, metadata={'''help''': '''The number of processes to use for the preprocessing.'''}, ) __UpperCAmelCase : float = field( default=0.15, metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) __UpperCAmelCase : bool = field( default=__lowerCamelCase, metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) }, ) def _UpperCamelCase ( self ): if self.train_file is not None: lowerCamelCase_ : str = self.train_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: lowerCamelCase_ : Union[str, Any] = self.validation_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' with open(lowerCAmelCase_ , "r" , encoding="utf-8") as f: lowerCamelCase_ : Tuple = [json.loads(lowerCAmelCase_) for line in f.read().splitlines() if (len(lowerCAmelCase_) > 0 and not line.isspace())] assert len(lowerCAmelCase_) == len(lowerCAmelCase_) lowerCamelCase_ : Any = {c: dataset[c] for c in dataset.column_names} lowerCamelCase_ : List[Any] = refs return Dataset.from_dict(lowerCAmelCase_) def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : str = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowerCamelCase_ : List[str] = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: lowerCamelCase_ : Dict = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome.") elif last_checkpoint is not None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch.") # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}""") # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowerCamelCase_ : Optional[int] = load_dataset(data_args.dataset_name , data_args.dataset_config_name) if "validation" not in datasets.keys(): lowerCamelCase_ : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[:{data_args.validation_split_percentage}%]""" , ) lowerCamelCase_ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[{data_args.validation_split_percentage}%:]""" , ) else: lowerCamelCase_ : Dict = {} if data_args.train_file is not None: lowerCamelCase_ : str = data_args.train_file if data_args.validation_file is not None: lowerCamelCase_ : Any = data_args.validation_file lowerCamelCase_ : Any = data_args.train_file.split(".")[-1] if extension == "txt": lowerCamelCase_ : List[str] = "text" lowerCamelCase_ : Dict = load_dataset(lowerCAmelCase_ , data_files=lowerCAmelCase_) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase_ : Optional[Any] = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: lowerCamelCase_ : Optional[Any] = AutoConfig.from_pretrained(model_args.config_name , **lowerCAmelCase_) elif model_args.model_name_or_path: lowerCamelCase_ : str = AutoConfig.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase_) else: lowerCamelCase_ : Optional[int] = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch.") if model_args.config_overrides is not None: logger.info(F"""Overriding config: {model_args.config_overrides}""") config.update_from_string(model_args.config_overrides) logger.info(F"""New config: {config}""") lowerCamelCase_ : List[str] = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: lowerCamelCase_ : str = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **lowerCAmelCase_) elif model_args.model_name_or_path: lowerCamelCase_ : Dict = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase_) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name.") if model_args.model_name_or_path: lowerCamelCase_ : Union[str, Any] = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch") lowerCamelCase_ : Dict = AutoModelForMaskedLM.from_config(lowerCAmelCase_) model.resize_token_embeddings(len(lowerCAmelCase_)) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: lowerCamelCase_ : Optional[Any] = datasets["train"].column_names else: lowerCamelCase_ : Dict = datasets["validation"].column_names lowerCamelCase_ : Union[str, Any] = "text" if "text" in column_names else column_names[0] lowerCamelCase_ : Optional[Any] = "max_length" if data_args.pad_to_max_length else False def tokenize_function(lowerCAmelCase_): # Remove empty lines lowerCamelCase_ : str = [line for line in examples["text"] if len(lowerCAmelCase_) > 0 and not line.isspace()] return tokenizer(examples["text"] , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=data_args.max_seq_length) lowerCamelCase_ : str = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: lowerCamelCase_ : List[Any] = add_chinese_references(tokenized_datasets["train"] , data_args.train_ref_file) if data_args.validation_ref_file is not None: lowerCamelCase_ : List[str] = add_chinese_references( tokenized_datasets["validation"] , data_args.validation_ref_file) # If we have ref files, need to avoid it removed by trainer lowerCamelCase_ : Optional[Any] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: lowerCamelCase_ : Union[str, Any] = False # Data collator # This one will take care of randomly masking the tokens. lowerCamelCase_ : Optional[Any] = DataCollatorForWholeWordMask(tokenizer=lowerCAmelCase_ , mlm_probability=data_args.mlm_probability) # Initialize our Trainer lowerCamelCase_ : int = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=tokenized_datasets["train"] if training_args.do_train else None , eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None , tokenizer=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: if last_checkpoint is not None: lowerCamelCase_ : Dict = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path): lowerCamelCase_ : Dict = model_args.model_name_or_path else: lowerCamelCase_ : int = None lowerCamelCase_ : Optional[Any] = trainer.train(resume_from_checkpoint=lowerCAmelCase_) trainer.save_model() # Saves the tokenizer too for easy upload lowerCamelCase_ : Tuple = os.path.join(training_args.output_dir , "train_results.txt") if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w") as writer: logger.info("***** Train results *****") for key, value in sorted(train_result.metrics.items()): logger.info(F""" {key} = {value}""") writer.write(F"""{key} = {value}\n""") # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json")) # Evaluation lowerCamelCase_ : Dict = {} if training_args.do_eval: logger.info("*** Evaluate ***") lowerCamelCase_ : Tuple = trainer.evaluate() lowerCamelCase_ : str = math.exp(eval_output["eval_loss"]) lowerCamelCase_ : Tuple = perplexity lowerCamelCase_ : int = os.path.join(training_args.output_dir , "eval_results_mlm_wwm.txt") if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w") as writer: logger.info("***** Eval results *****") for key, value in sorted(results.items()): logger.info(F""" {key} = {value}""") writer.write(F"""{key} = {value}\n""") return results def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' main() if __name__ == "__main__": main()
73
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''ClapFeatureExtractor''' __UpperCAmelCase : List[str] = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) def __call__( self , a_=None , a_=None , a_=None , **a_ ): lowerCamelCase_ : Any = kwargs.pop("sampling_rate" , a_ ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: lowerCamelCase_ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if audios is not None: lowerCamelCase_ : List[str] = self.feature_extractor( a_ , sampling_rate=a_ , return_tensors=a_ , **a_ ) if text is not None and audios is not None: lowerCamelCase_ : List[str] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) @property def _UpperCamelCase ( self ): lowerCamelCase_ : int = self.tokenizer.model_input_names lowerCamelCase_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
73
1
from math import sqrt def __magic_name__ ( lowerCAmelCase_): '''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(sqrt(lowerCAmelCase_) + 1) , 6): if number % i == 0 or number % (i + 2) == 0: return False return True def __magic_name__ ( lowerCAmelCase_ = 1_0001): '''simple docstring''' lowerCamelCase_ : List[str] = 0 lowerCamelCase_ : Tuple = 1 while count != nth and number < 3: number += 1 if is_prime(lowerCAmelCase_): count += 1 while count != nth: number += 2 if is_prime(lowerCAmelCase_): count += 1 return number if __name__ == "__main__": print(f'''{solution() = }''')
73
def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : Any = set() # Replace all the whitespace in our sentence lowerCamelCase_ : str = input_str.replace(" " , "") for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(lowerCAmelCase_) == 26 def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' lowerCamelCase_ : List[Any] = [False] * 26 for char in input_str: if char.islower(): lowerCamelCase_ : List[Any] = True elif char.isupper(): lowerCamelCase_ : Optional[int] = True return all(lowerCAmelCase_) def __magic_name__ ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()}) == 26 def __magic_name__ ( ): '''simple docstring''' from timeit import timeit lowerCamelCase_ : Optional[int] = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_faster()" , setup=lowerCAmelCase_)) print(timeit("is_pangram_fastest()" , setup=lowerCAmelCase_)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
73
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : str = ['''image_processor''', '''tokenizer'''] __UpperCAmelCase : Tuple = '''ViTImageProcessor''' __UpperCAmelCase : Dict = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self , a_=None , a_=None , **a_ ): lowerCamelCase_ : List[str] = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , a_ , ) lowerCamelCase_ : Union[str, Any] = kwargs.pop("feature_extractor" ) lowerCamelCase_ : Tuple = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(a_ , a_ ) def __call__( self , a_=None , a_=None , a_=None , a_=None , **a_ ): if text is None and visual_prompt is None and images is None: raise ValueError("You have to specify either text, visual prompt or images." ) if text is not None and visual_prompt is not None: raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt." ) if text is not None: lowerCamelCase_ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if visual_prompt is not None: lowerCamelCase_ : List[str] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if images is not None: lowerCamelCase_ : str = self.image_processor(a_ , return_tensors=a_ , **a_ ) if visual_prompt is not None and images is not None: lowerCamelCase_ : List[Any] = { "pixel_values": image_features.pixel_values, "conditional_pixel_values": prompt_features.pixel_values, } return encoding elif text is not None and images is not None: lowerCamelCase_ : int = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: lowerCamelCase_ : List[Any] = { "conditional_pixel_values": prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) @property def _UpperCamelCase ( self ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , a_ , ) return self.image_processor_class @property def _UpperCamelCase ( self ): warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , a_ , ) return self.image_processor
73
__magic_name__ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634E-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.35_58_18, } def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: lowerCamelCase_ : List[Any] = ( F"""Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n""" F"""Valid values are: {', '.join(lowerCAmelCase_)}""" ) raise ValueError(lowerCAmelCase_) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
73
1
import unittest from transformers import DonutProcessor __magic_name__ = '''naver-clova-ix/donut-base''' class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): lowerCamelCase_ : Any = DonutProcessor.from_pretrained(a_ ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = { "name": "John Doe", "age": "99", "city": "Atlanta", "state": "GA", "zip": "30301", "phone": "123-4567", "nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}], } lowerCamelCase_ : Tuple = ( "<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>" "<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>" "<s_nicknames><s_nickname>Johnny</s_nickname>" "<sep/><s_nickname>JD</s_nickname></s_nicknames>" ) lowerCamelCase_ : str = self.processor.tokenajson(a_ ) self.assertDictEqual(a_ , a_ )
73
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 __magic_name__ = logging.get_logger(__name__) __magic_name__ = {'''vocab_file''': '''spiece.model'''} __magic_name__ = { '''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''', } } __magic_name__ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) __magic_name__ = 0 __magic_name__ = 1 __magic_name__ = 2 __magic_name__ = 3 __magic_name__ = 4 class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[int] = '''left''' def __init__( self , a_ , a_=False , a_=True , a_=False , a_="<s>" , a_="</s>" , a_="<unk>" , a_="<sep>" , a_="<pad>" , a_="<cls>" , a_="<mask>" , a_=["<eop>", "<eod>"] , a_ = None , **a_ , ): # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ : str = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token lowerCamelCase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) lowerCamelCase_ : str = 3 lowerCamelCase_ : Dict = do_lower_case lowerCamelCase_ : str = remove_space lowerCamelCase_ : Tuple = keep_accents lowerCamelCase_ : Dict = vocab_file lowerCamelCase_ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) @property def _UpperCamelCase ( self ): return len(self.sp_model ) def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowerCamelCase_ : Any = self.__dict__.copy() lowerCamelCase_ : Optional[int] = None return state def __setstate__( self , a_ ): lowerCamelCase_ : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase_ : int = {} lowerCamelCase_ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self , a_ ): if self.remove_space: lowerCamelCase_ : Optional[int] = " ".join(inputs.strip().split() ) else: lowerCamelCase_ : str = inputs lowerCamelCase_ : Any = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: lowerCamelCase_ : Dict = unicodedata.normalize("NFKD" , a_ ) lowerCamelCase_ : int = "".join([c for c in outputs if not unicodedata.combining(a_ )] ) if self.do_lower_case: lowerCamelCase_ : Any = outputs.lower() return outputs def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : List[Any] = self.preprocess_text(a_ ) lowerCamelCase_ : Optional[int] = self.sp_model.encode(a_ , out_type=a_ ) lowerCamelCase_ : List[str] = [] for piece in pieces: if len(a_ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): lowerCamelCase_ : Tuple = self.sp_model.EncodeAsPieces(piece[:-1].replace(a_ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase_ : int = cur_pieces[1:] else: lowerCamelCase_ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(a_ ) else: new_pieces.append(a_ ) return new_pieces def _UpperCamelCase ( self , a_ ): return self.sp_model.PieceToId(a_ ) def _UpperCamelCase ( self , a_ ): return self.sp_model.IdToPiece(a_ ) def _UpperCamelCase ( self , a_ ): lowerCamelCase_ : Dict = "".join(a_ ).replace(a_ , " " ).strip() return out_string def _UpperCamelCase ( self , a_ , a_ = False , a_ = None , a_ = True , **a_ , ): lowerCamelCase_ : int = kwargs.pop("use_source_tokenizer" , a_ ) lowerCamelCase_ : List[str] = self.convert_ids_to_tokens(a_ , skip_special_tokens=a_ ) # 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 lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : List[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(a_ ) ) lowerCamelCase_ : Union[str, Any] = [] sub_texts.append(a_ ) else: current_sub_text.append(a_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase_ : Union[str, Any] = "".join(a_ ) lowerCamelCase_ : Optional[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase_ : List[Any] = self.clean_up_tokenization(a_ ) return clean_text else: return text def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, 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 _UpperCamelCase ( self , a_ , a_ = None , a_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ ) if token_ids_a is not None: return ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1, 1] return ([0] * len(a_ )) + [1, 1] def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Optional[Any] = [self.sep_token_id] lowerCamelCase_ : Union[str, Any] = [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 _UpperCamelCase ( self , a_ , a_ = None ): if not os.path.isdir(a_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase_ : Any = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , "wb" ) as fi: lowerCamelCase_ : Dict = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
73
1
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( __lowerCamelCase, unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = AudioLDMPipeline __UpperCAmelCase : Tuple = TEXT_TO_AUDIO_PARAMS __UpperCAmelCase : Optional[Any] = TEXT_TO_AUDIO_BATCH_PARAMS __UpperCAmelCase : List[str] = frozenset( [ '''num_inference_steps''', '''num_waveforms_per_prompt''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def _UpperCamelCase ( self ): torch.manual_seed(0 ) lowerCamelCase_ : str = 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, 64) , class_embed_type="simple_projection" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=a_ , ) lowerCamelCase_ : Optional[Any] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , ) torch.manual_seed(0 ) lowerCamelCase_ : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCamelCase_ : Dict = ClapTextConfig( 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 , projection_dim=32 , ) lowerCamelCase_ : str = ClapTextModelWithProjection(a_ ) lowerCamelCase_ : Any = RobertaTokenizer.from_pretrained("hf-internal-testing/tiny-random-roberta" , model_max_length=77 ) lowerCamelCase_ : Optional[Any] = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=a_ , ) lowerCamelCase_ : str = SpeechTaHifiGan(a_ ) lowerCamelCase_ : Tuple = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "vocoder": vocoder, } return components def _UpperCamelCase ( self , a_ , a_=0 ): if str(a_ ).startswith("mps" ): lowerCamelCase_ : str = torch.manual_seed(a_ ) else: lowerCamelCase_ : List[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : int = { "prompt": "A hammer hitting a wooden surface", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, } return inputs def _UpperCamelCase ( self ): lowerCamelCase_ : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ : List[Any] = self.get_dummy_components() lowerCamelCase_ : Union[str, Any] = AudioLDMPipeline(**a_ ) lowerCamelCase_ : Any = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Optional[int] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Optional[int] = audioldm_pipe(**a_ ) lowerCamelCase_ : List[str] = output.audios[0] assert audio.ndim == 1 assert len(a_ ) == 256 lowerCamelCase_ : Union[str, Any] = audio[:10] lowerCamelCase_ : Union[str, Any] = np.array( [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = self.get_dummy_components() lowerCamelCase_ : Optional[Any] = AudioLDMPipeline(**a_ ) lowerCamelCase_ : List[Any] = audioldm_pipe.to(a_ ) lowerCamelCase_ : Dict = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : List[Any] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Tuple = 3 * [inputs["prompt"]] # forward lowerCamelCase_ : Tuple = audioldm_pipe(**a_ ) lowerCamelCase_ : Optional[int] = output.audios[0] lowerCamelCase_ : List[Any] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Optional[Any] = 3 * [inputs.pop("prompt" )] lowerCamelCase_ : Optional[Any] = audioldm_pipe.tokenizer( a_ , padding="max_length" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=a_ , return_tensors="pt" , ) lowerCamelCase_ : Optional[Any] = text_inputs["input_ids"].to(a_ ) lowerCamelCase_ : Union[str, Any] = audioldm_pipe.text_encoder( a_ , ) lowerCamelCase_ : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state lowerCamelCase_ : Optional[Any] = F.normalize(a_ , dim=-1 ) lowerCamelCase_ : Optional[Any] = prompt_embeds # forward lowerCamelCase_ : List[Any] = audioldm_pipe(**a_ ) lowerCamelCase_ : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def _UpperCamelCase ( self ): lowerCamelCase_ : List[Any] = self.get_dummy_components() lowerCamelCase_ : Tuple = AudioLDMPipeline(**a_ ) lowerCamelCase_ : Dict = audioldm_pipe.to(a_ ) lowerCamelCase_ : Any = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Union[str, Any] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Dict = 3 * ["this is a negative prompt"] lowerCamelCase_ : Optional[int] = negative_prompt lowerCamelCase_ : List[str] = 3 * [inputs["prompt"]] # forward lowerCamelCase_ : Optional[Any] = audioldm_pipe(**a_ ) lowerCamelCase_ : Dict = output.audios[0] lowerCamelCase_ : Dict = self.get_dummy_inputs(a_ ) lowerCamelCase_ : int = 3 * [inputs.pop("prompt" )] lowerCamelCase_ : Dict = [] for p in [prompt, negative_prompt]: lowerCamelCase_ : Dict = audioldm_pipe.tokenizer( a_ , padding="max_length" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=a_ , return_tensors="pt" , ) lowerCamelCase_ : str = text_inputs["input_ids"].to(a_ ) lowerCamelCase_ : Optional[Any] = audioldm_pipe.text_encoder( a_ , ) lowerCamelCase_ : int = text_embeds.text_embeds # additional L_2 normalization over each hidden-state lowerCamelCase_ : List[str] = F.normalize(a_ , dim=-1 ) embeds.append(a_ ) lowerCamelCase_ ,lowerCamelCase_ : List[str] = embeds # forward lowerCamelCase_ : Dict = audioldm_pipe(**a_ ) lowerCamelCase_ : Optional[Any] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def _UpperCamelCase ( self ): lowerCamelCase_ : int = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ : int = self.get_dummy_components() lowerCamelCase_ : Any = PNDMScheduler(skip_prk_steps=a_ ) lowerCamelCase_ : List[Any] = AudioLDMPipeline(**a_ ) lowerCamelCase_ : Union[str, Any] = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Union[str, Any] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : List[str] = "egg cracking" lowerCamelCase_ : Tuple = audioldm_pipe(**a_ , negative_prompt=a_ ) lowerCamelCase_ : Tuple = output.audios[0] assert audio.ndim == 1 assert len(a_ ) == 256 lowerCamelCase_ : Optional[Any] = audio[:10] lowerCamelCase_ : List[str] = np.array( [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ : Optional[Any] = self.get_dummy_components() lowerCamelCase_ : int = PNDMScheduler(skip_prk_steps=a_ ) lowerCamelCase_ : int = AudioLDMPipeline(**a_ ) lowerCamelCase_ : Dict = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : List[str] = "A hammer hitting a wooden surface" # test num_waveforms_per_prompt=1 (default) lowerCamelCase_ : Any = audioldm_pipe(a_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts lowerCamelCase_ : List[Any] = 2 lowerCamelCase_ : Any = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt lowerCamelCase_ : List[str] = 2 lowerCamelCase_ : Any = audioldm_pipe(a_ , num_inference_steps=2 , num_waveforms_per_prompt=a_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts lowerCamelCase_ : Any = 2 lowerCamelCase_ : Tuple = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=a_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def _UpperCamelCase ( self ): lowerCamelCase_ : Tuple = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ : List[str] = self.get_dummy_components() lowerCamelCase_ : Optional[Any] = AudioLDMPipeline(**a_ ) lowerCamelCase_ : List[str] = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Optional[Any] = audioldm_pipe.vocoder.config.sampling_rate lowerCamelCase_ : Union[str, Any] = self.get_dummy_inputs(a_ ) lowerCamelCase_ : Union[str, Any] = audioldm_pipe(audio_length_in_s=0.0_16 , **a_ ) lowerCamelCase_ : Union[str, Any] = output.audios[0] assert audio.ndim == 1 assert len(a_ ) / vocoder_sampling_rate == 0.0_16 lowerCamelCase_ : Dict = audioldm_pipe(audio_length_in_s=0.0_32 , **a_ ) lowerCamelCase_ : List[Any] = output.audios[0] assert audio.ndim == 1 assert len(a_ ) / vocoder_sampling_rate == 0.0_32 def _UpperCamelCase ( self ): lowerCamelCase_ : List[str] = self.get_dummy_components() lowerCamelCase_ : Tuple = AudioLDMPipeline(**a_ ) lowerCamelCase_ : Tuple = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Dict = ["hey"] lowerCamelCase_ : int = audioldm_pipe(a_ , num_inference_steps=1 ) lowerCamelCase_ : str = output.audios.shape assert audio_shape == (1, 256) lowerCamelCase_ : Optional[int] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 lowerCamelCase_ : Tuple = SpeechTaHifiGan(a_ ).to(a_ ) lowerCamelCase_ : Optional[int] = audioldm_pipe(a_ , num_inference_steps=1 ) lowerCamelCase_ : Any = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def _UpperCamelCase ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=a_ ) def _UpperCamelCase ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=a_ ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _UpperCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=a_ ) @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCamelCase ( self , a_ , a_="cpu" , a_=torch.floataa , a_=0 ): lowerCamelCase_ : Tuple = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCamelCase_ : Optional[Any] = np.random.RandomState(a_ ).standard_normal((1, 8, 128, 16) ) lowerCamelCase_ : Dict = torch.from_numpy(a_ ).to(device=a_ , dtype=a_ ) lowerCamelCase_ : Optional[Any] = { "prompt": "A hammer hitting a wooden surface", "latents": latents, "generator": generator, "num_inference_steps": 3, "guidance_scale": 2.5, } return inputs def _UpperCamelCase ( self ): lowerCamelCase_ : str = AudioLDMPipeline.from_pretrained("cvssp/audioldm" ) lowerCamelCase_ : Any = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : Tuple = self.get_inputs(a_ ) lowerCamelCase_ : Dict = 25 lowerCamelCase_ : Optional[Any] = audioldm_pipe(**a_ ).audios[0] assert audio.ndim == 1 assert len(a_ ) == 8_1920 lowerCamelCase_ : Tuple = audio[7_7230:7_7240] lowerCamelCase_ : str = np.array( [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15] ) lowerCamelCase_ : int = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1E-2 def _UpperCamelCase ( self ): lowerCamelCase_ : int = AudioLDMPipeline.from_pretrained("cvssp/audioldm" ) lowerCamelCase_ : Tuple = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) lowerCamelCase_ : List[str] = audioldm_pipe.to(a_ ) audioldm_pipe.set_progress_bar_config(disable=a_ ) lowerCamelCase_ : int = self.get_inputs(a_ ) lowerCamelCase_ : str = audioldm_pipe(**a_ ).audios[0] assert audio.ndim == 1 assert len(a_ ) == 8_1920 lowerCamelCase_ : Optional[int] = audio[2_7780:2_7790] lowerCamelCase_ : Union[str, Any] = np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12] ) lowerCamelCase_ : str = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3E-2
73
def __magic_name__ ( lowerCAmelCase_ = 10 , lowerCAmelCase_ = 1000 , lowerCAmelCase_ = True): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)") return min_val if option else max_val def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' return int((number_a + number_a) / 2) def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) and isinstance(lowerCAmelCase_ , lowerCAmelCase_) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)") if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value") def answer(lowerCAmelCase_) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started...") lowerCamelCase_ : Optional[int] = lower lowerCamelCase_ : Tuple = higher lowerCamelCase_ : Union[str, Any] = [] while True: lowerCamelCase_ : Optional[int] = get_avg(lowerCAmelCase_ , lowerCAmelCase_) last_numbers.append(lowerCAmelCase_) if answer(lowerCAmelCase_) == "low": lowerCamelCase_ : Any = number elif answer(lowerCAmelCase_) == "high": lowerCamelCase_ : Optional[int] = number else: break print(F"""guess the number : {last_numbers[-1]}""") print(F"""details : {last_numbers!s}""") def __magic_name__ ( ): '''simple docstring''' lowerCamelCase_ : Optional[int] = int(input("Enter lower value : ").strip()) lowerCamelCase_ : List[str] = int(input("Enter high value : ").strip()) lowerCamelCase_ : List[str] = int(input("Enter value to guess : ").strip()) guess_the_number(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_) if __name__ == "__main__": main()
73
1
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class lowerCAmelCase__ : """simple docstring""" def __init__( self , a_ , a_ , a_ = True , a_ = False ): lowerCamelCase_ : Optional[Any] = scheduler lowerCamelCase_ : str = optimizers if isinstance(a_ , (list, tuple) ) else [optimizers] lowerCamelCase_ : Optional[Any] = split_batches lowerCamelCase_ : Dict = step_with_optimizer lowerCamelCase_ : Dict = GradientState() def _UpperCamelCase ( self , *a_ , **a_ ): if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*a_ , **a_ ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*a_ , **a_ ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step lowerCamelCase_ : List[Any] = AcceleratorState().num_processes for _ in range(a_ ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , "total_steps" ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*a_ , **a_ ) else: self.scheduler.step(*a_ , **a_ ) def _UpperCamelCase ( self ): return self.scheduler.get_last_lr() def _UpperCamelCase ( self ): return self.scheduler.state_dict() def _UpperCamelCase ( self , a_ ): self.scheduler.load_state_dict(a_ ) def _UpperCamelCase ( self ): return self.scheduler.get_lr() def _UpperCamelCase ( self , *a_ , **a_ ): return self.scheduler.print_lr(*a_ , **a_ )
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : List[str] = '''cvt''' def __init__( self , a_=3 , a_=[7, 3, 3] , a_=[4, 2, 2] , a_=[2, 1, 1] , a_=[64, 192, 384] , a_=[1, 3, 6] , a_=[1, 2, 10] , a_=[4.0, 4.0, 4.0] , a_=[0.0, 0.0, 0.0] , a_=[0.0, 0.0, 0.0] , a_=[0.0, 0.0, 0.1] , a_=[True, True, True] , a_=[False, False, True] , a_=["dw_bn", "dw_bn", "dw_bn"] , a_=[3, 3, 3] , a_=[1, 1, 1] , a_=[2, 2, 2] , a_=[1, 1, 1] , a_=[1, 1, 1] , a_=0.02 , a_=1E-12 , **a_ , ): super().__init__(**a_ ) lowerCamelCase_ : Optional[Any] = num_channels lowerCamelCase_ : str = patch_sizes lowerCamelCase_ : List[Any] = patch_stride lowerCamelCase_ : str = patch_padding lowerCamelCase_ : str = embed_dim lowerCamelCase_ : Union[str, Any] = num_heads lowerCamelCase_ : Optional[Any] = depth lowerCamelCase_ : int = mlp_ratio lowerCamelCase_ : Union[str, Any] = attention_drop_rate lowerCamelCase_ : Optional[Any] = drop_rate lowerCamelCase_ : Optional[int] = drop_path_rate lowerCamelCase_ : Union[str, Any] = qkv_bias lowerCamelCase_ : int = cls_token lowerCamelCase_ : int = qkv_projection_method lowerCamelCase_ : int = kernel_qkv lowerCamelCase_ : Optional[Any] = padding_kv lowerCamelCase_ : Optional[int] = stride_kv lowerCamelCase_ : Optional[int] = padding_q lowerCamelCase_ : List[Any] = stride_q lowerCamelCase_ : Any = initializer_range lowerCamelCase_ : int = layer_norm_eps
73
1
import math def __magic_name__ ( lowerCAmelCase_): '''simple docstring''' lowerCamelCase_ : List[Any] = 0 lowerCamelCase_ : Any = 0 while num > 0: lowerCamelCase_ : Optional[Any] = num % 8 lowerCamelCase_ : List[Any] = octal + (remainder * math.floor(math.pow(10 , lowerCAmelCase_))) counter += 1 lowerCamelCase_ : Dict = math.floor(num / 8) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return F"""0o{int(lowerCAmelCase_)}""" def __magic_name__ ( ): '''simple docstring''' print("\n2 in octal is:") print(decimal_to_octal(2)) # = 2 print("\n8 in octal is:") print(decimal_to_octal(8)) # = 10 print("\n65 in octal is:") print(decimal_to_octal(65)) # = 101 print("\n216 in octal is:") print(decimal_to_octal(216)) # = 330 print("\n512 in octal is:") print(decimal_to_octal(512)) # = 1000 print("\n") if __name__ == "__main__": main()
73
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __magic_name__ = {'''processing_layoutxlm''': ['''LayoutXLMProcessor''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''LayoutXLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''LayoutXLMTokenizerFast'''] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
73
1
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( '''The `image_to_image.py` script is outdated. Please use directly `from diffusers import''' ''' StableDiffusionImg2ImgPipeline` instead.''' )
73
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" __UpperCAmelCase : Dict = '''EncodecFeatureExtractor''' __UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , a_ , a_ ): super().__init__(a_ , a_ ) lowerCamelCase_ : Optional[Any] = self.feature_extractor lowerCamelCase_ : Optional[int] = False def _UpperCamelCase ( self , a_=None , a_=None , a_=True ): return self.tokenizer.get_decoder_prompt_ids(task=a_ , language=a_ , no_timestamps=a_ ) def __call__( self , *a_ , **a_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a_ , **a_ ) lowerCamelCase_ : str = kwargs.pop("audio" , a_ ) lowerCamelCase_ : List[str] = kwargs.pop("sampling_rate" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("text" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : int = args[0] lowerCamelCase_ : str = 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 text is not None: lowerCamelCase_ : Dict = self.tokenizer(a_ , **a_ ) if audio is not None: lowerCamelCase_ : Optional[Any] = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ ) if audio is None: return inputs elif text is None: return audio_inputs else: lowerCamelCase_ : Dict = audio_inputs["input_values"] if "padding_mask" in audio_inputs: lowerCamelCase_ : int = audio_inputs["padding_mask"] return inputs def _UpperCamelCase ( self , *a_ , **a_ ): lowerCamelCase_ : Dict = kwargs.pop("audio" , a_ ) lowerCamelCase_ : Optional[Any] = kwargs.pop("padding_mask" , a_ ) if len(a_ ) > 0: lowerCamelCase_ : Optional[int] = args[0] lowerCamelCase_ : Optional[Any] = args[1:] if audio_values is not None: return self._decode_audio(a_ , padding_mask=a_ ) else: return self.tokenizer.batch_decode(*a_ , **a_ ) def _UpperCamelCase ( self , *a_ , **a_ ): return self.tokenizer.decode(*a_ , **a_ ) def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Any = to_numpy(a_ ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : List[str] = audio_values.shape if padding_mask is None: return list(a_ ) lowerCamelCase_ : Tuple = to_numpy(a_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) lowerCamelCase_ : List[str] = seq_len - padding_mask.shape[-1] lowerCamelCase_ : int = 1 - self.feature_extractor.padding_value lowerCamelCase_ : List[Any] = np.pad(a_ , ((0, 0), (0, difference)) , "constant" , constant_values=a_ ) lowerCamelCase_ : str = audio_values.tolist() for i in range(a_ ): lowerCamelCase_ : Dict = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] lowerCamelCase_ : Dict = sliced_audio.reshape(a_ , -1 ) return audio_values
73
1
import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor __magic_name__ = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowerCamelCase ): """simple docstring""" def __init__( self , *a_ , **a_ ): warnings.warn( "The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ChineseCLIPImageProcessor instead." , a_ , ) super().__init__(*a_ , **a_ )
73
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_): '''simple docstring''' if digit_amount > 0: return round(number - int(lowerCAmelCase_) , lowerCAmelCase_) return number - int(lowerCAmelCase_) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.3_45, 1)) print(decimal_isolate(35.3_45, 2)) print(decimal_isolate(35.3_45, 3)) print(decimal_isolate(-14.7_89, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.1_23, 1)) print(decimal_isolate(-14.1_23, 2)) print(decimal_isolate(-14.1_23, 3))
73
1