code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( '''The RoBERTa Model transformer with early exiting (DeeRoBERTa). ''' , lowercase , ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = RobertaConfig __snake_case = '''roberta''' def __init__( self : List[Any] , __UpperCAmelCase : Any ) ->Union[str, Any]: """simple docstring""" super().__init__(__UpperCAmelCase ) a = RobertaEmbeddings(__UpperCAmelCase ) self.init_weights() @add_start_docstrings( '''RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. ''' , lowercase , ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = RobertaConfig __snake_case = '''roberta''' def __init__( self : str , __UpperCAmelCase : str ) ->Any: """simple docstring""" super().__init__(__UpperCAmelCase ) a = config.num_labels a = config.num_hidden_layers a = DeeRobertaModel(__UpperCAmelCase ) a = nn.Dropout(config.hidden_dropout_prob ) a = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Tuple=None , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Any=None , __UpperCAmelCase : str=None , __UpperCAmelCase : int=None , __UpperCAmelCase : int=None , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Optional[int]=-1 , __UpperCAmelCase : Optional[Any]=False , ) ->int: """simple docstring""" a = self.num_layers try: a = self.roberta( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , position_ids=__UpperCAmelCase , head_mask=__UpperCAmelCase , inputs_embeds=__UpperCAmelCase , ) a = outputs[1] a = self.dropout(__UpperCAmelCase ) a = self.classifier(__UpperCAmelCase ) a = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: a = e.message a = e.exit_layer a = outputs[0] if not self.training: a = entropy(__UpperCAmelCase ) a = [] a = [] if labels is not None: if self.num_labels == 1: # We are doing regression a = MSELoss() a = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: a = CrossEntropyLoss() a = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits a = [] for highway_exit in outputs[-1]: a = highway_exit[0] if not self.training: highway_logits_all.append(__UpperCAmelCase ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression a = MSELoss() a = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: a = CrossEntropyLoss() a = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(__UpperCAmelCase ) if train_highway: a = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: a = (loss,) + outputs if not self.training: a = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: a = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
359
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def _a ( a :Union[str, Any] , a :List[Any] ) -> List[Any]: a = checkpoint a = {} a = vae_state_dict['''encoder.conv_in.weight'''] a = vae_state_dict['''encoder.conv_in.bias'''] a = vae_state_dict['''encoder.conv_out.weight'''] a = vae_state_dict['''encoder.conv_out.bias'''] a = vae_state_dict['''encoder.norm_out.weight'''] a = vae_state_dict['''encoder.norm_out.bias'''] a = vae_state_dict['''decoder.conv_in.weight'''] a = vae_state_dict['''decoder.conv_in.bias'''] a = vae_state_dict['''decoder.conv_out.weight'''] a = vae_state_dict['''decoder.conv_out.bias'''] a = vae_state_dict['''decoder.norm_out.weight'''] a = vae_state_dict['''decoder.norm_out.bias'''] a = vae_state_dict['''quant_conv.weight'''] a = vae_state_dict['''quant_conv.bias'''] a = vae_state_dict['''post_quant_conv.weight'''] a = vae_state_dict['''post_quant_conv.bias'''] # Retrieves the keys for the encoder down blocks only a = len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''encoder.down''' in layer} ) a = { layer_id: [key for key in vae_state_dict if F"""down.{layer_id}""" in key] for layer_id in range(a ) } # Retrieves the keys for the decoder up blocks only a = len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''decoder.up''' in layer} ) a = { layer_id: [key for key in vae_state_dict if F"""up.{layer_id}""" in key] for layer_id in range(a ) } for i in range(a ): a = [key for key in down_blocks[i] if F"""down.{i}""" in key and F"""down.{i}.downsample""" not in key] if F"""encoder.down.{i}.downsample.conv.weight""" in vae_state_dict: a = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.weight""" ) a = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.bias""" ) a = renew_vae_resnet_paths(a ) a = {'''old''': F"""down.{i}.block""", '''new''': F"""down_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''encoder.mid.block''' in key] a = 2 for i in range(1 , num_mid_res_blocks + 1 ): a = [key for key in mid_resnets if F"""encoder.mid.block_{i}""" in key] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""mid.block_{i}""", '''new''': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''encoder.mid.attn''' in key] a = renew_vae_attention_paths(a ) a = {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) for i in range(a ): a = num_up_blocks - 1 - i a = [ key for key in up_blocks[block_id] if F"""up.{block_id}""" in key and F"""up.{block_id}.upsample""" not in key ] if F"""decoder.up.{block_id}.upsample.conv.weight""" in vae_state_dict: a = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.weight""" ] a = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.bias""" ] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""up.{block_id}.block""", '''new''': F"""up_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''decoder.mid.block''' in key] a = 2 for i in range(1 , num_mid_res_blocks + 1 ): a = [key for key in mid_resnets if F"""decoder.mid.block_{i}""" in key] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""mid.block_{i}""", '''new''': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''decoder.mid.attn''' in key] a = renew_vae_attention_paths(a ) a = {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) return new_checkpoint def _a ( a :str , a :str , ) -> List[str]: # Only support V1 a = requests.get( ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml''' ) a = io.BytesIO(r.content ) a = OmegaConf.load(a ) a = 512 a = '''cuda''' if torch.cuda.is_available() else '''cpu''' if checkpoint_path.endswith('''safetensors''' ): from safetensors import safe_open a = {} with safe_open(a , framework='''pt''' , device='''cpu''' ) as f: for key in f.keys(): a = f.get_tensor(a ) else: a = torch.load(a , map_location=a )['''state_dict'''] # Convert the VAE model. a = create_vae_diffusers_config(a , image_size=a ) a = custom_convert_ldm_vae_checkpoint(a , a ) a = AutoencoderKL(**a ) vae.load_state_dict(a ) vae.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--vae_pt_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") UpperCAmelCase__ = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
26
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_roberta_prelayernorm": [ "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig", "RobertaPreLayerNormOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
360
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''image_processor''', '''tokenizer'''] __snake_case = '''CLIPImageProcessor''' __snake_case = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Dict , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : Optional[Any] ) ->List[str]: """simple docstring""" a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __UpperCAmelCase , ) a = kwargs.pop('''feature_extractor''' ) a = 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__(__UpperCAmelCase , __UpperCAmelCase ) def __call__( self : List[str] , __UpperCAmelCase : Any=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Any=None , **__UpperCAmelCase : str ) ->Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: a = self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if images is not None: a = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is not None and images is not None: a = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__UpperCAmelCase ) , tensor_type=__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : str , **__UpperCAmelCase : Tuple ) ->Any: """simple docstring""" return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a = self.tokenizer.model_input_names a = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __UpperCAmelCase , ) return self.image_processor_class @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __UpperCAmelCase , ) return self.image_processor
26
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json" # See all FNet models at https://huggingface.co/models?filter=fnet } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''fnet''' def __init__( self : Tuple , __UpperCAmelCase : Optional[int]=32_000 , __UpperCAmelCase : Tuple=768 , __UpperCAmelCase : Any=12 , __UpperCAmelCase : str=3_072 , __UpperCAmelCase : Optional[int]="gelu_new" , __UpperCAmelCase : List[str]=0.1 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : List[str]=4 , __UpperCAmelCase : int=0.02 , __UpperCAmelCase : str=1e-1_2 , __UpperCAmelCase : str=False , __UpperCAmelCase : Optional[int]=512 , __UpperCAmelCase : Dict=3 , __UpperCAmelCase : Optional[int]=1 , __UpperCAmelCase : List[str]=2 , **__UpperCAmelCase : str , ) ->List[Any]: """simple docstring""" super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) a = vocab_size a = max_position_embeddings a = hidden_size a = num_hidden_layers a = intermediate_size a = hidden_act a = hidden_dropout_prob a = initializer_range a = type_vocab_size a = layer_norm_eps a = use_tpu_fourier_optimizations a = tpu_short_seq_length
361
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } UpperCAmelCase__ = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } UpperCAmelCase__ = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = ['''input_ids''', '''attention_mask'''] __snake_case = DistilBertTokenizer def __init__( self : Dict , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[int]="[UNK]" , __UpperCAmelCase : str="[SEP]" , __UpperCAmelCase : Tuple="[PAD]" , __UpperCAmelCase : Any="[CLS]" , __UpperCAmelCase : int="[MASK]" , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : str , ) ->Optional[int]: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int]=None ) ->Optional[Any]: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
26
0
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient UpperCAmelCase__ = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) def _a ( a :Dict ) -> Optional[Any]: a = test_results.split(''' ''' ) a = 0 a = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. a = expressions[-2] if '''=''' in expressions[-1] else expressions[-1] for i, expression in enumerate(a ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def _a ( a :Optional[int] ) -> List[str]: a = {} a = None a = False for line in failures_short_lines.split('''\n''' ): if re.search(r'''_ \[doctest\]''' , a ): a = True a = line.split(''' ''' )[2] elif in_error and not line.split(''' ''' )[0].isdigit(): a = line a = False return failures class lowercase_ : '''simple docstring''' def __init__( self : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : Dict ) ->List[Any]: """simple docstring""" a = title a = doc_test_results['''time_spent'''].split(''',''' )[0] a = doc_test_results['''success'''] a = doc_test_results['''failures'''] a = self.n_success + self.n_failures # Failures and success of the modeling tests a = doc_test_results @property def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" a = [self._time_spent] a = 0 for time in time_spent: a = time.split(''':''' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(__UpperCAmelCase ) == 1: a = [0, 0, time_parts[0]] a , a , a = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 3_600 + minutes * 60 + seconds a , a , a = total_secs // 3_600, (total_secs % 3_600) // 60, total_secs % 60 return F"""{int(__UpperCAmelCase )}h{int(__UpperCAmelCase )}m{int(__UpperCAmelCase )}s""" @property def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def __lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" return { "type": "section", "text": { "type": "plain_text", "text": F"""🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.""", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"""https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}""", }, } @property def __lowerCAmelCase ( self : Dict ) ->Dict: """simple docstring""" return { "type": "section", "text": { "type": "plain_text", "text": ( F"""There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in""" F""" {self.time}.""" ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"""https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}""", }, } @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" a = 40 a = {k: v['''failed'''] for k, v in doc_test_results.items() if isinstance(__UpperCAmelCase , __UpperCAmelCase )} a = '''''' for category, failures in category_failures.items(): if len(__UpperCAmelCase ) == 0: continue if report != "": report += "\n\n" report += F"""*{category} failures*:""".ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(__UpperCAmelCase ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": F"""The following examples had failures:\n\n\n{report}\n""", }, } @property def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(__UpperCAmelCase ) @staticmethod def __lowerCAmelCase ( ) ->Tuple: """simple docstring""" a = [ { '''type''': '''section''', '''text''': { '''type''': '''plain_text''', '''text''': '''There was an issue running the tests.''', }, '''accessory''': { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''Check Action results''', '''emoji''': True}, '''url''': F"""https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}""", }, } ] print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(__UpperCAmelCase )} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text='''There was an issue running the tests.''' , blocks=__UpperCAmelCase , ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" print('''Sending the following payload''' ) print(json.dumps({'''blocks''': json.loads(self.payload )} ) ) a = F"""{self.n_failures} failures out of {self.n_tests} tests,""" if self.n_failures else '''All tests passed.''' a = client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , blocks=self.payload , text=__UpperCAmelCase , ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Tuple , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] ) ->Optional[int]: """simple docstring""" a = '''''' for key, value in failures.items(): a = value[:200] + ''' [Truncated]''' if len(__UpperCAmelCase ) > 250 else value failures_text += F"""*{key}*\n_{value}_\n\n""" a = job_name a = {'''type''': '''section''', '''text''': {'''type''': '''mrkdwn''', '''text''': text}} if job_link is not None: a = { '''type''': '''button''', '''text''': {'''type''': '''plain_text''', '''text''': '''GitHub Action job''', '''emoji''': True}, '''url''': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" if self.thread_ts is None: raise ValueError('''Can only post reply if a post has been made.''' ) a = self.doc_test_results.pop('''job_link''' ) self.doc_test_results.pop('''failures''' ) self.doc_test_results.pop('''success''' ) self.doc_test_results.pop('''time_spent''' ) a = sorted(self.doc_test_results.items() , key=lambda __UpperCAmelCase : t[0] ) for job, job_result in sorted_dict: if len(job_result['''failures'''] ): a = F"""*Num failures* :{len(job_result['failed'] )} \n""" a = job_result['''failures'''] a = self.get_reply_blocks(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , text=__UpperCAmelCase ) print('''Sending the following reply''' ) print(json.dumps({'''blocks''': blocks} ) ) client.chat_postMessage( channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY'''] , text=F"""Results for {job}""" , blocks=__UpperCAmelCase , thread_ts=self.thread_ts['''ts'''] , ) time.sleep(1 ) def _a ( ) -> Tuple: a = os.environ['''GITHUB_RUN_ID'''] a = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100""" a = requests.get(a ).json() a = {} try: jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) a = math.ceil((result['''total_count'''] - 100) / 100 ) for i in range(a ): a = requests.get(url + F"""&page={i + 2}""" ).json() jobs.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) return jobs except Exception as e: print('''Unknown error, could not fetch links.''' , a ) return {} def _a ( a :str ) -> Dict: a = {} if os.path.exists(a ): a = os.listdir(a ) for file in files: try: with open(os.path.join(a , a ) , encoding='''utf-8''' ) as f: a = f.read() except UnicodeDecodeError as e: raise ValueError(F"""Could not open {os.path.join(a , a )}.""" ) from e return _artifact def _a ( ) -> int: class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : str ) ->List[Any]: """simple docstring""" a = name a = [] def __str__( self : int ) ->Optional[int]: """simple docstring""" return self.name def __lowerCAmelCase ( self : Any , __UpperCAmelCase : str ) ->int: """simple docstring""" self.paths.append({'''name''': self.name, '''path''': path} ) a = {} a = filter(os.path.isdir , os.listdir() ) for directory in directories: a = directory if artifact_name not in _available_artifacts: a = Artifact(a ) _available_artifacts[artifact_name].add_path(a ) return _available_artifacts if __name__ == "__main__": UpperCAmelCase__ = get_job_links() UpperCAmelCase__ = retrieve_available_artifacts() UpperCAmelCase__ = collections.OrderedDict( [ ("*.py", "API Examples"), ("*.md", "MD Examples"), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' UpperCAmelCase__ = { v: { "failed": [], "failures": {}, } for v in docs.values() } # Link to the GitHub Action job UpperCAmelCase__ = github_actions_job_links.get("run_doctests") UpperCAmelCase__ = available_artifacts["doc_tests_gpu_test_reports"].paths[0] UpperCAmelCase__ = retrieve_artifact(artifact_path["name"]) if "stats" in artifact: UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = handle_test_results(artifact["stats"]) UpperCAmelCase__ = failed UpperCAmelCase__ = success UpperCAmelCase__ = time_spent[1:-1] + ", " UpperCAmelCase__ = extract_first_line_failure(artifact["failures_short"]) for line in artifact["summary_short"].split("\n"): if re.search("FAILED", line): UpperCAmelCase__ = line.replace("FAILED ", "") UpperCAmelCase__ = line.split()[0].replace("\n", "") if "::" in line: UpperCAmelCase__ , UpperCAmelCase__ = line.split("::") else: UpperCAmelCase__ , UpperCAmelCase__ = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): UpperCAmelCase__ = docs[file_regex] doc_test_results[category]["failed"].append(test) UpperCAmelCase__ = all_failures[test] if test in all_failures else "N/A" UpperCAmelCase__ = failure break UpperCAmelCase__ = Message("🤗 Results of the doc tests.", doc_test_results) message.post() message.post_reply()
362
from __future__ import annotations import typing from collections import Counter def _a ( a :int ) -> typing.Counter[int]: a = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(a , max_perimeter + 1 ): a = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(a ): a = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _a ( a :int = 1_000 ) -> int: a = pythagorean_triple(a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f"""Perimeter {solution()} has maximum solutions""")
26
0
from __future__ import annotations def _a ( a :float , a :float , a :float ) -> float: if days_between_payments <= 0: raise ValueError('''days_between_payments must be > 0''' ) if daily_interest_rate < 0: raise ValueError('''daily_interest_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * daily_interest_rate * days_between_payments def _a ( a :float , a :float , a :float , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('''number_of_compounding_periods must be > 0''' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('''nominal_annual_interest_rate_percentage must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _a ( a :float , a :float , a :float , ) -> float: if number_of_years <= 0: raise ValueError('''number_of_years must be > 0''' ) if nominal_annual_percentage_rate < 0: raise ValueError('''nominal_annual_percentage_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return compound_interest( a , nominal_annual_percentage_rate / 365 , number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
363
from __future__ import annotations def _a ( a :dict , a :str ) -> set[str]: a , a = set(a ), [start] while stack: a = stack.pop() explored.add(a ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a ) return explored UpperCAmelCase__ = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, "A"))
26
0
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class lowercase_ ( lowercase , lowercase ): '''simple docstring''' @register_to_config def __init__( self : List[str] , *, __UpperCAmelCase : int = 4 , __UpperCAmelCase : int = 768 , __UpperCAmelCase : int , __UpperCAmelCase : List[Any] , ) ->List[Any]: """simple docstring""" super().__init__() a = nn.Parameter(torch.zeros(__UpperCAmelCase ) ) # parameters for additional clip time embeddings a = nn.Linear(__UpperCAmelCase , __UpperCAmelCase ) a = nn.Linear(__UpperCAmelCase , __UpperCAmelCase ) # parameters for encoder hidden states a = clip_extra_context_tokens a = nn.Linear( __UpperCAmelCase , self.clip_extra_context_tokens * cross_attention_dim ) a = nn.Linear(__UpperCAmelCase , __UpperCAmelCase ) a = nn.LayerNorm(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , *, __UpperCAmelCase : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings a = image_embeddings.shape[0] a = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) a = classifier_free_guidance_embeddings.expand( __UpperCAmelCase , -1 ) a = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] a = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... a = self.embedding_proj(__UpperCAmelCase ) a = self.clip_image_embeddings_project_to_time_embeddings(__UpperCAmelCase ) a = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" a = self.clip_extra_context_tokens_proj(__UpperCAmelCase ) a = clip_extra_context_tokens.reshape(__UpperCAmelCase , -1 , self.clip_extra_context_tokens ) a = clip_extra_context_tokens.permute(0 , 2 , 1 ) a = self.encoder_hidden_states_proj(__UpperCAmelCase ) a = self.text_encoder_hidden_states_norm(__UpperCAmelCase ) a = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
364
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase__ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex UpperCAmelCase__ = 10 UpperCAmelCase__ = 256 def _a ( a :List[str] ) -> Optional[MinHash]: if len(a ) < MIN_NUM_TOKENS: return None a = MinHash(num_perm=a ) for token in set(a ): min_hash.update(token.encode() ) return min_hash def _a ( a :str ) -> Set[str]: return {t for t in NON_ALPHA.split(a ) if len(t.strip() ) > 0} class lowercase_ : '''simple docstring''' def __init__( self : Any , *, __UpperCAmelCase : float = 0.85 , ) ->Dict: """simple docstring""" a = duplication_jaccard_threshold a = NUM_PERM a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) a = defaultdict(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : MinHash ) ->None: """simple docstring""" a = self._index.query(__UpperCAmelCase ) if code_key in self._index.keys: print(F"""Duplicate key {code_key}""" ) return self._index.insert(__UpperCAmelCase , __UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__UpperCAmelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->List[List[Dict]]: """simple docstring""" a = [] for base, duplicates in self._duplicate_clusters.items(): a = [base] + list(__UpperCAmelCase ) # reformat the cluster to be a list of dict a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(__UpperCAmelCase ) return duplicate_clusters def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Dict ) ->None: """simple docstring""" a = self.get_duplicate_clusters() with open(__UpperCAmelCase , '''w''' ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def _a ( a :List[Any] ) -> List[Any]: a , a = element a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _a ( a :Type[Dataset] ) -> List[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(a , max_queue_size=10_000 ) , chunksize=100 , ): if data is not None: yield data def _a ( a :Type[Dataset] , a :float ) -> str: a = DuplicationIndex(duplication_jaccard_threshold=a ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a ) ) , max_queue_size=100 ) ): di.add(a , a ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _a ( a :str , a :str ) -> float: a = get_tokens(a ) a = get_tokens(a ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase__ = None def _a ( a :Tuple , a :Tuple ) -> Any: a = [] for elementa in cluster: a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(a , a ) >= jaccard_threshold: elementa["copies"] += 1 break else: a = 1 extremes.append(a ) return extremes def _a ( a :List[Any] , a :Optional[Any] , a :Union[str, Any] ) -> Optional[int]: global _shared_dataset a = dataset a = [] a = partial(_find_cluster_extremes_shared , jaccard_threshold=a ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( a , a , ) , total=len(a ) , ): extremes_list.append(a ) return extremes_list def _a ( a :Type[Dataset] , a :float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: a = make_duplicate_clusters(a , a ) a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} a = {} a = find_extremes(a , a , a ) for extremes in extremes_clusters: for element in extremes: a = element a = duplicate_indices - set(extreme_dict.keys() ) a = dataset.filter(lambda a , a : idx not in remove_indices , with_indices=a ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: a = element['''base_index'''] in extreme_dict if element["is_extreme"]: a = extreme_dict[element['''base_index''']]['''copies'''] print(F"""Original dataset size: {len(a )}""" ) print(F"""Number of duplicate clusters: {len(a )}""" ) print(F"""Files in duplicate cluster: {len(a )}""" ) print(F"""Unique files in duplicate cluster: {len(a )}""" ) print(F"""Filtered dataset size: {len(a )}""" ) return ds_filter, duplicate_clusters
26
0
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase__ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex UpperCAmelCase__ = 10 UpperCAmelCase__ = 256 def _a ( a :List[str] ) -> Optional[MinHash]: if len(a ) < MIN_NUM_TOKENS: return None a = MinHash(num_perm=a ) for token in set(a ): min_hash.update(token.encode() ) return min_hash def _a ( a :str ) -> Set[str]: return {t for t in NON_ALPHA.split(a ) if len(t.strip() ) > 0} class lowercase_ : '''simple docstring''' def __init__( self : Any , *, __UpperCAmelCase : float = 0.85 , ) ->Dict: """simple docstring""" a = duplication_jaccard_threshold a = NUM_PERM a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) a = defaultdict(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : MinHash ) ->None: """simple docstring""" a = self._index.query(__UpperCAmelCase ) if code_key in self._index.keys: print(F"""Duplicate key {code_key}""" ) return self._index.insert(__UpperCAmelCase , __UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__UpperCAmelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->List[List[Dict]]: """simple docstring""" a = [] for base, duplicates in self._duplicate_clusters.items(): a = [base] + list(__UpperCAmelCase ) # reformat the cluster to be a list of dict a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(__UpperCAmelCase ) return duplicate_clusters def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Dict ) ->None: """simple docstring""" a = self.get_duplicate_clusters() with open(__UpperCAmelCase , '''w''' ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def _a ( a :List[Any] ) -> List[Any]: a , a = element a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _a ( a :Type[Dataset] ) -> List[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(a , max_queue_size=10_000 ) , chunksize=100 , ): if data is not None: yield data def _a ( a :Type[Dataset] , a :float ) -> str: a = DuplicationIndex(duplication_jaccard_threshold=a ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a ) ) , max_queue_size=100 ) ): di.add(a , a ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _a ( a :str , a :str ) -> float: a = get_tokens(a ) a = get_tokens(a ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase__ = None def _a ( a :Tuple , a :Tuple ) -> Any: a = [] for elementa in cluster: a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(a , a ) >= jaccard_threshold: elementa["copies"] += 1 break else: a = 1 extremes.append(a ) return extremes def _a ( a :List[Any] , a :Optional[Any] , a :Union[str, Any] ) -> Optional[int]: global _shared_dataset a = dataset a = [] a = partial(_find_cluster_extremes_shared , jaccard_threshold=a ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( a , a , ) , total=len(a ) , ): extremes_list.append(a ) return extremes_list def _a ( a :Type[Dataset] , a :float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: a = make_duplicate_clusters(a , a ) a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} a = {} a = find_extremes(a , a , a ) for extremes in extremes_clusters: for element in extremes: a = element a = duplicate_indices - set(extreme_dict.keys() ) a = dataset.filter(lambda a , a : idx not in remove_indices , with_indices=a ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: a = element['''base_index'''] in extreme_dict if element["is_extreme"]: a = extreme_dict[element['''base_index''']]['''copies'''] print(F"""Original dataset size: {len(a )}""" ) print(F"""Number of duplicate clusters: {len(a )}""" ) print(F"""Files in duplicate cluster: {len(a )}""" ) print(F"""Unique files in duplicate cluster: {len(a )}""" ) print(F"""Filtered dataset size: {len(a )}""" ) return ds_filter, duplicate_clusters
365
from math import ceil, sqrt def _a ( a :int = 1_000_000 ) -> int: a = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: a = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
26
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
366
UpperCAmelCase__ = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
26
0
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ = "bart" UpperCAmelCase__ = True @st.cache(allow_output_mutation=a ) def _a ( ) -> Tuple: if LOAD_DENSE_INDEX: a = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) a = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) a = qar_model.eval() else: a , a = (None, None) if MODEL_TYPE == "bart": a = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) a = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) a = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) a = sas_model.eval() else: a , a = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def _a ( ) -> Dict: if LOAD_DENSE_INDEX: a = faiss.StandardGpuResources() a = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] a = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) a = faiss.IndexFlatIP(128 ) a = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: a , a = (None, None) a = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def _a ( ) -> Optional[int]: a = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) a = elia['''train_eli5'''] a = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) a = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = load_indexes() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = load_models() UpperCAmelCase__ , UpperCAmelCase__ = load_train_data() def _a ( a :str , a :Tuple=10 ) -> List[str]: a = embed_questions_for_retrieval([question] , a , a ) a , a = eli5_train_q_index.search(a , a ) a = [elia_train[int(a )] for i in I[0]] return nn_examples def _a ( a :str , a :Any="wiki40b" , a :int="dense" , a :Union[str, Any]=10 ) -> List[str]: if source == "none": a , a = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": a , a = query_qa_dense_index( a , a , a , a , a , a ) else: a , a = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) a = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] a = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def _a ( a :Tuple , a :int , a :int , a :Dict=64 , a :List[Any]=256 , a :List[Any]=False , a :List[Any]=2 , a :Tuple=0.95 , a :Optional[Any]=0.8 ) -> int: with torch.no_grad(): a = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=1_024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar UpperCAmelCase__ = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" UpperCAmelCase__ = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] UpperCAmelCase__ = st.sidebar.checkbox("Demo options") if demo_options: UpperCAmelCase__ = st.sidebar.selectbox( "", action_list, index=3, ) UpperCAmelCase__ = action_list.index(action_st) UpperCAmelCase__ = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) UpperCAmelCase__ = show_type == "Show full text of passages" else: UpperCAmelCase__ = 3 UpperCAmelCase__ = True UpperCAmelCase__ = st.sidebar.checkbox("Retrieval options") if retrieval_options: UpperCAmelCase__ = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) UpperCAmelCase__ = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) UpperCAmelCase__ = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: UpperCAmelCase__ = "wiki40b" UpperCAmelCase__ = "dense" UpperCAmelCase__ = "beam" UpperCAmelCase__ = 2 UpperCAmelCase__ = 64 UpperCAmelCase__ = 256 UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = st.sidebar.checkbox("Generation options") if generate_options: UpperCAmelCase__ = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) UpperCAmelCase__ = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) UpperCAmelCase__ = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ = None # start main text UpperCAmelCase__ = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] UpperCAmelCase__ = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ = st.text_input("Enter your question here:", "") else: UpperCAmelCase__ = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method="dense", n_results=10) UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method="sparse", n_results=10) UpperCAmelCase__ = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ = support_list[:10] UpperCAmelCase__ = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ , UpperCAmelCase__ = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): UpperCAmelCase__ = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) UpperCAmelCase__ = res[1].strip() if sec_titles == "": UpperCAmelCase__ = "[{}]({})".format(res[0], wiki_url) else: UpperCAmelCase__ = sec_titles.split(" & ") UpperCAmelCase__ = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ = find_nearest_training(question) UpperCAmelCase__ = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) UpperCAmelCase__ = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) UpperCAmelCase__ = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
367
def _a ( a :list ) -> list: if len(a ) <= 1: return lst a = 1 while i < len(a ): if lst[i - 1] <= lst[i]: i += 1 else: a , a = lst[i], lst[i - 1] i -= 1 if i == 0: a = 1 return lst if __name__ == "__main__": UpperCAmelCase__ = input("Enter numbers separated by a comma:\n").strip() UpperCAmelCase__ = [int(item) for item in user_input.split(",")] print(gnome_sort(unsorted))
26
0
"""simple docstring""" import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {name: getattr(transformers, name + "Fast") for name in SLOW_TO_FAST_CONVERTERS} def _a ( a :List[str] , a :Tuple , a :Union[str, Any] , a :Optional[int] ) -> int: if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(F"""Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.""" ) if tokenizer_name is None: a = TOKENIZER_CLASSES else: a = {tokenizer_name: getattr(a , tokenizer_name + '''Fast''' )} logger.info(F"""Loading tokenizer classes: {tokenizer_names}""" ) for tokenizer_name in tokenizer_names: a = TOKENIZER_CLASSES[tokenizer_name] a = True if checkpoint_name is None: a = list(tokenizer_class.max_model_input_sizes.keys() ) else: a = [checkpoint_name] logger.info(F"""For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}""" ) for checkpoint in checkpoint_names: logger.info(F"""Loading {tokenizer_class.__class__.__name__} {checkpoint}""" ) # Load tokenizer a = tokenizer_class.from_pretrained(a , force_download=a ) # Save fast tokenizer logger.info(F"""Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}""" ) # For organization names we create sub-directories if "/" in checkpoint: a , a = checkpoint.split('''/''' ) a = os.path.join(a , a ) elif add_prefix: a = checkpoint a = dump_path else: a = None a = dump_path logger.info(F"""=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}""" ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: a = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] a = file_path.split(a )[-1][0] if next_char == "/": a = os.path.join(a , a ) a = None logger.info(F"""=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}""" ) a = tokenizer.save_pretrained( a , legacy_format=a , filename_prefix=a ) logger.info(F"""=> File names {file_names}""" ) for file_name in file_names: if not file_name.endswith('''tokenizer.json''' ): os.remove(a ) logger.info(F"""=> removing {file_name}""" ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--dump_path", default=None, type=str, required=True, help="Path to output generated fast tokenizer files." ) parser.add_argument( "--tokenizer_name", default=None, type=str, help=( f"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ "download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--checkpoint_name", default=None, type=str, help="Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.", ) parser.add_argument( "--force_download", action="store_true", help="Re-download checkpoints.", ) UpperCAmelCase__ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
368
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
0
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = [ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] UpperCAmelCase__ = [ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def _a ( a :Any ) -> Optional[int]: a = torch.load(a , map_location='''cpu''' ) return sd def _a ( a :Tuple , a :Dict , a :Any=rename_keys_prefix ) -> Union[str, Any]: a = OrderedDict() a = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue a = key for name_pair in rename_keys_prefix: a = new_key.replace(name_pair[0] , name_pair[1] ) a = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately a = new_d['''cls.predictions.bias'''] return new_d @torch.no_grad() def _a ( a :Optional[int] , a :int ) -> str: assert ( checkpoint_path.split('''/''' )[-1] in ACCEPTABLE_CHECKPOINTS ), F"""The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.""" # Get Config if "pre" in checkpoint_path: a = '''pretraining''' if "vcr" in checkpoint_path: a = {'''visual_embedding_dim''': 512} elif "vqa_advanced" in checkpoint_path: a = {'''visual_embedding_dim''': 2_048} elif "vqa" in checkpoint_path: a = {'''visual_embedding_dim''': 2_048} elif "nlvr" in checkpoint_path: a = {'''visual_embedding_dim''': 1_024} else: raise NotImplementedError(F"""No implementation found for `{checkpoint_path}`.""" ) else: if "vcr" in checkpoint_path: a = {'''visual_embedding_dim''': 512} a = '''multichoice''' elif "vqa_advanced" in checkpoint_path: a = {'''visual_embedding_dim''': 2_048} a = '''vqa_advanced''' elif "vqa" in checkpoint_path: a = {'''visual_embedding_dim''': 2_048, '''num_labels''': 3_129} a = '''vqa''' elif "nlvr" in checkpoint_path: a = { '''visual_embedding_dim''': 1_024, '''num_labels''': 2, } a = '''nlvr''' a = VisualBertConfig(**a ) # Load State Dict a = load_state_dict(a ) a = get_new_dict(a , a ) if model_type == "pretraining": a = VisualBertForPreTraining(a ) elif model_type == "vqa": a = VisualBertForQuestionAnswering(a ) elif model_type == "nlvr": a = VisualBertForVisualReasoning(a ) elif model_type == "multichoice": a = VisualBertForMultipleChoice(a ) model.load_state_dict(a ) # Save Checkpoints Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") UpperCAmelCase__ = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
369
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = OrderedDict( [ ("audio-spectrogram-transformer", "ASTFeatureExtractor"), ("beit", "BeitFeatureExtractor"), ("chinese_clip", "ChineseCLIPFeatureExtractor"), ("clap", "ClapFeatureExtractor"), ("clip", "CLIPFeatureExtractor"), ("clipseg", "ViTFeatureExtractor"), ("conditional_detr", "ConditionalDetrFeatureExtractor"), ("convnext", "ConvNextFeatureExtractor"), ("cvt", "ConvNextFeatureExtractor"), ("data2vec-audio", "Wav2Vec2FeatureExtractor"), ("data2vec-vision", "BeitFeatureExtractor"), ("deformable_detr", "DeformableDetrFeatureExtractor"), ("deit", "DeiTFeatureExtractor"), ("detr", "DetrFeatureExtractor"), ("dinat", "ViTFeatureExtractor"), ("donut-swin", "DonutFeatureExtractor"), ("dpt", "DPTFeatureExtractor"), ("encodec", "EncodecFeatureExtractor"), ("flava", "FlavaFeatureExtractor"), ("glpn", "GLPNFeatureExtractor"), ("groupvit", "CLIPFeatureExtractor"), ("hubert", "Wav2Vec2FeatureExtractor"), ("imagegpt", "ImageGPTFeatureExtractor"), ("layoutlmv2", "LayoutLMv2FeatureExtractor"), ("layoutlmv3", "LayoutLMv3FeatureExtractor"), ("levit", "LevitFeatureExtractor"), ("maskformer", "MaskFormerFeatureExtractor"), ("mctct", "MCTCTFeatureExtractor"), ("mobilenet_v1", "MobileNetV1FeatureExtractor"), ("mobilenet_v2", "MobileNetV2FeatureExtractor"), ("mobilevit", "MobileViTFeatureExtractor"), ("nat", "ViTFeatureExtractor"), ("owlvit", "OwlViTFeatureExtractor"), ("perceiver", "PerceiverFeatureExtractor"), ("poolformer", "PoolFormerFeatureExtractor"), ("regnet", "ConvNextFeatureExtractor"), ("resnet", "ConvNextFeatureExtractor"), ("segformer", "SegformerFeatureExtractor"), ("sew", "Wav2Vec2FeatureExtractor"), ("sew-d", "Wav2Vec2FeatureExtractor"), ("speech_to_text", "Speech2TextFeatureExtractor"), ("speecht5", "SpeechT5FeatureExtractor"), ("swiftformer", "ViTFeatureExtractor"), ("swin", "ViTFeatureExtractor"), ("swinv2", "ViTFeatureExtractor"), ("table-transformer", "DetrFeatureExtractor"), ("timesformer", "VideoMAEFeatureExtractor"), ("tvlt", "TvltFeatureExtractor"), ("unispeech", "Wav2Vec2FeatureExtractor"), ("unispeech-sat", "Wav2Vec2FeatureExtractor"), ("van", "ConvNextFeatureExtractor"), ("videomae", "VideoMAEFeatureExtractor"), ("vilt", "ViltFeatureExtractor"), ("vit", "ViTFeatureExtractor"), ("vit_mae", "ViTFeatureExtractor"), ("vit_msn", "ViTFeatureExtractor"), ("wav2vec2", "Wav2Vec2FeatureExtractor"), ("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"), ("wavlm", "Wav2Vec2FeatureExtractor"), ("whisper", "WhisperFeatureExtractor"), ("xclip", "CLIPFeatureExtractor"), ("yolos", "YolosFeatureExtractor"), ] ) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _a ( a :str ) -> Any: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: a = model_type_to_module_name(a ) a = importlib.import_module(F""".{module_name}""" , '''transformers.models''' ) try: return getattr(a , a ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(a , '''__name__''' , a ) == 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. a = importlib.import_module('''transformers''' ) if hasattr(a , a ): return getattr(a , a ) return None def _a ( a :Union[str, os.PathLike] , a :Optional[Union[str, os.PathLike]] = None , a :bool = False , a :bool = False , a :Optional[Dict[str, str]] = None , a :Optional[Union[bool, str]] = None , a :Optional[str] = None , a :bool = False , **a :int , ) -> Tuple: a = get_file_from_repo( a , a , cache_dir=a , force_download=a , resume_download=a , proxies=a , use_auth_token=a , revision=a , local_files_only=a , ) 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(a , encoding='''utf-8''' ) as reader: return json.load(a ) class lowercase_ : '''simple docstring''' def __init__( self : Tuple ) ->int: """simple docstring""" raise EnvironmentError( '''AutoFeatureExtractor is designed to be instantiated ''' '''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__UpperCAmelCase ) def __lowerCAmelCase ( cls : int , __UpperCAmelCase : Optional[Any] , **__UpperCAmelCase : Dict ) ->List[Any]: """simple docstring""" a = kwargs.pop('''config''' , __UpperCAmelCase ) a = kwargs.pop('''trust_remote_code''' , __UpperCAmelCase ) a = True a , a = FeatureExtractionMixin.get_feature_extractor_dict(__UpperCAmelCase , **__UpperCAmelCase ) a = config_dict.get('''feature_extractor_type''' , __UpperCAmelCase ) a = None if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a = 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(__UpperCAmelCase , __UpperCAmelCase ): a = AutoConfig.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) # It could be in `config.feature_extractor_type`` a = getattr(__UpperCAmelCase , '''feature_extractor_type''' , __UpperCAmelCase ) if hasattr(__UpperCAmelCase , '''auto_map''' ) and "AutoFeatureExtractor" in config.auto_map: a = config.auto_map['''AutoFeatureExtractor'''] if feature_extractor_class is not None: a = feature_extractor_class_from_name(__UpperCAmelCase ) a = feature_extractor_auto_map is not None a = feature_extractor_class is not None or type(__UpperCAmelCase ) in FEATURE_EXTRACTOR_MAPPING a = resolve_trust_remote_code( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if has_remote_code and trust_remote_code: a = get_class_from_dynamic_module( __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ) a = kwargs.pop('''code_revision''' , __UpperCAmelCase ) if os.path.isdir(__UpperCAmelCase ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(__UpperCAmelCase ) in FEATURE_EXTRACTOR_MAPPING: a = FEATURE_EXTRACTOR_MAPPING[type(__UpperCAmelCase )] return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) 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 __lowerCAmelCase ( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple ) ->Optional[int]: """simple docstring""" FEATURE_EXTRACTOR_MAPPING.register(__UpperCAmelCase , __UpperCAmelCase )
26
0
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowercase_ : '''simple docstring''' def __init__( self : Any , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : Optional[Any]=3 , __UpperCAmelCase : Optional[Any]=4 , __UpperCAmelCase : List[Any]=2 , __UpperCAmelCase : List[Any]=7 , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : int=True , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Tuple=99 , __UpperCAmelCase : int=36 , __UpperCAmelCase : Dict=2 , __UpperCAmelCase : Dict=4 , __UpperCAmelCase : List[Any]=37 , __UpperCAmelCase : Dict="gelu" , __UpperCAmelCase : Dict=0.1 , __UpperCAmelCase : Dict=0.1 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : Tuple=16 , __UpperCAmelCase : List[Any]=2 , __UpperCAmelCase : List[Any]=0.02 , __UpperCAmelCase : Tuple=6 , __UpperCAmelCase : Dict=6 , __UpperCAmelCase : Dict=3 , __UpperCAmelCase : int=4 , __UpperCAmelCase : int=None , __UpperCAmelCase : List[str]=1_000 , ) ->List[str]: """simple docstring""" a = parent a = batch_size a = num_channels a = image_size a = patch_size a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = coordinate_size a = shape_size a = num_labels a = num_choices a = scope a = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) a = text_seq_length a = (image_size // patch_size) ** 2 + 1 a = self.text_seq_length + self.image_seq_length def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" a = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) a = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) a = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a = bbox[i, j, 3] a = bbox[i, j, 1] a = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: a = bbox[i, j, 2] a = bbox[i, j, 0] a = tmp_coordinate a = tf.constant(__UpperCAmelCase ) a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.text_seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) a = LayoutLMvaConfig( 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 , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : Dict ) ->Optional[int]: """simple docstring""" a = TFLayoutLMvaModel(config=__UpperCAmelCase ) # text + image a = model(__UpperCAmelCase , pixel_values=__UpperCAmelCase , training=__UpperCAmelCase ) a = model( __UpperCAmelCase , bbox=__UpperCAmelCase , pixel_values=__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , training=__UpperCAmelCase , ) a = model(__UpperCAmelCase , bbox=__UpperCAmelCase , pixel_values=__UpperCAmelCase , training=__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only a = model(__UpperCAmelCase , training=__UpperCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only a = model({'''pixel_values''': pixel_values} , training=__UpperCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple ) ->Any: """simple docstring""" a = self.num_labels a = TFLayoutLMvaForSequenceClassification(config=__UpperCAmelCase ) a = model( __UpperCAmelCase , bbox=__UpperCAmelCase , pixel_values=__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , training=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any] , __UpperCAmelCase : int ) ->List[str]: """simple docstring""" a = self.num_labels a = TFLayoutLMvaForTokenClassification(config=__UpperCAmelCase ) a = model( __UpperCAmelCase , bbox=__UpperCAmelCase , pixel_values=__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , training=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : Tuple , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] ) ->str: """simple docstring""" a = 2 a = TFLayoutLMvaForQuestionAnswering(config=__UpperCAmelCase ) a = model( __UpperCAmelCase , bbox=__UpperCAmelCase , pixel_values=__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase , training=__UpperCAmelCase , ) 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 __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = self.prepare_config_and_inputs() ((a) , (a) , (a) , (a) , (a) , (a) , (a) , (a)) = config_and_inputs a = { '''input_ids''': input_ids, '''bbox''': bbox, '''pixel_values''': pixel_values, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_tf class lowercase_ ( lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any] ) ->Dict: """simple docstring""" return True def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any]=False ) ->dict: """simple docstring""" a = copy.deepcopy(__UpperCAmelCase ) if model_class in get_values(__UpperCAmelCase ): a = { k: tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(__UpperCAmelCase , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__UpperCAmelCase ): a = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__UpperCAmelCase ): a = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) a = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__UpperCAmelCase ): a = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(__UpperCAmelCase ): a = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = TFLayoutLMvaModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37 ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__UpperCAmelCase ) if getattr(__UpperCAmelCase , '''hf_compute_loss''' , __UpperCAmelCase ): # The number of elements in the loss should be the same as the number of elements in the label a = self._prepare_for_class(inputs_dict.copy() , __UpperCAmelCase , return_labels=__UpperCAmelCase ) a = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=__UpperCAmelCase )[0] ] a = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs a = self._prepare_for_class(inputs_dict.copy() , __UpperCAmelCase , return_labels=__UpperCAmelCase ) a = prepared_for_class.pop('''input_ids''' ) a = model(__UpperCAmelCase , **__UpperCAmelCase )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions a = self._prepare_for_class(inputs_dict.copy() , __UpperCAmelCase , return_labels=__UpperCAmelCase ) a = prepared_for_class.pop('''input_ids''' ) if "labels" in prepared_for_class: a = prepared_for_class['''labels'''].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: a = -100 a = tf.convert_to_tensor(__UpperCAmelCase ) a = model(__UpperCAmelCase , **__UpperCAmelCase )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict a = self._prepare_for_class(inputs_dict.copy() , __UpperCAmelCase , return_labels=__UpperCAmelCase ) a = model(__UpperCAmelCase )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple a = self._prepare_for_class(inputs_dict.copy() , __UpperCAmelCase , return_labels=__UpperCAmelCase ) # Get keys that were added with the _prepare_for_class function a = prepared_for_class.keys() - inputs_dict.keys() a = inspect.signature(model.call ).parameters a = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple a = {0: '''input_ids'''} for label_key in label_keys: a = signature_names.index(__UpperCAmelCase ) a = label_key a = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple a = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: a = prepared_for_class[value] a = tuple(__UpperCAmelCase ) # Send to model a = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a = type self.model_tester.create_and_check_model(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Optional[int]: """simple docstring""" ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) @slow def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = TFLayoutLMvaModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def _a ( ) -> Optional[int]: a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf class lowercase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def __lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase ) if is_vision_available() else None @slow def __lowerCAmelCase ( self : str ) ->List[str]: """simple docstring""" a = TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''' ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__UpperCAmelCase , return_tensors='''tf''' ).pixel_values a = tf.constant([[1, 2]] ) a = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass a = model(input_ids=__UpperCAmelCase , bbox=__UpperCAmelCase , pixel_values=__UpperCAmelCase , training=__UpperCAmelCase ) # verify the logits a = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , __UpperCAmelCase ) a = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , __UpperCAmelCase , atol=1e-4 ) )
370
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = BlipImageProcessor() a = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''' ) a = BertTokenizerFast.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) a = InstructBlipProcessor(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Tuple ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).tokenizer def __lowerCAmelCase ( self : int , **__UpperCAmelCase : str ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).image_processor def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->Optional[Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).qformer_tokenizer def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" a = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) self.assertIsInstance(processor.qformer_tokenizer , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) a = qformer_tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['''qformer_''' + key] ) def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Dict ) ->List[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , )
26
0
from math import pi, sqrt def _a ( a :float ) -> float: if num <= 0: raise ValueError('''math domain error''' ) if num > 171.5: raise OverflowError('''math range error''' ) elif num - int(a ) not in (0, 0.5): raise NotImplementedError('''num must be an integer or a half-integer''' ) elif num == 0.5: return sqrt(a ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def _a ( ) -> None: assert gamma(0.5 ) == sqrt(a ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase__ = 1.0 while num: UpperCAmelCase__ = float(input("Gamma of: ")) print(f"""gamma({num}) = {gamma(num)}""") print("\nEnter 0 to exit...")
371
import math def _a ( a :int = 100 ) -> int: a = sum(i * i for i in range(1 , n + 1 ) ) a = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
26
0
from __future__ import annotations def _a ( a :list[int | str] ) -> None: create_state_space_tree(a , [] , 0 , [0 for i in range(len(a ) )] ) def _a ( a :list[int | str] , a :list[int | str] , a :int , a :list[int] , ) -> None: if index == len(a ): print(a ) return for i in range(len(a ) ): if not index_used[i]: current_sequence.append(sequence[i] ) a = True create_state_space_tree(a , a , index + 1 , a ) current_sequence.pop() a = False UpperCAmelCase__ = [3, 1, 2, 4] generate_all_permutations(sequence) UpperCAmelCase__ = ["A", "B", "C"] generate_all_permutations(sequence_a)
350
def _a ( a :int = 600_851_475_143 ) -> int: try: a = int(a ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''' ) a = 2 a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 a = i while n % i == 0: a = n // i i += 1 return int(a ) if __name__ == "__main__": print(f"""{solution() = }""")
26
0
import math def _a ( a :list , a :int = 0 , a :int = 0 ) -> list: a = end or len(a ) for i in range(a , a ): a = i a = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: a = array[temp_index - 1] temp_index -= 1 a = temp_index_value return array def _a ( a :list , a :int , a :int ) -> None: # Max Heap a = index a = 2 * index + 1 # Left Node a = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: a = left_index if right_index < heap_size and array[largest] < array[right_index]: a = right_index if largest != index: a , a = array[largest], array[index] heapify(a , a , a ) def _a ( a :list ) -> list: a = len(a ) for i in range(n // 2 , -1 , -1 ): heapify(a , a , a ) for i in range(n - 1 , 0 , -1 ): a , a = array[0], array[i] heapify(a , 0 , a ) return array def _a ( a :list , a :int , a :int , a :int ) -> int: if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def _a ( a :list , a :int , a :int , a :int ) -> int: a = low a = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i a , a = array[j], array[i] i += 1 def _a ( a :list ) -> list: if len(a ) == 0: return array a = 2 * math.ceil(math.loga(len(a ) ) ) a = 16 return intro_sort(a , 0 , len(a ) , a , a ) def _a ( a :list , a :int , a :int , a :int , a :int ) -> list: while end - start > size_threshold: if max_depth == 0: return heap_sort(a ) max_depth -= 1 a = median_of_a(a , a , start + ((end - start) // 2) + 1 , end - 1 ) a = partition(a , a , a , a ) intro_sort(a , a , a , a , a ) a = p return insertion_sort(a , a , a ) if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase__ = input("Enter numbers separated by a comma : ").strip() UpperCAmelCase__ = [float(item) for item in user_input.split(",")] print(sort(unsorted))
351
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ = "bart" UpperCAmelCase__ = True @st.cache(allow_output_mutation=a ) def _a ( ) -> Tuple: if LOAD_DENSE_INDEX: a = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) a = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) a = qar_model.eval() else: a , a = (None, None) if MODEL_TYPE == "bart": a = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) a = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) a = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) a = sas_model.eval() else: a , a = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def _a ( ) -> Dict: if LOAD_DENSE_INDEX: a = faiss.StandardGpuResources() a = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] a = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) a = faiss.IndexFlatIP(128 ) a = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: a , a = (None, None) a = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def _a ( ) -> Optional[int]: a = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) a = elia['''train_eli5'''] a = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) a = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = load_indexes() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = load_models() UpperCAmelCase__ , UpperCAmelCase__ = load_train_data() def _a ( a :str , a :Tuple=10 ) -> List[str]: a = embed_questions_for_retrieval([question] , a , a ) a , a = eli5_train_q_index.search(a , a ) a = [elia_train[int(a )] for i in I[0]] return nn_examples def _a ( a :str , a :Any="wiki40b" , a :int="dense" , a :Union[str, Any]=10 ) -> List[str]: if source == "none": a , a = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": a , a = query_qa_dense_index( a , a , a , a , a , a ) else: a , a = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) a = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] a = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def _a ( a :Tuple , a :int , a :int , a :Dict=64 , a :List[Any]=256 , a :List[Any]=False , a :List[Any]=2 , a :Tuple=0.95 , a :Optional[Any]=0.8 ) -> int: with torch.no_grad(): a = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=1_024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar UpperCAmelCase__ = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" UpperCAmelCase__ = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] UpperCAmelCase__ = st.sidebar.checkbox("Demo options") if demo_options: UpperCAmelCase__ = st.sidebar.selectbox( "", action_list, index=3, ) UpperCAmelCase__ = action_list.index(action_st) UpperCAmelCase__ = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) UpperCAmelCase__ = show_type == "Show full text of passages" else: UpperCAmelCase__ = 3 UpperCAmelCase__ = True UpperCAmelCase__ = st.sidebar.checkbox("Retrieval options") if retrieval_options: UpperCAmelCase__ = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) UpperCAmelCase__ = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) UpperCAmelCase__ = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: UpperCAmelCase__ = "wiki40b" UpperCAmelCase__ = "dense" UpperCAmelCase__ = "beam" UpperCAmelCase__ = 2 UpperCAmelCase__ = 64 UpperCAmelCase__ = 256 UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = st.sidebar.checkbox("Generation options") if generate_options: UpperCAmelCase__ = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) UpperCAmelCase__ = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) UpperCAmelCase__ = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ = None # start main text UpperCAmelCase__ = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] UpperCAmelCase__ = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ = st.text_input("Enter your question here:", "") else: UpperCAmelCase__ = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method="dense", n_results=10) UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method="sparse", n_results=10) UpperCAmelCase__ = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ = support_list[:10] UpperCAmelCase__ = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ , UpperCAmelCase__ = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): UpperCAmelCase__ = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) UpperCAmelCase__ = res[1].strip() if sec_titles == "": UpperCAmelCase__ = "[{}]({})".format(res[0], wiki_url) else: UpperCAmelCase__ = sec_titles.split(" & ") UpperCAmelCase__ = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ = find_nearest_training(question) UpperCAmelCase__ = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) UpperCAmelCase__ = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) UpperCAmelCase__ = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
26
0
import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( enum.Enum ): '''simple docstring''' __snake_case = 0 __snake_case = 1 @add_end_docstrings(lowercase ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''generated''' def __init__( self : int , *__UpperCAmelCase : int , **__UpperCAmelCase : Optional[int] ) ->Optional[int]: """simple docstring""" super().__init__(*__UpperCAmelCase , **__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : int=None , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : Any=None , **__UpperCAmelCase : Union[str, Any] , ) ->List[Any]: """simple docstring""" a = {} if truncation is not None: a = truncation a = generate_kwargs a = {} if return_tensors is not None and return_type is None: a = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: a = return_type if clean_up_tokenization_spaces is not None: a = clean_up_tokenization_spaces if stop_sequence is not None: a = self.tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) if len(__UpperCAmelCase ) > 1: warnings.warn( '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of''' ''' the stop sequence will be used as the stop sequence string in the interim.''' ) a = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : int ) ->List[Any]: """simple docstring""" return True def __lowerCAmelCase ( self : Dict , *__UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str ) ->Tuple: """simple docstring""" a = self.model.config.prefix if self.model.config.prefix is not None else '''''' if isinstance(args[0] , __UpperCAmelCase ): if self.tokenizer.pad_token_id is None: raise ValueError('''Please make sure that the tokenizer has a pad_token_id when using a batch input''' ) a = ([prefix + arg for arg in args[0]],) a = True elif isinstance(args[0] , __UpperCAmelCase ): a = (prefix + args[0],) a = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) a = self.tokenizer(*__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : Dict , *__UpperCAmelCase : Dict , **__UpperCAmelCase : List[Any] ) ->str: """simple docstring""" a = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) if ( isinstance(args[0] , __UpperCAmelCase ) and all(isinstance(__UpperCAmelCase , __UpperCAmelCase ) for el in args[0] ) and all(len(__UpperCAmelCase ) == 1 for res in result ) ): return [res[0] for res in result] return result def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str=TruncationStrategy.DO_NOT_TRUNCATE , **__UpperCAmelCase : int ) ->List[Any]: """simple docstring""" a = self._parse_and_tokenize(__UpperCAmelCase , truncation=__UpperCAmelCase , **__UpperCAmelCase ) return inputs def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : List[str] , **__UpperCAmelCase : Any ) ->int: """simple docstring""" if self.framework == "pt": a , a = model_inputs['''input_ids'''].shape elif self.framework == "tf": a , a = tf.shape(model_inputs['''input_ids'''] ).numpy() a = generate_kwargs.get('''min_length''' , self.model.config.min_length ) a = generate_kwargs.get('''max_length''' , self.model.config.max_length ) self.check_inputs(__UpperCAmelCase , generate_kwargs['''min_length'''] , generate_kwargs['''max_length'''] ) a = self.model.generate(**__UpperCAmelCase , **__UpperCAmelCase ) a = output_ids.shape[0] if self.framework == "pt": a = output_ids.reshape(__UpperCAmelCase , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": a = tf.reshape(__UpperCAmelCase , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int]=ReturnType.TEXT , __UpperCAmelCase : Dict=False ) ->Dict: """simple docstring""" a = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: a = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: a = { F"""{self.return_name}_text""": self.tokenizer.decode( __UpperCAmelCase , skip_special_tokens=__UpperCAmelCase , clean_up_tokenization_spaces=__UpperCAmelCase , ) } records.append(__UpperCAmelCase ) return records @add_end_docstrings(lowercase ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''summary''' def __call__( self : Dict , *__UpperCAmelCase : Optional[Any] , **__UpperCAmelCase : str ) ->str: """simple docstring""" return super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : int ) ->bool: """simple docstring""" if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ '''a summarization task, where outputs shorter than the input are typically wanted, you might ''' F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(lowercase ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''translation''' def __lowerCAmelCase ( self : Any , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : int ) ->Optional[int]: """simple docstring""" if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ '''increasing your max_length manually, e.g. translator(\'...\', max_length=400)''' ) return True def __lowerCAmelCase ( self : Dict , *__UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[Any]=TruncationStrategy.DO_NOT_TRUNCATE , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Optional[int]=None ) ->List[Any]: """simple docstring""" if getattr(self.tokenizer , '''_build_translation_inputs''' , __UpperCAmelCase ): return self.tokenizer._build_translation_inputs( *__UpperCAmelCase , return_tensors=self.framework , truncation=__UpperCAmelCase , src_lang=__UpperCAmelCase , tgt_lang=__UpperCAmelCase ) else: return super()._parse_and_tokenize(*__UpperCAmelCase , truncation=__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Dict=None , __UpperCAmelCase : List[Any]=None , **__UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" a , a , a = super()._sanitize_parameters(**__UpperCAmelCase ) if src_lang is not None: a = src_lang if tgt_lang is not None: a = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. a = kwargs.get('''task''' , self.task ) a = task.split('''_''' ) if task and len(__UpperCAmelCase ) == 4: # translation, XX, to YY a = items[1] a = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : Tuple , *__UpperCAmelCase : int , **__UpperCAmelCase : int ) ->str: """simple docstring""" return super().__call__(*__UpperCAmelCase , **__UpperCAmelCase )
352
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ = "▁" UpperCAmelCase__ = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = BertGenerationTokenizer __snake_case = False __snake_case = True def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" super().setUp() a = BertGenerationTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = '''<s>''' a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(__UpperCAmelCase ) , 1_002 ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def __lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" a = BertGenerationTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) a = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__UpperCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [285, 46, 10, 170, 382] , ) a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) a = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) a = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" return BertGenerationTokenizer.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) @slow def __lowerCAmelCase ( self : Any ) ->str: """simple docstring""" a = '''Hello World!''' a = [18_536, 2_260, 101] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) a = [ 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, ] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @require_torch @slow def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence a = list(self.big_tokenizer.get_vocab().keys() )[:10] a = ''' '''.join(__UpperCAmelCase ) a = self.big_tokenizer.encode_plus(__UpperCAmelCase , return_tensors='''pt''' , return_token_type_ids=__UpperCAmelCase ) a = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=__UpperCAmelCase ) a = BertGenerationConfig() a = BertGenerationEncoder(__UpperCAmelCase ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__UpperCAmelCase ) model(**__UpperCAmelCase ) @slow def __lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" a = {'''input_ids''': [[39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114], [448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='''google/bert_for_seq_generation_L-24_bbc_encoder''' , revision='''c817d1fd1be2ffa69431227a1fe320544943d4db''' , )
26
0
def _a ( a :int ) -> bool: if number < 0: raise ValueError('''number must not be negative''' ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
353
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger("transformers.models.speecht5") def _a ( a :Optional[Any] , a :Tuple , a :Dict ) -> List[str]: hf_model.apply_weight_norm() a = checkpoint['''input_conv.weight_g'''] a = checkpoint['''input_conv.weight_v'''] a = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): a = checkpoint[F"""upsamples.{i}.1.weight_g"""] a = checkpoint[F"""upsamples.{i}.1.weight_v"""] a = checkpoint[F"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): a = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_g"""] a = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_v"""] a = checkpoint[F"""blocks.{i}.convs1.{j}.1.bias"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_g"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_v"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.bias"""] a = checkpoint['''output_conv.1.weight_g'''] a = checkpoint['''output_conv.1.weight_v'''] a = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def _a ( a :List[str] , a :Union[str, Any] , a :Dict , a :Dict=None , a :List[Any]=None , ) -> int: if config_path is not None: a = SpeechTaHifiGanConfig.from_pretrained(a ) else: a = SpeechTaHifiGanConfig() a = SpeechTaHifiGan(a ) a = torch.load(a ) load_weights(orig_checkpoint['''model''']['''generator'''] , a , a ) a = np.load(a ) a = stats[0].reshape(-1 ) a = stats[1].reshape(-1 ) a = torch.from_numpy(a ).float() a = torch.from_numpy(a ).float() model.save_pretrained(a ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--stats_path", required=True, default=None, type=str, help="Path to stats.npy file") 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." ) UpperCAmelCase__ = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
26
0
# Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def _a ( a :str ) -> Tuple: return 1 / (1 + np.exp(-z )) def _a ( a :int , a :Any ) -> Tuple: return (-y * np.log(a ) - (1 - y) * np.log(1 - h )).mean() def _a ( a :List[str] , a :Optional[Any] , a :int ) -> List[Any]: a = np.dot(a , a ) return np.sum(y * scores - np.log(1 + np.exp(a ) ) ) def _a ( a :Union[str, Any] , a :int , a :Optional[Any] , a :Tuple=70_000 ) -> Any: a = np.zeros(x.shape[1] ) for iterations in range(a ): a = np.dot(a , a ) a = sigmoid_function(a ) a = np.dot(x.T , h - y ) / y.size a = theta - alpha * gradient # updating the weights a = np.dot(a , a ) a = sigmoid_function(a ) a = cost_function(a , a ) if iterations % 100 == 0: print(F"""loss: {j} \t""" ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": UpperCAmelCase__ = datasets.load_iris() UpperCAmelCase__ = iris.data[:, :2] UpperCAmelCase__ = (iris.target != 0) * 1 UpperCAmelCase__ = 0.1 UpperCAmelCase__ = logistic_reg(alpha, x, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def _a ( a :Dict ) -> Tuple: return sigmoid_function( np.dot(a , a ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="b", label="0") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="r", label="1") ((UpperCAmelCase__) , (UpperCAmelCase__)) = (x[:, 0].min(), x[:, 0].max()) ((UpperCAmelCase__) , (UpperCAmelCase__)) = (x[:, 1].min(), x[:, 1].max()) ((UpperCAmelCase__) , (UpperCAmelCase__)) = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) UpperCAmelCase__ = np.c_[xxa.ravel(), xxa.ravel()] UpperCAmelCase__ = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
354
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase__ = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTBigCodeForSequenceClassification", "GPTBigCodeForTokenClassification", "GPTBigCodeForCausalLM", "GPTBigCodeModel", "GPTBigCodePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
0
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline UpperCAmelCase__ = datasets.utils.logging.get_logger(__name__) @dataclass class lowercase_ ( datasets.BuilderConfig ): '''simple docstring''' __snake_case = None __snake_case = '''utf-8''' __snake_case = None __snake_case = None __snake_case = True # deprecated __snake_case = None # deprecated __snake_case = 10 << 20 # 10MB __snake_case = None class lowercase_ ( datasets.ArrowBasedBuilder ): '''simple docstring''' __snake_case = JsonConfig def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" if self.config.block_size is not None: logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''' ) a = self.config.block_size if self.config.use_threads is not True: logger.warning( '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.''' ) if self.config.newlines_in_values is not None: raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported''' ) return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] ) ->Union[str, Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) a = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__UpperCAmelCase , (str, list, tuple) ): a = data_files if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = [files] a = [dl_manager.iter_files(__UpperCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] a = [] for split_name, files in data_files.items(): if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = [files] a = [dl_manager.iter_files(__UpperCAmelCase ) for file in files] splits.append(datasets.SplitGenerator(name=__UpperCAmelCase , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self : str , __UpperCAmelCase : pa.Table ) ->pa.Table: """simple docstring""" if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): a = self.config.features.arrow_schema.field(__UpperCAmelCase ).type a = pa_table.append_column(__UpperCAmelCase , pa.array([None] * len(__UpperCAmelCase ) , type=__UpperCAmelCase ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example a = table_cast(__UpperCAmelCase , self.config.features.arrow_schema ) return pa_table def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] ) ->Union[str, Any]: """simple docstring""" for file_idx, file in enumerate(itertools.chain.from_iterable(__UpperCAmelCase ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__UpperCAmelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__UpperCAmelCase ) # We keep only the field we are interested in a = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__UpperCAmelCase , (list, tuple) ): a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__UpperCAmelCase ) for row in dataset] for col in keys} else: a = dataset a = pa.Table.from_pydict(__UpperCAmelCase ) yield file_idx, self._cast_table(__UpperCAmelCase ) # If the file has one json object per line else: with open(__UpperCAmelCase , '''rb''' ) as f: a = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small a = max(self.config.chunksize // 32 , 16 << 10 ) a = ( self.config.encoding_errors if self.config.encoding_errors is not None else '''strict''' ) while True: a = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__UpperCAmelCase ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": a = batch.decode(self.config.encoding , errors=__UpperCAmelCase ).encode('''utf-8''' ) try: while True: try: a = paj.read_json( io.BytesIO(__UpperCAmelCase ) , read_options=paj.ReadOptions(block_size=__UpperCAmelCase ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__UpperCAmelCase , pa.ArrowInvalid ) and "straddling" not in str(__UpperCAmelCase ) or block_size > len(__UpperCAmelCase ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(__UpperCAmelCase )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( __UpperCAmelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: a = json.load(__UpperCAmelCase ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(__UpperCAmelCase )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__UpperCAmelCase , __UpperCAmelCase ): # list is the only sequence type supported in JSON try: a = set().union(*[row.keys() for row in dataset] ) a = {col: [row.get(__UpperCAmelCase ) for row in dataset] for col in keys} a = pa.Table.from_pydict(__UpperCAmelCase ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(__UpperCAmelCase )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(__UpperCAmelCase ) break else: logger.error(F"""Failed to read file '{file}' with error {type(__UpperCAmelCase )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__UpperCAmelCase ) batch_idx += 1
355
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def _a ( a :Tuple ) -> int: a = tmp_path / '''file.csv''' a = textwrap.dedent( '''\ header1,header2 1,2 10,20 ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :int ) -> List[str]: a = tmp_path / '''malformed_file.csv''' a = textwrap.dedent( '''\ header1,header2 1,2 10,20, ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :Dict , a :int ) -> List[str]: a = tmp_path / '''csv_with_image.csv''' a = textwrap.dedent( F"""\ image {image_file} """ ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :List[Any] ) -> Dict: a = tmp_path / '''csv_with_label.csv''' a = textwrap.dedent( '''\ label good bad good ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :Tuple ) -> Any: a = tmp_path / '''csv_with_int_list.csv''' a = textwrap.dedent( '''\ int_list 1 2 3 4 5 6 7 8 9 ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) def _a ( a :Dict , a :int , a :Union[str, Any] ) -> List[Any]: a = Csv() a = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(a , match='''Error tokenizing data''' ): for _ in generator: pass assert any( record.levelname == '''ERROR''' and '''Failed to read file''' in record.message and os.path.basename(a ) in record.message for record in caplog.records ) @require_pil def _a ( a :Dict ) -> Any: with open(a , encoding='''utf-8''' ) as f: a = f.read().splitlines()[1] a = Csv(encoding='''utf-8''' , features=Features({'''image''': Image()} ) ) a = csv._generate_tables([[csv_file_with_image]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''image''' ).type == Image()() a = pa_table.to_pydict()['''image'''] assert generated_content == [{"path": image_file, "bytes": None}] def _a ( a :Any ) -> Tuple: with open(a , encoding='''utf-8''' ) as f: a = f.read().splitlines()[1:] a = Csv(encoding='''utf-8''' , features=Features({'''label''': ClassLabel(names=['''good''', '''bad'''] )} ) ) a = csv._generate_tables([[csv_file_with_label]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''label''' ).type == ClassLabel(names=['''good''', '''bad'''] )() a = pa_table.to_pydict()['''label'''] assert generated_content == [ClassLabel(names=['''good''', '''bad'''] ).straint(a ) for label in labels] def _a ( a :Union[str, Any] ) -> Optional[Any]: a = Csv(encoding='''utf-8''' , sep=''',''' , converters={'''int_list''': lambda a : [int(a ) for i in x.split()]} ) a = csv._generate_tables([[csv_file_with_int_list]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('''int_list''' ).type ) a = pa_table.to_pydict()['''int_list'''] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
26
0
import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( "--original_config_file", default=None, type=str, help="The YAML config file corresponding to the original architecture.", ) parser.add_argument( "--num_in_channels", default=None, type=int, help="The number of input channels. If `None` number of input channels will be automatically inferred.", ) parser.add_argument( "--scheduler_type", default="pndm", type=str, help="Type of scheduler to use. Should be one of ['pndm', 'lms', 'ddim', 'euler', 'euler-ancestral', 'dpm']", ) parser.add_argument( "--pipeline_type", default=None, type=str, help=( "The pipeline type. One of 'FrozenOpenCLIPEmbedder', 'FrozenCLIPEmbedder', 'PaintByExample'" ". If `None` pipeline will be automatically inferred." ), ) parser.add_argument( "--image_size", default=None, type=int, help=( "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2" " Base. Use 768 for Stable Diffusion v2." ), ) parser.add_argument( "--prediction_type", default=None, type=str, help=( "The prediction type that the model was trained on. Use 'epsilon' for Stable Diffusion v1.X and Stable" " Diffusion v2 Base. Use 'v_prediction' for Stable Diffusion v2." ), ) parser.add_argument( "--extract_ema", action="store_true", help=( "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights" " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield" " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning." ), ) parser.add_argument( "--upcast_attention", action="store_true", help=( "Whether the attention computation should always be upcasted. This is necessary when running stable" " diffusion 2.1." ), ) parser.add_argument( "--from_safetensors", action="store_true", help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.", ) parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") parser.add_argument( "--stable_unclip", type=str, default=None, required=False, help="Set if this is a stable unCLIP model. One of 'txt2img' or 'img2img'.", ) parser.add_argument( "--stable_unclip_prior", type=str, default=None, required=False, help="Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.", ) parser.add_argument( "--clip_stats_path", type=str, help="Path to the clip stats file. Only required if the stable unclip model's config specifies `model.params.noise_aug_config.params.clip_stats_path`.", required=False, ) parser.add_argument( "--controlnet", action="store_true", default=None, help="Set flag if this is a controlnet checkpoint." ) parser.add_argument("--half", action="store_true", help="Save weights in half precision.") parser.add_argument( "--vae_path", type=str, default=None, required=False, help="Set to a path, hub id to an already converted vae to not convert it again.", ) UpperCAmelCase__ = parser.parse_args() UpperCAmelCase__ = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
356
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = torch.device("cpu") def _a ( ) -> Union[str, Any]: a = '''http://images.cocodataset.org/val2017/000000039769.jpg''' a = Image.open(requests.get(a , stream=a ).raw ) return im def _a ( a :Dict ) -> Tuple: if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1703e00, 2.1107e00, -2.0811e00, 8.8685e-01, 2.4360e-01] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9636e-01, 2.3478e-01, -1.6963e00, -1.7381e00, -8.6337e-01] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2768e-01, -4.7429e-01, -1.0897e00, -1.0248e00, 3.5523e-02] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5330e-01, 2.4211e-01, -6.0185e-01, -8.2789e-01, -6.0446e-02] ) def _a ( a :int , a :Any , a :Union[str, Any] ) -> int: a = dct.pop(a ) a = val def _a ( a :Any ) -> Dict: a = [] for k in state_dict.keys(): a = k if ".pwconv" in k: a = k_new.replace('''.pwconv''' , '''.point_wise_conv''' ) if ".dwconv" in k: a = k_new.replace('''.dwconv''' , '''.depth_wise_conv''' ) if ".Proj." in k: a = k_new.replace('''.Proj.''' , '''.proj.''' ) if "patch_embed" in k_new: a = k_new.replace('''patch_embed''' , '''swiftformer.patch_embed.patch_embedding''' ) if "network" in k_new: a = k_new.split('''.''' ) if ls[2].isdigit(): a = '''swiftformer.encoder.network.''' + ls[1] + '''.blocks.''' + ls[2] + '''.''' + '''.'''.join(ls[3:] ) else: a = k_new.replace('''network''' , '''swiftformer.encoder.network''' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def _a ( a :List[Any] , a :Tuple , a :List[str] ) -> Union[str, Any]: a = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size a = 1_000 a = '''huggingface/label-files''' a = '''imagenet-1k-id2label.json''' a = json.load(open(hf_hub_download(a , a , repo_type='''dataset''' ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": a = [3, 3, 6, 4] a = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": a = [3, 3, 9, 6] a = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": a = [4, 3, 10, 5] a = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": a = [4, 4, 12, 6] a = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('''https''' ): a = torch.hub.load_state_dict_from_url(a , map_location='''cpu''' , check_hash=a ) else: a = torch.load(a , map_location='''cpu''' ) a = checkpoint a = create_rename_keys(a ) for rename_key_src, rename_key_dest in rename_keys: rename_key(a , a , a ) # load HuggingFace model a = SwiftFormerForImageClassification(a ).eval() hf_model.load_state_dict(a ) # prepare test inputs a = prepare_img() a = ViTImageProcessor.from_pretrained('''preprocessor_config''' ) a = processor(images=a , return_tensors='''pt''' ) # compare outputs from both models a = get_expected_output(a ) a = hf_model(inputs['''pixel_values'''] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , a , atol=1e-3 ) Path(a ).mkdir(exist_ok=a ) print(F"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swiftformer_name", default="swiftformer_xs", choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"], type=str, help="Name of the SwiftFormer model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default="./converted_outputs/", type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.") UpperCAmelCase__ = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
26
0
from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Dict , __UpperCAmelCase : Distribution , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : int=None , __UpperCAmelCase : Tuple=0 ) ->List[Any]: """simple docstring""" a = 1.0 if scale is None else scale a = 0.0 if loc is None else loc super().__init__(__UpperCAmelCase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=__UpperCAmelCase )] ) @property def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return self.base_dist.mean * self.scale + self.loc @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" return self.base_dist.variance * self.scale**2 @property def __lowerCAmelCase ( self : Dict ) ->List[str]: """simple docstring""" return self.variance.sqrt() class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : int , __UpperCAmelCase : Dict[str, int] , __UpperCAmelCase : Callable[..., Tuple[torch.Tensor]] , **__UpperCAmelCase : Union[str, Any] ) ->None: """simple docstring""" super().__init__(**__UpperCAmelCase ) a = args_dim a = nn.ModuleList([nn.Linear(__UpperCAmelCase , __UpperCAmelCase ) for dim in args_dim.values()] ) a = domain_map def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : torch.Tensor ) ->Tuple[torch.Tensor]: """simple docstring""" a = [proj(__UpperCAmelCase ) for proj in self.proj] return self.domain_map(*__UpperCAmelCase ) class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : Tuple ) ->Optional[int]: """simple docstring""" super().__init__() a = function def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : int , *__UpperCAmelCase : List[str] ) ->Optional[int]: """simple docstring""" return self.function(__UpperCAmelCase , *__UpperCAmelCase ) class lowercase_ : '''simple docstring''' __snake_case = 42 __snake_case = 42 __snake_case = 42 def __init__( self : Optional[Any] , __UpperCAmelCase : int = 1 ) ->None: """simple docstring""" a = dim a = {k: dim * self.args_dim[k] for k in self.args_dim} def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[Any] ) ->List[Any]: """simple docstring""" if self.dim == 1: return self.distribution_class(*__UpperCAmelCase ) else: return Independent(self.distribution_class(*__UpperCAmelCase ) , 1 ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None , ) ->Distribution: """simple docstring""" a = self._base_distribution(__UpperCAmelCase ) if loc is None and scale is None: return distr else: return AffineTransformed(__UpperCAmelCase , loc=__UpperCAmelCase , scale=__UpperCAmelCase , event_dim=self.event_dim ) @property def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" return () if self.dim == 1 else (self.dim,) @property def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" return len(self.event_shape ) @property def __lowerCAmelCase ( self : Optional[int] ) ->float: """simple docstring""" return 0.0 def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : int ) ->nn.Module: """simple docstring""" return ParameterProjection( in_features=__UpperCAmelCase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def __lowerCAmelCase ( self : List[str] , *__UpperCAmelCase : torch.Tensor ) ->int: """simple docstring""" raise NotImplementedError() @staticmethod def __lowerCAmelCase ( __UpperCAmelCase : torch.Tensor ) ->torch.Tensor: """simple docstring""" return (x + torch.sqrt(torch.square(__UpperCAmelCase ) + 4.0 )) / 2.0 class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = {'''df''': 1, '''loc''': 1, '''scale''': 1} __snake_case = StudentT @classmethod def __lowerCAmelCase ( cls : Union[str, Any] , __UpperCAmelCase : torch.Tensor , __UpperCAmelCase : torch.Tensor , __UpperCAmelCase : torch.Tensor ) ->int: """simple docstring""" a = cls.squareplus(__UpperCAmelCase ).clamp_min(torch.finfo(scale.dtype ).eps ) a = 2.0 + cls.squareplus(__UpperCAmelCase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = {'''loc''': 1, '''scale''': 1} __snake_case = Normal @classmethod def __lowerCAmelCase ( cls : Dict , __UpperCAmelCase : torch.Tensor , __UpperCAmelCase : torch.Tensor ) ->Union[str, Any]: """simple docstring""" a = cls.squareplus(__UpperCAmelCase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = {'''total_count''': 1, '''logits''': 1} __snake_case = NegativeBinomial @classmethod def __lowerCAmelCase ( cls : Optional[int] , __UpperCAmelCase : torch.Tensor , __UpperCAmelCase : torch.Tensor ) ->int: """simple docstring""" a = cls.squareplus(__UpperCAmelCase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Union[str, Any] ) ->Distribution: """simple docstring""" a , a = distr_args if self.dim == 1: return self.distribution_class(total_count=__UpperCAmelCase , logits=__UpperCAmelCase ) else: return Independent(self.distribution_class(total_count=__UpperCAmelCase , logits=__UpperCAmelCase ) , 1 ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None ) ->Distribution: """simple docstring""" a , a = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
357
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : DDPMScheduler , __UpperCAmelCase : Optional[int] , ) ->List[str]: """simple docstring""" super().__init__() a = value_function a = unet a = scheduler a = env a = env.get_dataset() a = {} for key in self.data.keys(): try: a = self.data[key].mean() except: # noqa: E722 pass a = {} for key in self.data.keys(): try: a = self.data[key].std() except: # noqa: E722 pass a = env.observation_space.shape[0] a = env.action_space.shape[0] def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] ) ->Dict: """simple docstring""" return (x_in - self.means[key]) / self.stds[key] def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict ) ->List[str]: """simple docstring""" return x_in * self.stds[key] + self.means[key] def __lowerCAmelCase ( self : int , __UpperCAmelCase : int ) ->List[str]: """simple docstring""" if type(__UpperCAmelCase ) is dict: return {k: self.to_torch(__UpperCAmelCase ) for k, v in x_in.items()} elif torch.is_tensor(__UpperCAmelCase ): return x_in.to(self.unet.device ) return torch.tensor(__UpperCAmelCase , device=self.unet.device ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple ) ->int: """simple docstring""" for key, val in cond.items(): a = val.clone() return x_in def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = x.shape[0] a = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model a = torch.full((batch_size,) , __UpperCAmelCase , device=self.unet.device , dtype=torch.long ) for _ in range(__UpperCAmelCase ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models a = self.value_function(x.permute(0 , 2 , 1 ) , __UpperCAmelCase ).sample a = torch.autograd.grad([y.sum()] , [x] )[0] a = self.scheduler._get_variance(__UpperCAmelCase ) a = torch.exp(0.5 * posterior_variance ) a = model_std * grad a = 0 a = x.detach() a = x + scale * grad a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.unet(x.permute(0 , 2 , 1 ) , __UpperCAmelCase ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg a = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , predict_epsilon=__UpperCAmelCase )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.to_torch(__UpperCAmelCase ) return x, y def __call__( self : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int]=64 , __UpperCAmelCase : int=32 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : str=0.1 ) ->List[str]: """simple docstring""" a = self.normalize(__UpperCAmelCase , '''observations''' ) a = obs[None].repeat(__UpperCAmelCase , axis=0 ) a = {0: self.to_torch(__UpperCAmelCase )} a = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) a = randn_tensor(__UpperCAmelCase , device=self.unet.device ) a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.to_torch(__UpperCAmelCase ) # run the diffusion process a , a = self.run_diffusion(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # sort output trajectories by value a = y.argsort(0 , descending=__UpperCAmelCase ).squeeze() a = x[sorted_idx] a = sorted_values[:, :, : self.action_dim] a = actions.detach().cpu().numpy() a = self.de_normalize(__UpperCAmelCase , key='''actions''' ) # select the action with the highest value if y is not None: a = 0 else: # if we didn't run value guiding, select a random action a = np.random.randint(0 , __UpperCAmelCase ) a = denorm_actions[selected_index, 0] return denorm_actions
26
0
from __future__ import annotations import math def _a ( a :int ) -> list[int]: if num <= 0: a = F"""{num}: Invalid input, please enter a positive integer.""" raise ValueError(a ) a = [True] * (num + 1) a = [] a = 2 a = int(math.sqrt(a ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(a ) # Set multiples of start be False for i in range(start * start , num + 1 , a ): if sieve[i] is True: a = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(a ) return prime if __name__ == "__main__": print(prime_sieve(int(input("Enter a positive integer: ").strip())))
358
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 UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "spiece.model"} UpperCAmelCase__ = { "vocab_file": { "TsinghuaAI/CPM-Generate": "https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model", } } class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Any=True , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : List[str]="<s>" , __UpperCAmelCase : int="</s>" , __UpperCAmelCase : Any="<unk>" , __UpperCAmelCase : Optional[Any]="<sep>" , __UpperCAmelCase : int="<pad>" , __UpperCAmelCase : Any="<cls>" , __UpperCAmelCase : List[str]="<mask>" , __UpperCAmelCase : Optional[int]=["<eop>", "<eod>"] , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : Union[str, Any] , ) ->None: """simple docstring""" a = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) a = 3 a = do_lower_case a = remove_space a = keep_accents a = vocab_file a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) a = jieba a = str.maketrans(''' \n''' , '''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" return len(self.sp_model ) def __lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" a = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = self.__dict__.copy() a = None return state def __setstate__( self : List[str] , __UpperCAmelCase : Optional[int] ) ->str: """simple docstring""" a = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a = {} a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] ) ->List[str]: """simple docstring""" if self.remove_space: a = ''' '''.join(inputs.strip().split() ) else: a = inputs a = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: a = unicodedata.normalize('''NFKD''' , __UpperCAmelCase ) a = ''''''.join([c for c in outputs if not unicodedata.combining(__UpperCAmelCase )] ) if self.do_lower_case: a = outputs.lower() return outputs def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = self.preprocess_text(__UpperCAmelCase ) a = self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) a = [] for piece in pieces: if len(__UpperCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): a = self.sp_model.EncodeAsPieces(piece[:-1].replace(__UpperCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: a = cur_pieces[1:] else: a = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__UpperCAmelCase ) else: new_pieces.append(__UpperCAmelCase ) return new_pieces def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Any ) ->Any: """simple docstring""" return self.sp_model.PieceToId(__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Dict ) ->Union[str, Any]: """simple docstring""" return self.sp_model.IdToPiece(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = ''''''.join(__UpperCAmelCase ).replace(__UpperCAmelCase , ''' ''' ).strip() return out_string def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase , token_ids_a=__UpperCAmelCase , already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is not None: return ([0] * len(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] return ([0] * len(__UpperCAmelCase )) + [1, 1] def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a = os.path.join( __UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase , '''wb''' ) as fi: a = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,) def __lowerCAmelCase ( self : Any , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = super()._decode(*__UpperCAmelCase , **__UpperCAmelCase ) a = text.replace(''' ''' , '''''' ).replace('''\u2582''' , ''' ''' ).replace('''\u2583''' , '''\n''' ) return text
26
0
"""simple docstring""" print((lambda quine: quine % quine)("print((lambda quine: quine %% quine)(%r))"))
359
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def _a ( a :Union[str, Any] , a :List[Any] ) -> List[Any]: a = checkpoint a = {} a = vae_state_dict['''encoder.conv_in.weight'''] a = vae_state_dict['''encoder.conv_in.bias'''] a = vae_state_dict['''encoder.conv_out.weight'''] a = vae_state_dict['''encoder.conv_out.bias'''] a = vae_state_dict['''encoder.norm_out.weight'''] a = vae_state_dict['''encoder.norm_out.bias'''] a = vae_state_dict['''decoder.conv_in.weight'''] a = vae_state_dict['''decoder.conv_in.bias'''] a = vae_state_dict['''decoder.conv_out.weight'''] a = vae_state_dict['''decoder.conv_out.bias'''] a = vae_state_dict['''decoder.norm_out.weight'''] a = vae_state_dict['''decoder.norm_out.bias'''] a = vae_state_dict['''quant_conv.weight'''] a = vae_state_dict['''quant_conv.bias'''] a = vae_state_dict['''post_quant_conv.weight'''] a = vae_state_dict['''post_quant_conv.bias'''] # Retrieves the keys for the encoder down blocks only a = len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''encoder.down''' in layer} ) a = { layer_id: [key for key in vae_state_dict if F"""down.{layer_id}""" in key] for layer_id in range(a ) } # Retrieves the keys for the decoder up blocks only a = len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''decoder.up''' in layer} ) a = { layer_id: [key for key in vae_state_dict if F"""up.{layer_id}""" in key] for layer_id in range(a ) } for i in range(a ): a = [key for key in down_blocks[i] if F"""down.{i}""" in key and F"""down.{i}.downsample""" not in key] if F"""encoder.down.{i}.downsample.conv.weight""" in vae_state_dict: a = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.weight""" ) a = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.bias""" ) a = renew_vae_resnet_paths(a ) a = {'''old''': F"""down.{i}.block""", '''new''': F"""down_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''encoder.mid.block''' in key] a = 2 for i in range(1 , num_mid_res_blocks + 1 ): a = [key for key in mid_resnets if F"""encoder.mid.block_{i}""" in key] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""mid.block_{i}""", '''new''': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''encoder.mid.attn''' in key] a = renew_vae_attention_paths(a ) a = {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) for i in range(a ): a = num_up_blocks - 1 - i a = [ key for key in up_blocks[block_id] if F"""up.{block_id}""" in key and F"""up.{block_id}.upsample""" not in key ] if F"""decoder.up.{block_id}.upsample.conv.weight""" in vae_state_dict: a = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.weight""" ] a = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.bias""" ] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""up.{block_id}.block""", '''new''': F"""up_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''decoder.mid.block''' in key] a = 2 for i in range(1 , num_mid_res_blocks + 1 ): a = [key for key in mid_resnets if F"""decoder.mid.block_{i}""" in key] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""mid.block_{i}""", '''new''': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''decoder.mid.attn''' in key] a = renew_vae_attention_paths(a ) a = {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) return new_checkpoint def _a ( a :str , a :str , ) -> List[str]: # Only support V1 a = requests.get( ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml''' ) a = io.BytesIO(r.content ) a = OmegaConf.load(a ) a = 512 a = '''cuda''' if torch.cuda.is_available() else '''cpu''' if checkpoint_path.endswith('''safetensors''' ): from safetensors import safe_open a = {} with safe_open(a , framework='''pt''' , device='''cpu''' ) as f: for key in f.keys(): a = f.get_tensor(a ) else: a = torch.load(a , map_location=a )['''state_dict'''] # Convert the VAE model. a = create_vae_diffusers_config(a , image_size=a ) a = custom_convert_ldm_vae_checkpoint(a , a ) a = AutoencoderKL(**a ) vae.load_state_dict(a ) vae.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--vae_pt_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") UpperCAmelCase__ = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
26
0
from __future__ import annotations def _a ( a :dict , a :str ) -> set[str]: a , a = set(a ), [start] while stack: a = stack.pop() explored.add(a ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a ) return explored UpperCAmelCase__ = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, "A"))
360
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''image_processor''', '''tokenizer'''] __snake_case = '''CLIPImageProcessor''' __snake_case = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Dict , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : Optional[Any] ) ->List[str]: """simple docstring""" a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __UpperCAmelCase , ) a = kwargs.pop('''feature_extractor''' ) a = 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__(__UpperCAmelCase , __UpperCAmelCase ) def __call__( self : List[str] , __UpperCAmelCase : Any=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Any=None , **__UpperCAmelCase : str ) ->Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: a = self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if images is not None: a = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is not None and images is not None: a = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__UpperCAmelCase ) , tensor_type=__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : str , **__UpperCAmelCase : Tuple ) ->Any: """simple docstring""" return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a = self.tokenizer.model_input_names a = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __UpperCAmelCase , ) return self.image_processor_class @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __UpperCAmelCase , ) return self.image_processor
26
0
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class lowercase_ : '''simple docstring''' __snake_case = PegasusConfig __snake_case = {} __snake_case = '''gelu''' def __init__( self : Optional[int] , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[str]=13 , __UpperCAmelCase : List[Any]=7 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : List[Any]=False , __UpperCAmelCase : str=99 , __UpperCAmelCase : List[Any]=32 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : Any=4 , __UpperCAmelCase : Tuple=37 , __UpperCAmelCase : str=0.1 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : List[Any]=40 , __UpperCAmelCase : List[str]=2 , __UpperCAmelCase : int=1 , __UpperCAmelCase : List[Any]=0 , ) ->Union[str, Any]: """simple docstring""" a = parent a = batch_size a = seq_length a = is_training a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = eos_token_id a = pad_token_id a = bos_token_id def __lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" a = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) a = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) a = tf.concat([input_ids, eos_tensor] , axis=1 ) a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) a = prepare_pegasus_inputs_dict(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) return config, inputs_dict def __lowerCAmelCase ( self : int , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[int] ) ->List[Any]: """simple docstring""" a = TFPegasusModel(config=__UpperCAmelCase ).get_decoder() a = inputs_dict['''input_ids'''] a = input_ids[:1, :] a = inputs_dict['''attention_mask'''][:1, :] a = inputs_dict['''head_mask'''] a = 1 # first forward pass a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , head_mask=__UpperCAmelCase , use_cache=__UpperCAmelCase ) a , a = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids a = ids_tensor((self.batch_size, 3) , config.vocab_size ) a = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and a = tf.concat([input_ids, next_tokens] , axis=-1 ) a = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase )[0] a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice a = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) a = output_from_no_past[:, -3:, random_slice_idx] a = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__UpperCAmelCase , __UpperCAmelCase , rtol=1e-3 ) def _a ( a :Any , a :Optional[Any] , a :int , a :Tuple=None , a :Optional[int]=None , a :List[Any]=None , a :int=None , a :Any=None , ) -> Union[str, Any]: if attention_mask is None: a = tf.cast(tf.math.not_equal(a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: a = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: a = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: a = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: a = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowercase_ ( lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () __snake_case = (TFPegasusForConditionalGeneration,) if is_tf_available() else () __snake_case = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) __snake_case = True __snake_case = False __snake_case = False def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = TFPegasusModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__UpperCAmelCase ) @require_sentencepiece @require_tokenizers @require_tf class lowercase_ ( unittest.TestCase ): '''simple docstring''' __snake_case = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] __snake_case = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers __snake_case = '''google/pegasus-xsum''' @cached_property def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" a = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __lowerCAmelCase ( self : Tuple , **__UpperCAmelCase : List[Any] ) ->Dict: """simple docstring""" a = self.translate_src_text(**__UpperCAmelCase ) assert self.expected_text == generated_words def __lowerCAmelCase ( self : Tuple , **__UpperCAmelCase : Dict ) ->Optional[int]: """simple docstring""" a = self.tokenizer(self.src_text , **__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors='''tf''' ) a = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__UpperCAmelCase , ) a = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__UpperCAmelCase ) return generated_words @slow def __lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" self._assert_generated_batch_equal_expected()
361
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } UpperCAmelCase__ = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } UpperCAmelCase__ = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = ['''input_ids''', '''attention_mask'''] __snake_case = DistilBertTokenizer def __init__( self : Dict , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[int]="[UNK]" , __UpperCAmelCase : str="[SEP]" , __UpperCAmelCase : Tuple="[PAD]" , __UpperCAmelCase : Any="[CLS]" , __UpperCAmelCase : int="[MASK]" , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : str , ) ->Optional[int]: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int]=None ) ->Optional[Any]: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
26
0
from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge UpperCAmelCase__ = [ "Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of the" " final seconds on board Flight 9525. The Germanwings co-pilot says he had a \"previous episode of severe" " depression\" German airline confirms it knew of Andreas Lubitz's depression years before he took control.", "The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal" " accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC's" " founding Rome Statute in January. Israel and the United States opposed the Palestinians' efforts to join the" " body.", "Amnesty International releases its annual report on the death penalty. The report catalogs the use of" " state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the" " world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital" " punishment.", ] UpperCAmelCase__ = [ "Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports ." " Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz" " had informed his Lufthansa training school of an episode of severe depression, airline says .", "Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June ." " Israel and the United States opposed the move, which could open the door to war crimes investigations against" " Israelis .", "Amnesty's annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to" " death . Organization claims that governments around the world are using the threat of terrorism to advance" " executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death" " sentences up by 28% .", ] def _a ( ) -> Optional[Any]: a = calculate_rouge(a , a , bootstrap_aggregation=a , rouge_keys=['''rouge2''', '''rougeL'''] ) assert isinstance(a , a ) a = calculate_rouge(a , a , bootstrap_aggregation=a , rouge_keys=['''rouge2'''] ) assert ( pd.DataFrame(no_aggregation['''rouge2'''] ).fmeasure.mean() == pd.DataFrame(no_aggregation_just_ra['''rouge2'''] ).fmeasure.mean() ) def _a ( ) -> int: a = '''rougeLsum''' a = calculate_rouge(a , a , newline_sep=a , rouge_keys=[k] )[k] a = calculate_rouge(a , a , newline_sep=a , rouge_keys=[k] )[k] assert score > score_no_sep def _a ( ) -> int: a = ['''rouge1''', '''rouge2''', '''rougeL'''] a = calculate_rouge(a , a , newline_sep=a , rouge_keys=a ) a = calculate_rouge(a , a , newline_sep=a , rouge_keys=a ) assert score_sep == score_no_sep def _a ( ) -> Union[str, Any]: a = [ '''Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.''', '''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .''', ] a = [ '''Margot Frank, died in 1945, a month earlier than previously thought.''', '''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of''' ''' the final seconds on board Flight 9525.''', ] assert calculate_rouge(a , a , newline_sep=a ) == calculate_rouge(a , a , newline_sep=a ) def _a ( ) -> str: a = [ '''" "a person who has such a video needs to immediately give it to the investigators," prosecutor says .<n> "it is a very disturbing scene," editor-in-chief of bild online tells "erin burnett: outfront" ''' ] a = [ ''' Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports . Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says .''' ] a = calculate_rouge(a , a , rouge_keys=['''rougeLsum'''] , newline_sep=a )['''rougeLsum'''] a = calculate_rouge(a , a , rouge_keys=['''rougeLsum'''] )['''rougeLsum'''] assert new_score > prev_score def _a ( ) -> int: a = Path('''examples/seq2seq/test_data/wmt_en_ro''' ) a = calculate_rouge_path(data_dir.joinpath('''test.source''' ) , data_dir.joinpath('''test.target''' ) ) assert isinstance(a , a ) a = calculate_rouge_path( data_dir.joinpath('''test.source''' ) , data_dir.joinpath('''test.target''' ) , bootstrap_aggregation=a ) assert isinstance(a , a )
362
from __future__ import annotations import typing from collections import Counter def _a ( a :int ) -> typing.Counter[int]: a = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(a , max_perimeter + 1 ): a = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(a ): a = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _a ( a :int = 1_000 ) -> int: a = pythagorean_triple(a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f"""Perimeter {solution()} has maximum solutions""")
26
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "xlm-mlm-en-2048": "https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json", "xlm-mlm-ende-1024": "https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json", "xlm-mlm-enfr-1024": "https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json", "xlm-mlm-enro-1024": "https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json", "xlm-mlm-tlm-xnli15-1024": "https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json", "xlm-mlm-xnli15-1024": "https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json", "xlm-clm-enfr-1024": "https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json", "xlm-clm-ende-1024": "https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json", "xlm-mlm-17-1280": "https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json", "xlm-mlm-100-1280": "https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json", } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''xlm''' __snake_case = { '''hidden_size''': '''emb_dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', '''n_words''': '''vocab_size''', # For backward compatibility } def __init__( self : Any , __UpperCAmelCase : Union[str, Any]=30_145 , __UpperCAmelCase : int=2_048 , __UpperCAmelCase : Union[str, Any]=12 , __UpperCAmelCase : List[str]=16 , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : Any=0.1 , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Tuple=False , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Any=False , __UpperCAmelCase : List[str]=1 , __UpperCAmelCase : int=True , __UpperCAmelCase : str=512 , __UpperCAmelCase : int=2_048**-0.5 , __UpperCAmelCase : Optional[Any]=1e-1_2 , __UpperCAmelCase : Tuple=0.02 , __UpperCAmelCase : Optional[int]=0 , __UpperCAmelCase : Dict=1 , __UpperCAmelCase : str=2 , __UpperCAmelCase : int=3 , __UpperCAmelCase : Optional[int]=5 , __UpperCAmelCase : int=True , __UpperCAmelCase : str="first" , __UpperCAmelCase : Optional[Any]=True , __UpperCAmelCase : Tuple=None , __UpperCAmelCase : Any=True , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : Any=5 , __UpperCAmelCase : List[str]=5 , __UpperCAmelCase : List[str]=0 , __UpperCAmelCase : Union[str, Any]=0 , __UpperCAmelCase : str=2 , __UpperCAmelCase : Optional[int]=0 , **__UpperCAmelCase : Dict , ) ->int: """simple docstring""" a = vocab_size a = emb_dim a = n_layers a = n_heads a = dropout a = attention_dropout a = gelu_activation a = sinusoidal_embeddings a = causal a = asm a = n_langs a = use_lang_emb a = layer_norm_eps a = bos_index a = eos_index a = pad_index a = unk_index a = mask_index a = is_encoder a = max_position_embeddings a = embed_init_std a = init_std a = summary_type a = summary_use_proj a = summary_activation a = summary_proj_to_labels a = summary_first_dropout a = start_n_top a = end_n_top a = mask_token_id a = lang_id if "n_words" in kwargs: a = kwargs['''n_words'''] super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : List[Any] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": a = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: a = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
363
from __future__ import annotations def _a ( a :dict , a :str ) -> set[str]: a , a = set(a ), [start] while stack: a = stack.pop() explored.add(a ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a ) return explored UpperCAmelCase__ = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, "A"))
26
0
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position UpperCAmelCase__ = "2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip UpperCAmelCase__ = concatenate_datasets UpperCAmelCase__ = DownloadConfig UpperCAmelCase__ = DownloadManager UpperCAmelCase__ = DownloadMode UpperCAmelCase__ = DownloadConfig UpperCAmelCase__ = DownloadMode UpperCAmelCase__ = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
364
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase__ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex UpperCAmelCase__ = 10 UpperCAmelCase__ = 256 def _a ( a :List[str] ) -> Optional[MinHash]: if len(a ) < MIN_NUM_TOKENS: return None a = MinHash(num_perm=a ) for token in set(a ): min_hash.update(token.encode() ) return min_hash def _a ( a :str ) -> Set[str]: return {t for t in NON_ALPHA.split(a ) if len(t.strip() ) > 0} class lowercase_ : '''simple docstring''' def __init__( self : Any , *, __UpperCAmelCase : float = 0.85 , ) ->Dict: """simple docstring""" a = duplication_jaccard_threshold a = NUM_PERM a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) a = defaultdict(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : MinHash ) ->None: """simple docstring""" a = self._index.query(__UpperCAmelCase ) if code_key in self._index.keys: print(F"""Duplicate key {code_key}""" ) return self._index.insert(__UpperCAmelCase , __UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__UpperCAmelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->List[List[Dict]]: """simple docstring""" a = [] for base, duplicates in self._duplicate_clusters.items(): a = [base] + list(__UpperCAmelCase ) # reformat the cluster to be a list of dict a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(__UpperCAmelCase ) return duplicate_clusters def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Dict ) ->None: """simple docstring""" a = self.get_duplicate_clusters() with open(__UpperCAmelCase , '''w''' ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def _a ( a :List[Any] ) -> List[Any]: a , a = element a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _a ( a :Type[Dataset] ) -> List[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(a , max_queue_size=10_000 ) , chunksize=100 , ): if data is not None: yield data def _a ( a :Type[Dataset] , a :float ) -> str: a = DuplicationIndex(duplication_jaccard_threshold=a ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a ) ) , max_queue_size=100 ) ): di.add(a , a ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _a ( a :str , a :str ) -> float: a = get_tokens(a ) a = get_tokens(a ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase__ = None def _a ( a :Tuple , a :Tuple ) -> Any: a = [] for elementa in cluster: a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(a , a ) >= jaccard_threshold: elementa["copies"] += 1 break else: a = 1 extremes.append(a ) return extremes def _a ( a :List[Any] , a :Optional[Any] , a :Union[str, Any] ) -> Optional[int]: global _shared_dataset a = dataset a = [] a = partial(_find_cluster_extremes_shared , jaccard_threshold=a ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( a , a , ) , total=len(a ) , ): extremes_list.append(a ) return extremes_list def _a ( a :Type[Dataset] , a :float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: a = make_duplicate_clusters(a , a ) a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} a = {} a = find_extremes(a , a , a ) for extremes in extremes_clusters: for element in extremes: a = element a = duplicate_indices - set(extreme_dict.keys() ) a = dataset.filter(lambda a , a : idx not in remove_indices , with_indices=a ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: a = element['''base_index'''] in extreme_dict if element["is_extreme"]: a = extreme_dict[element['''base_index''']]['''copies'''] print(F"""Original dataset size: {len(a )}""" ) print(F"""Number of duplicate clusters: {len(a )}""" ) print(F"""Files in duplicate cluster: {len(a )}""" ) print(F"""Unique files in duplicate cluster: {len(a )}""" ) print(F"""Filtered dataset size: {len(a )}""" ) return ds_filter, duplicate_clusters
26
0
from math import ceil, sqrt def _a ( a :int = 1_000_000 ) -> int: a = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: a = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
365
from math import ceil, sqrt def _a ( a :int = 1_000_000 ) -> int: a = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: a = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
26
0
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : List[Any] , *__UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : List[Any]=None , **__UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" super().__init__(*__UpperCAmelCase , **__UpperCAmelCase ) a = eval_examples a = post_process_function def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Optional[Dataset] = None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Optional[List[str]] = None , __UpperCAmelCase : str = "eval" , **__UpperCAmelCase : Any , ) ->Dict[str, float]: """simple docstring""" a = gen_kwargs.copy() a = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) a = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) a = gen_kwargs a = self.eval_dataset if eval_dataset is None else eval_dataset a = self.get_eval_dataloader(__UpperCAmelCase ) a = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. a = self.compute_metrics a = None a = time.time() a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: a = eval_loop( __UpperCAmelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__UpperCAmelCase , metric_key_prefix=__UpperCAmelCase , ) finally: a = compute_metrics a = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __UpperCAmelCase , __UpperCAmelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default a = self.post_process_function(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = self.compute_metrics(__UpperCAmelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): a = metrics.pop(__UpperCAmelCase ) metrics.update(output.metrics ) else: a = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__UpperCAmelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) a = self.callback_handler.on_evaluate(self.args , self.state , self.control , __UpperCAmelCase ) return metrics def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : int=None , __UpperCAmelCase : str = "test" , **__UpperCAmelCase : Any ) ->int: """simple docstring""" a = gen_kwargs.copy() a = self.get_test_dataloader(__UpperCAmelCase ) # Temporarily disable metric computation, we will do it in the loop here. a = self.compute_metrics a = None a = time.time() a = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: a = eval_loop( __UpperCAmelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__UpperCAmelCase , metric_key_prefix=__UpperCAmelCase , ) finally: a = compute_metrics a = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __UpperCAmelCase , __UpperCAmelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output a = self.post_process_function(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , '''predict''' ) a = self.compute_metrics(__UpperCAmelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): a = metrics.pop(__UpperCAmelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__UpperCAmelCase )
366
UpperCAmelCase__ = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
26
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "bigcode/gpt_bigcode-santacoder": "https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json", } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''gpt_bigcode''' __snake_case = ['''past_key_values'''] __snake_case = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : List[Any] , __UpperCAmelCase : Union[str, Any]=50_257 , __UpperCAmelCase : Optional[Any]=1_024 , __UpperCAmelCase : int=768 , __UpperCAmelCase : List[str]=12 , __UpperCAmelCase : str=12 , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Optional[Any]="gelu_pytorch_tanh" , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : Any=0.1 , __UpperCAmelCase : str=1e-5 , __UpperCAmelCase : Union[str, Any]=0.02 , __UpperCAmelCase : int=True , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Dict=50_256 , __UpperCAmelCase : Optional[int]=50_256 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : int=True , __UpperCAmelCase : int=True , **__UpperCAmelCase : str , ) ->Optional[int]: """simple docstring""" a = vocab_size a = n_positions a = n_embd a = n_layer a = n_head a = n_inner a = activation_function a = resid_pdrop a = embd_pdrop a = attn_pdrop a = layer_norm_epsilon a = initializer_range a = scale_attn_weights a = use_cache a = attention_softmax_in_fpaa a = scale_attention_softmax_in_fpaa a = multi_query a = bos_token_id a = eos_token_id super().__init__(bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase )
367
def _a ( a :list ) -> list: if len(a ) <= 1: return lst a = 1 while i < len(a ): if lst[i - 1] <= lst[i]: i += 1 else: a , a = lst[i], lst[i - 1] i -= 1 if i == 0: a = 1 return lst if __name__ == "__main__": UpperCAmelCase__ = input("Enter numbers separated by a comma:\n").strip() UpperCAmelCase__ = [int(item) for item in user_input.split(",")] print(gnome_sort(unsorted))
26
0
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: UpperCAmelCase__ = None UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "vocab_file": { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/spiece.model", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/spiece.model", }, "tokenizer_file": { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json", }, } UpperCAmelCase__ = { "google/fnet-base": 512, "google/fnet-large": 512, } UpperCAmelCase__ = "▁" class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ['''input_ids''', '''token_type_ids'''] __snake_case = FNetTokenizer def __init__( self : List[str] , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Union[str, Any]=False , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Dict="<unk>" , __UpperCAmelCase : Optional[Any]="[SEP]" , __UpperCAmelCase : List[str]="<pad>" , __UpperCAmelCase : Optional[int]="[CLS]" , __UpperCAmelCase : Any="[MASK]" , **__UpperCAmelCase : Tuple , ) ->List[Any]: """simple docstring""" a = ( AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase , normalized=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token ) super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , **__UpperCAmelCase , ) a = do_lower_case a = remove_space a = keep_accents a = vocab_file a = False if not self.vocab_file else True def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : str , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a = os.path.join( __UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) return (out_vocab_file,)
368
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase__ = "\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)[\"depth\"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline(\"depth-estimation\")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to(\"cuda\")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to(\"cuda\")\n\n\n >>> img = load_image(\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n ... \"/kandinsky/cat.png\"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")\n\n >>> prompt = \"A robot, 4k photo\"\n >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"\n\n >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save(\"robot_cat.png\")\n ```\n" def _a ( a :Tuple , a :str , a :List[str]=8 ) -> Any: a = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Dict , __UpperCAmelCase : UNetaDConditionModel , __UpperCAmelCase : DDPMScheduler , __UpperCAmelCase : VQModel , ) ->Optional[int]: """simple docstring""" super().__init__() self.register_modules( unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , movq=__UpperCAmelCase , ) a = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : int , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : str ) ->str: """simple docstring""" if latents is None: a = randn_tensor(__UpperCAmelCase , generator=__UpperCAmelCase , device=__UpperCAmelCase , dtype=__UpperCAmelCase ) else: if latents.shape != shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) a = latents.to(__UpperCAmelCase ) a = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : List[str]=0 ) ->Dict: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a = torch.device(F"""cuda:{gpu_id}""" ) a = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : int , __UpperCAmelCase : Union[str, Any]=0 ) ->Dict: """simple docstring""" if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=__UpperCAmelCase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a = None for cpu_offloaded_model in [self.unet, self.movq]: a , a = cpu_offload_with_hook(__UpperCAmelCase , __UpperCAmelCase , prev_module_hook=__UpperCAmelCase ) # We'll offload the last model manually. a = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(__UpperCAmelCase , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__UpperCAmelCase ) def __call__( self : List[str] , __UpperCAmelCase : Union[torch.FloatTensor, List[torch.FloatTensor]] , __UpperCAmelCase : Union[torch.FloatTensor, List[torch.FloatTensor]] , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : int = 512 , __UpperCAmelCase : int = 512 , __UpperCAmelCase : int = 100 , __UpperCAmelCase : float = 4.0 , __UpperCAmelCase : int = 1 , __UpperCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , ) ->List[Any]: """simple docstring""" a = self._execution_device a = guidance_scale > 1.0 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = torch.cat(__UpperCAmelCase , dim=0 ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = torch.cat(__UpperCAmelCase , dim=0 ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = torch.cat(__UpperCAmelCase , dim=0 ) a = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a = image_embeds.repeat_interleave(__UpperCAmelCase , dim=0 ) a = negative_image_embeds.repeat_interleave(__UpperCAmelCase , dim=0 ) a = hint.repeat_interleave(__UpperCAmelCase , dim=0 ) a = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__UpperCAmelCase ) a = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=__UpperCAmelCase ) self.scheduler.set_timesteps(__UpperCAmelCase , device=__UpperCAmelCase ) a = self.scheduler.timesteps a = self.movq.config.latent_channels a , a = downscale_height_and_width(__UpperCAmelCase , __UpperCAmelCase , self.movq_scale_factor ) # create initial latent a = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(__UpperCAmelCase ) ): # expand the latents if we are doing classifier free guidance a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a = {'''image_embeds''': image_embeds, '''hint''': hint} a = self.unet( sample=__UpperCAmelCase , timestep=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , added_cond_kwargs=__UpperCAmelCase , return_dict=__UpperCAmelCase , )[0] if do_classifier_free_guidance: a , a = noise_pred.split(latents.shape[1] , dim=1 ) a , a = noise_pred.chunk(2 ) a , a = variance_pred.chunk(2 ) a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a , a = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a = self.scheduler.step( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase , )[0] # post-processing a = self.movq.decode(__UpperCAmelCase , force_not_quantize=__UpperCAmelCase )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: a = image * 0.5 + 0.5 a = image.clamp(0 , 1 ) a = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCAmelCase )
369
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = OrderedDict( [ ("audio-spectrogram-transformer", "ASTFeatureExtractor"), ("beit", "BeitFeatureExtractor"), ("chinese_clip", "ChineseCLIPFeatureExtractor"), ("clap", "ClapFeatureExtractor"), ("clip", "CLIPFeatureExtractor"), ("clipseg", "ViTFeatureExtractor"), ("conditional_detr", "ConditionalDetrFeatureExtractor"), ("convnext", "ConvNextFeatureExtractor"), ("cvt", "ConvNextFeatureExtractor"), ("data2vec-audio", "Wav2Vec2FeatureExtractor"), ("data2vec-vision", "BeitFeatureExtractor"), ("deformable_detr", "DeformableDetrFeatureExtractor"), ("deit", "DeiTFeatureExtractor"), ("detr", "DetrFeatureExtractor"), ("dinat", "ViTFeatureExtractor"), ("donut-swin", "DonutFeatureExtractor"), ("dpt", "DPTFeatureExtractor"), ("encodec", "EncodecFeatureExtractor"), ("flava", "FlavaFeatureExtractor"), ("glpn", "GLPNFeatureExtractor"), ("groupvit", "CLIPFeatureExtractor"), ("hubert", "Wav2Vec2FeatureExtractor"), ("imagegpt", "ImageGPTFeatureExtractor"), ("layoutlmv2", "LayoutLMv2FeatureExtractor"), ("layoutlmv3", "LayoutLMv3FeatureExtractor"), ("levit", "LevitFeatureExtractor"), ("maskformer", "MaskFormerFeatureExtractor"), ("mctct", "MCTCTFeatureExtractor"), ("mobilenet_v1", "MobileNetV1FeatureExtractor"), ("mobilenet_v2", "MobileNetV2FeatureExtractor"), ("mobilevit", "MobileViTFeatureExtractor"), ("nat", "ViTFeatureExtractor"), ("owlvit", "OwlViTFeatureExtractor"), ("perceiver", "PerceiverFeatureExtractor"), ("poolformer", "PoolFormerFeatureExtractor"), ("regnet", "ConvNextFeatureExtractor"), ("resnet", "ConvNextFeatureExtractor"), ("segformer", "SegformerFeatureExtractor"), ("sew", "Wav2Vec2FeatureExtractor"), ("sew-d", "Wav2Vec2FeatureExtractor"), ("speech_to_text", "Speech2TextFeatureExtractor"), ("speecht5", "SpeechT5FeatureExtractor"), ("swiftformer", "ViTFeatureExtractor"), ("swin", "ViTFeatureExtractor"), ("swinv2", "ViTFeatureExtractor"), ("table-transformer", "DetrFeatureExtractor"), ("timesformer", "VideoMAEFeatureExtractor"), ("tvlt", "TvltFeatureExtractor"), ("unispeech", "Wav2Vec2FeatureExtractor"), ("unispeech-sat", "Wav2Vec2FeatureExtractor"), ("van", "ConvNextFeatureExtractor"), ("videomae", "VideoMAEFeatureExtractor"), ("vilt", "ViltFeatureExtractor"), ("vit", "ViTFeatureExtractor"), ("vit_mae", "ViTFeatureExtractor"), ("vit_msn", "ViTFeatureExtractor"), ("wav2vec2", "Wav2Vec2FeatureExtractor"), ("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"), ("wavlm", "Wav2Vec2FeatureExtractor"), ("whisper", "WhisperFeatureExtractor"), ("xclip", "CLIPFeatureExtractor"), ("yolos", "YolosFeatureExtractor"), ] ) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _a ( a :str ) -> Any: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: a = model_type_to_module_name(a ) a = importlib.import_module(F""".{module_name}""" , '''transformers.models''' ) try: return getattr(a , a ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(a , '''__name__''' , a ) == 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. a = importlib.import_module('''transformers''' ) if hasattr(a , a ): return getattr(a , a ) return None def _a ( a :Union[str, os.PathLike] , a :Optional[Union[str, os.PathLike]] = None , a :bool = False , a :bool = False , a :Optional[Dict[str, str]] = None , a :Optional[Union[bool, str]] = None , a :Optional[str] = None , a :bool = False , **a :int , ) -> Tuple: a = get_file_from_repo( a , a , cache_dir=a , force_download=a , resume_download=a , proxies=a , use_auth_token=a , revision=a , local_files_only=a , ) 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(a , encoding='''utf-8''' ) as reader: return json.load(a ) class lowercase_ : '''simple docstring''' def __init__( self : Tuple ) ->int: """simple docstring""" raise EnvironmentError( '''AutoFeatureExtractor is designed to be instantiated ''' '''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__UpperCAmelCase ) def __lowerCAmelCase ( cls : int , __UpperCAmelCase : Optional[Any] , **__UpperCAmelCase : Dict ) ->List[Any]: """simple docstring""" a = kwargs.pop('''config''' , __UpperCAmelCase ) a = kwargs.pop('''trust_remote_code''' , __UpperCAmelCase ) a = True a , a = FeatureExtractionMixin.get_feature_extractor_dict(__UpperCAmelCase , **__UpperCAmelCase ) a = config_dict.get('''feature_extractor_type''' , __UpperCAmelCase ) a = None if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a = 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(__UpperCAmelCase , __UpperCAmelCase ): a = AutoConfig.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) # It could be in `config.feature_extractor_type`` a = getattr(__UpperCAmelCase , '''feature_extractor_type''' , __UpperCAmelCase ) if hasattr(__UpperCAmelCase , '''auto_map''' ) and "AutoFeatureExtractor" in config.auto_map: a = config.auto_map['''AutoFeatureExtractor'''] if feature_extractor_class is not None: a = feature_extractor_class_from_name(__UpperCAmelCase ) a = feature_extractor_auto_map is not None a = feature_extractor_class is not None or type(__UpperCAmelCase ) in FEATURE_EXTRACTOR_MAPPING a = resolve_trust_remote_code( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if has_remote_code and trust_remote_code: a = get_class_from_dynamic_module( __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ) a = kwargs.pop('''code_revision''' , __UpperCAmelCase ) if os.path.isdir(__UpperCAmelCase ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(__UpperCAmelCase ) in FEATURE_EXTRACTOR_MAPPING: a = FEATURE_EXTRACTOR_MAPPING[type(__UpperCAmelCase )] return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) 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 __lowerCAmelCase ( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple ) ->Optional[int]: """simple docstring""" FEATURE_EXTRACTOR_MAPPING.register(__UpperCAmelCase , __UpperCAmelCase )
26
0
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = (DPMSolverSDEScheduler,) __snake_case = 10 def __lowerCAmelCase ( self : List[str] , **__UpperCAmelCase : int ) ->List[Any]: """simple docstring""" a = { '''num_train_timesteps''': 1_100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''noise_sampler_seed''': 0, } config.update(**__UpperCAmelCase ) return config def __lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=__UpperCAmelCase , beta_end=__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" a = self.scheduler_classes[0] a = self.get_scheduler_config() a = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) a = self.dummy_model() a = self.dummy_sample_deter * scheduler.init_noise_sigma a = sample.to(__UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): a = scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) a = model(__UpperCAmelCase , __UpperCAmelCase ) a = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = output.prev_sample a = torch.sum(torch.abs(__UpperCAmelCase ) ) a = torch.mean(torch.abs(__UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1e-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1e-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1e-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1e-3 def __lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" a = self.scheduler_classes[0] a = self.get_scheduler_config(prediction_type='''v_prediction''' ) a = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) a = self.dummy_model() a = self.dummy_sample_deter * scheduler.init_noise_sigma a = sample.to(__UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): a = scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) a = model(__UpperCAmelCase , __UpperCAmelCase ) a = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = output.prev_sample a = torch.sum(torch.abs(__UpperCAmelCase ) ) a = torch.mean(torch.abs(__UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1e-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1e-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1e-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1e-3 def __lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" a = self.scheduler_classes[0] a = self.get_scheduler_config() a = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps , device=__UpperCAmelCase ) a = self.dummy_model() a = self.dummy_sample_deter.to(__UpperCAmelCase ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a = scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) a = model(__UpperCAmelCase , __UpperCAmelCase ) a = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = output.prev_sample a = torch.sum(torch.abs(__UpperCAmelCase ) ) a = torch.mean(torch.abs(__UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1e-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1e-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1e-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1e-3 def __lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" a = self.scheduler_classes[0] a = self.get_scheduler_config() a = scheduler_class(**__UpperCAmelCase , use_karras_sigmas=__UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps , device=__UpperCAmelCase ) a = self.dummy_model() a = self.dummy_sample_deter.to(__UpperCAmelCase ) * scheduler.init_noise_sigma a = sample.to(__UpperCAmelCase ) for t in scheduler.timesteps: a = scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) a = model(__UpperCAmelCase , __UpperCAmelCase ) a = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = output.prev_sample a = torch.sum(torch.abs(__UpperCAmelCase ) ) a = torch.mean(torch.abs(__UpperCAmelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2
370
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = BlipImageProcessor() a = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''' ) a = BertTokenizerFast.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) a = InstructBlipProcessor(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Tuple ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).tokenizer def __lowerCAmelCase ( self : int , **__UpperCAmelCase : str ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).image_processor def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->Optional[Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).qformer_tokenizer def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" a = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) self.assertIsInstance(processor.qformer_tokenizer , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) a = qformer_tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['''qformer_''' + key] ) def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Dict ) ->List[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , )
26
0
import argparse import json from tqdm import tqdm def _a ( ) -> Optional[int]: a = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--src_path''' , type=a , default='''biencoder-nq-dev.json''' , help='''Path to raw DPR training data''' , ) parser.add_argument( '''--evaluation_set''' , type=a , help='''where to store parsed evaluation_set file''' , ) parser.add_argument( '''--gold_data_path''' , type=a , help='''where to store parsed gold_data_path file''' , ) a = parser.parse_args() with open(args.src_path , '''r''' ) as src_file, open(args.evaluation_set , '''w''' ) as eval_file, open( args.gold_data_path , '''w''' ) as gold_file: a = json.load(a ) for dpr_record in tqdm(a ): a = dpr_record['''question'''] a = [context['''title'''] for context in dpr_record['''positive_ctxs''']] eval_file.write(question + '''\n''' ) gold_file.write('''\t'''.join(a ) + '''\n''' ) if __name__ == "__main__": main()
371
import math def _a ( a :int = 100 ) -> int: a = sum(i * i for i in range(1 , n + 1 ) ) a = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
26
0
import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class lowercase_ : '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int]=13 , __UpperCAmelCase : Optional[int]=7 , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Any=True , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : Union[str, Any]=99 , __UpperCAmelCase : int=64 , __UpperCAmelCase : Any=32 , __UpperCAmelCase : Union[str, Any]=5 , __UpperCAmelCase : Optional[Any]=4 , __UpperCAmelCase : Optional[Any]=37 , __UpperCAmelCase : Dict="gelu" , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : List[str]=0.1 , __UpperCAmelCase : Union[str, Any]=512 , __UpperCAmelCase : Union[str, Any]=16 , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : List[Any]=0.02 , __UpperCAmelCase : List[Any]=3 , __UpperCAmelCase : Union[str, Any]=4 , __UpperCAmelCase : int=None , ) ->List[str]: """simple docstring""" a = parent a = batch_size a = seq_length a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = embedding_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_labels a = num_choices a = scope def __lowerCAmelCase ( self : Dict ) ->List[str]: """simple docstring""" a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = None a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a = ids_tensor([self.batch_size] , self.num_choices ) a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" return MegatronBertConfig( 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 , embedding_size=self.embedding_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=__UpperCAmelCase , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : Any , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : List[str] ) ->List[Any]: """simple docstring""" a = MegatronBertModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) a = model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) a = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[str] ) ->str: """simple docstring""" a = MegatronBertForMaskedLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : List[str] ) ->Optional[int]: """simple docstring""" a = MegatronBertForCausalLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] ) ->Dict: """simple docstring""" a = MegatronBertForNextSentencePrediction(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCAmelCase ( self : int , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = MegatronBertForPreTraining(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , next_sentence_label=__UpperCAmelCase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any] ) ->Union[str, Any]: """simple docstring""" a = MegatronBertForQuestionAnswering(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase , ) 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 __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[str] , __UpperCAmelCase : Any , __UpperCAmelCase : Tuple , __UpperCAmelCase : Any , __UpperCAmelCase : int , __UpperCAmelCase : List[str] ) ->Optional[Any]: """simple docstring""" a = self.num_labels a = MegatronBertForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : Any , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple ) ->Dict: """simple docstring""" a = self.num_labels a = MegatronBertForTokenClassification(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str ) ->Optional[int]: """simple docstring""" a = self.num_choices a = MegatronBertForMultipleChoice(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowercase_ ( lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) __snake_case = ( { '''feature-extraction''': MegatronBertModel, '''fill-mask''': MegatronBertForMaskedLM, '''question-answering''': MegatronBertForQuestionAnswering, '''text-classification''': MegatronBertForSequenceClassification, '''text-generation''': MegatronBertForCausalLM, '''token-classification''': MegatronBertForTokenClassification, '''zero-shot''': MegatronBertForSequenceClassification, } if is_torch_available() else {} ) __snake_case = True # test_resize_embeddings = False __snake_case = False def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : List[str]=False ) ->Union[str, Any]: """simple docstring""" a = super()._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) if return_labels: if model_class in get_values(__UpperCAmelCase ): a = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__UpperCAmelCase ) a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__UpperCAmelCase ) return inputs_dict def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = MegatronBertModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37 ) def __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] ) ->Optional[int]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*__UpperCAmelCase ) def _a ( a :Union[str, Any] ) -> int: return torch.tensor( a , dtype=torch.long , device=a , ) UpperCAmelCase__ = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class lowercase_ ( unittest.TestCase ): '''simple docstring''' @slow @unittest.skip('''Model is not available.''' ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" a = '''nvidia/megatron-bert-uncased-345m''' if "MYDIR" in os.environ: a = os.path.join(os.environ['''MYDIR'''] , __UpperCAmelCase ) a = MegatronBertModel.from_pretrained(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.half() a = _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]] ) with torch.no_grad(): a = model(__UpperCAmelCase )[0] a = torch.Size((1, 9, 1_024) ) self.assertEqual(output.shape , __UpperCAmelCase ) a = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): a = output[0, ii, jj] a = expected[3 * ii + jj] a = '''ii={} jj={} a={} b={}'''.format(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) self.assertTrue(math.isclose(__UpperCAmelCase , __UpperCAmelCase , rel_tol=__UpperCAmelCase , abs_tol=__UpperCAmelCase ) , msg=__UpperCAmelCase )
350
def _a ( a :int = 600_851_475_143 ) -> int: try: a = int(a ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''' ) a = 2 a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 a = i while n % i == 0: a = n // i i += 1 return int(a ) if __name__ == "__main__": print(f"""{solution() = }""")
26
0
UpperCAmelCase__ = "\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" UpperCAmelCase__ = [{"type": "code", "content": INSTALL_CONTENT}] UpperCAmelCase__ = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
351
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ = "bart" UpperCAmelCase__ = True @st.cache(allow_output_mutation=a ) def _a ( ) -> Tuple: if LOAD_DENSE_INDEX: a = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) a = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) a = qar_model.eval() else: a , a = (None, None) if MODEL_TYPE == "bart": a = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) a = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) a = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) a = sas_model.eval() else: a , a = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def _a ( ) -> Dict: if LOAD_DENSE_INDEX: a = faiss.StandardGpuResources() a = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] a = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) a = faiss.IndexFlatIP(128 ) a = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: a , a = (None, None) a = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def _a ( ) -> Optional[int]: a = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) a = elia['''train_eli5'''] a = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) a = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = load_indexes() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = load_models() UpperCAmelCase__ , UpperCAmelCase__ = load_train_data() def _a ( a :str , a :Tuple=10 ) -> List[str]: a = embed_questions_for_retrieval([question] , a , a ) a , a = eli5_train_q_index.search(a , a ) a = [elia_train[int(a )] for i in I[0]] return nn_examples def _a ( a :str , a :Any="wiki40b" , a :int="dense" , a :Union[str, Any]=10 ) -> List[str]: if source == "none": a , a = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": a , a = query_qa_dense_index( a , a , a , a , a , a ) else: a , a = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) a = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] a = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def _a ( a :Tuple , a :int , a :int , a :Dict=64 , a :List[Any]=256 , a :List[Any]=False , a :List[Any]=2 , a :Tuple=0.95 , a :Optional[Any]=0.8 ) -> int: with torch.no_grad(): a = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=1_024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar UpperCAmelCase__ = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" UpperCAmelCase__ = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] UpperCAmelCase__ = st.sidebar.checkbox("Demo options") if demo_options: UpperCAmelCase__ = st.sidebar.selectbox( "", action_list, index=3, ) UpperCAmelCase__ = action_list.index(action_st) UpperCAmelCase__ = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) UpperCAmelCase__ = show_type == "Show full text of passages" else: UpperCAmelCase__ = 3 UpperCAmelCase__ = True UpperCAmelCase__ = st.sidebar.checkbox("Retrieval options") if retrieval_options: UpperCAmelCase__ = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) UpperCAmelCase__ = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) UpperCAmelCase__ = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: UpperCAmelCase__ = "wiki40b" UpperCAmelCase__ = "dense" UpperCAmelCase__ = "beam" UpperCAmelCase__ = 2 UpperCAmelCase__ = 64 UpperCAmelCase__ = 256 UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = st.sidebar.checkbox("Generation options") if generate_options: UpperCAmelCase__ = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) UpperCAmelCase__ = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) UpperCAmelCase__ = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ = None # start main text UpperCAmelCase__ = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] UpperCAmelCase__ = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ = st.text_input("Enter your question here:", "") else: UpperCAmelCase__ = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method="dense", n_results=10) UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method="sparse", n_results=10) UpperCAmelCase__ = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ = support_list[:10] UpperCAmelCase__ = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ , UpperCAmelCase__ = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): UpperCAmelCase__ = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) UpperCAmelCase__ = res[1].strip() if sec_titles == "": UpperCAmelCase__ = "[{}]({})".format(res[0], wiki_url) else: UpperCAmelCase__ = sec_titles.split(" & ") UpperCAmelCase__ = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ = find_nearest_training(question) UpperCAmelCase__ = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) UpperCAmelCase__ = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) UpperCAmelCase__ = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
26
0
def _a ( a :float , a :int ) -> float: if digit_amount > 0: return round(number - int(a ) , a ) return number - int(a ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
352
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ = "▁" UpperCAmelCase__ = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = BertGenerationTokenizer __snake_case = False __snake_case = True def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" super().setUp() a = BertGenerationTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = '''<s>''' a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(__UpperCAmelCase ) , 1_002 ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def __lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" a = BertGenerationTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) a = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__UpperCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [285, 46, 10, 170, 382] , ) a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) a = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) a = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" return BertGenerationTokenizer.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) @slow def __lowerCAmelCase ( self : Any ) ->str: """simple docstring""" a = '''Hello World!''' a = [18_536, 2_260, 101] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) a = [ 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, ] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @require_torch @slow def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence a = list(self.big_tokenizer.get_vocab().keys() )[:10] a = ''' '''.join(__UpperCAmelCase ) a = self.big_tokenizer.encode_plus(__UpperCAmelCase , return_tensors='''pt''' , return_token_type_ids=__UpperCAmelCase ) a = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=__UpperCAmelCase ) a = BertGenerationConfig() a = BertGenerationEncoder(__UpperCAmelCase ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__UpperCAmelCase ) model(**__UpperCAmelCase ) @slow def __lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" a = {'''input_ids''': [[39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114], [448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='''google/bert_for_seq_generation_L-24_bbc_encoder''' , revision='''c817d1fd1be2ffa69431227a1fe320544943d4db''' , )
26
0
import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.file_download import REGEX_COMMIT_HASH from huggingface_hub.utils import ( EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError, is_jinja_available, ) from packaging import version from requests import HTTPError from .. import __version__ from .constants import ( DEPRECATED_REVISION_ARGS, DIFFUSERS_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME, ) from .import_utils import ( ENV_VARS_TRUE_VALUES, _flax_version, _jax_version, _onnxruntime_version, _torch_version, is_flax_available, is_onnx_available, is_torch_available, ) from .logging import get_logger UpperCAmelCase__ = get_logger(__name__) UpperCAmelCase__ = Path(__file__).parent / "model_card_template.md" UpperCAmelCase__ = uuida().hex UpperCAmelCase__ = os.getenv("HF_HUB_OFFLINE", "").upper() in ENV_VARS_TRUE_VALUES UpperCAmelCase__ = os.getenv("DISABLE_TELEMETRY", "").upper() in ENV_VARS_TRUE_VALUES UpperCAmelCase__ = HUGGINGFACE_CO_RESOLVE_ENDPOINT + "/api/telemetry/" def _a ( a :Union[Dict, str, None] = None ) -> str: a = F"""diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}""" if DISABLE_TELEMETRY or HF_HUB_OFFLINE: return ua + "; telemetry/off" if is_torch_available(): ua += F"""; torch/{_torch_version}""" if is_flax_available(): ua += F"""; jax/{_jax_version}""" ua += F"""; flax/{_flax_version}""" if is_onnx_available(): ua += F"""; onnxruntime/{_onnxruntime_version}""" # CI will set this value to True if os.environ.get('''DIFFUSERS_IS_CI''' , '''''' ).upper() in ENV_VARS_TRUE_VALUES: ua += "; is_ci/true" if isinstance(a , a ): ua += "; " + "; ".join(F"""{k}/{v}""" for k, v in user_agent.items() ) elif isinstance(a , a ): ua += "; " + user_agent return ua def _a ( a :str , a :Optional[str] = None , a :Optional[str] = None ) -> Optional[Any]: if token is None: a = HfFolder.get_token() if organization is None: a = whoami(a )['''name'''] return F"""{username}/{model_id}""" else: return F"""{organization}/{model_id}""" def _a ( a :Optional[Any] , a :str ) -> str: if not is_jinja_available(): raise ValueError( '''Modelcard rendering is based on Jinja templates.''' ''' Please make sure to have `jinja` installed before using `create_model_card`.''' ''' To install it, please run `pip install Jinja2`.''' ) if hasattr(a , '''local_rank''' ) and args.local_rank not in [-1, 0]: return a = args.hub_token if hasattr(a , '''hub_token''' ) else None a = get_full_repo_name(a , token=a ) a = ModelCard.from_template( card_data=ModelCardData( # Card metadata object that will be converted to YAML block language='''en''' , license='''apache-2.0''' , library_name='''diffusers''' , tags=[] , datasets=args.dataset_name , metrics=[] , ) , template_path=a , model_name=a , repo_name=a , dataset_name=args.dataset_name if hasattr(a , '''dataset_name''' ) else None , learning_rate=args.learning_rate , train_batch_size=args.train_batch_size , eval_batch_size=args.eval_batch_size , gradient_accumulation_steps=( args.gradient_accumulation_steps if hasattr(a , '''gradient_accumulation_steps''' ) else None ) , adam_betaa=args.adam_betaa if hasattr(a , '''adam_beta1''' ) else None , adam_betaa=args.adam_betaa if hasattr(a , '''adam_beta2''' ) else None , adam_weight_decay=args.adam_weight_decay if hasattr(a , '''adam_weight_decay''' ) else None , adam_epsilon=args.adam_epsilon if hasattr(a , '''adam_epsilon''' ) else None , lr_scheduler=args.lr_scheduler if hasattr(a , '''lr_scheduler''' ) else None , lr_warmup_steps=args.lr_warmup_steps if hasattr(a , '''lr_warmup_steps''' ) else None , ema_inv_gamma=args.ema_inv_gamma if hasattr(a , '''ema_inv_gamma''' ) else None , ema_power=args.ema_power if hasattr(a , '''ema_power''' ) else None , ema_max_decay=args.ema_max_decay if hasattr(a , '''ema_max_decay''' ) else None , mixed_precision=args.mixed_precision , ) a = os.path.join(args.output_dir , '''README.md''' ) model_card.save(a ) def _a ( a :Optional[str] , a :Optional[str] = None ) -> int: if resolved_file is None or commit_hash is not None: return commit_hash a = str(Path(a ).as_posix() ) a = re.search(r'''snapshots/([^/]+)/''' , a ) if search is None: return None a = search.groups()[0] return commit_hash if REGEX_COMMIT_HASH.match(a ) else None # Old default cache path, potentially to be migrated. # This logic was more or less taken from `transformers`, with the following differences: # - Diffusers doesn't use custom environment variables to specify the cache path. # - There is no need to migrate the cache format, just move the files to the new location. UpperCAmelCase__ = os.path.expanduser( os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface")) ) UpperCAmelCase__ = os.path.join(hf_cache_home, "diffusers") def _a ( a :Optional[str] = None , a :Optional[str] = None ) -> None: if new_cache_dir is None: a = DIFFUSERS_CACHE if old_cache_dir is None: a = old_diffusers_cache a = Path(a ).expanduser() a = Path(a ).expanduser() for old_blob_path in old_cache_dir.glob('''**/blobs/*''' ): if old_blob_path.is_file() and not old_blob_path.is_symlink(): a = new_cache_dir / old_blob_path.relative_to(a ) new_blob_path.parent.mkdir(parents=a , exist_ok=a ) os.replace(a , a ) try: os.symlink(a , a ) except OSError: logger.warning( '''Could not create symlink between old cache and new cache. If you use an older version of diffusers again, files will be re-downloaded.''' ) # At this point, old_cache_dir contains symlinks to the new cache (it can still be used). UpperCAmelCase__ = os.path.join(DIFFUSERS_CACHE, "version_diffusers_cache.txt") if not os.path.isfile(cache_version_file): UpperCAmelCase__ = 0 else: with open(cache_version_file) as f: try: UpperCAmelCase__ = int(f.read()) except ValueError: UpperCAmelCase__ = 0 if cache_version < 1: UpperCAmelCase__ = os.path.isdir(old_diffusers_cache) and len(os.listdir(old_diffusers_cache)) > 0 if old_cache_is_not_empty: logger.warning( "The cache for model files in Diffusers v0.14.0 has moved to a new location. Moving your " "existing cached models. This is a one-time operation, you can interrupt it or run it " "later by calling `diffusers.utils.hub_utils.move_cache()`." ) try: move_cache() except Exception as e: UpperCAmelCase__ = "\n".join(traceback.format_tb(e.__traceback__)) logger.error( f"""There was a problem when trying to move your cache:\n\n{trace}\n{e.__class__.__name__}: {e}\n\nPlease """ "file an issue at https://github.com/huggingface/diffusers/issues/new/choose, copy paste this whole " "message and we will do our best to help." ) if cache_version < 1: try: os.makedirs(DIFFUSERS_CACHE, exist_ok=True) with open(cache_version_file, "w") as f: f.write("1") except Exception: logger.warning( f"""There was a problem when trying to write in your cache folder ({DIFFUSERS_CACHE}). Please, ensure """ "the directory exists and can be written to." ) def _a ( a :str , a :Optional[str] = None ) -> str: if variant is not None: a = weights_name.split('''.''' ) a = splits[:-1] + [variant] + splits[-1:] a = '''.'''.join(a ) return weights_name def _a ( a :Dict , *, a :Tuple , a :Any , a :Any , a :Dict , a :str , a :List[str] , a :List[str] , a :Optional[int] , a :Any , a :List[Any] , a :Optional[Any]=None , ) -> Any: a = str(a ) if os.path.isfile(a ): return pretrained_model_name_or_path elif os.path.isdir(a ): if os.path.isfile(os.path.join(a , a ) ): # Load from a PyTorch checkpoint a = os.path.join(a , a ) return model_file elif subfolder is not None and os.path.isfile( os.path.join(a , a , a ) ): a = os.path.join(a , a , a ) return model_file else: raise EnvironmentError( F"""Error no file named {weights_name} found in directory {pretrained_model_name_or_path}.""" ) else: # 1. First check if deprecated way of loading from branches is used if ( revision in DEPRECATED_REVISION_ARGS and (weights_name == WEIGHTS_NAME or weights_name == SAFETENSORS_WEIGHTS_NAME) and version.parse(version.parse(a ).base_version ) >= version.parse('''0.20.0''' ) ): try: a = hf_hub_download( a , filename=_add_variant(a , a ) , cache_dir=a , force_download=a , proxies=a , resume_download=a , local_files_only=a , use_auth_token=a , user_agent=a , subfolder=a , revision=revision or commit_hash , ) warnings.warn( F"""Loading the variant {revision} from {pretrained_model_name_or_path} via `revision='{revision}'` is deprecated. Loading instead from `revision='main'` with `variant={revision}`. Loading model variants via `revision='{revision}'` will be removed in diffusers v1. Please use `variant='{revision}'` instead.""" , a , ) return model_file except: # noqa: E722 warnings.warn( F"""You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision='{revision}'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant='{revision}'` instead. However, it appears that {pretrained_model_name_or_path} currently does not have a {_add_variant(a , a )} file in the 'main' branch of {pretrained_model_name_or_path}. \n The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title '{pretrained_model_name_or_path} is missing {_add_variant(a , a )}' so that the correct variant file can be added.""" , a , ) try: # 2. Load model file as usual a = hf_hub_download( a , filename=a , cache_dir=a , force_download=a , proxies=a , resume_download=a , local_files_only=a , use_auth_token=a , user_agent=a , subfolder=a , revision=revision or commit_hash , ) return model_file except RepositoryNotFoundError: raise EnvironmentError( F"""{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier """ '''listed on \'https://huggingface.co/models\'\nIf this is a private repository, make sure to pass a ''' '''token having permission to this repo with `use_auth_token` or log in with `huggingface-cli ''' '''login`.''' ) except RevisionNotFoundError: raise EnvironmentError( F"""{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for """ '''this model name. Check the model page at ''' F"""'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions.""" ) except EntryNotFoundError: raise EnvironmentError( F"""{pretrained_model_name_or_path} does not appear to have a file named {weights_name}.""" ) except HTTPError as err: raise EnvironmentError( F"""There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}""" ) except ValueError: raise EnvironmentError( F"""We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it""" F""" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a""" F""" directory containing a file named {weights_name} or""" ''' \nCheckout your internet connection or see how to run the library in''' ''' offline mode at \'https://huggingface.co/docs/diffusers/installation#offline-mode\'.''' ) except EnvironmentError: raise EnvironmentError( F"""Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from """ '''\'https://huggingface.co/models\', make sure you don\'t have a local directory with the same name. ''' F"""Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory """ F"""containing a file named {weights_name}""" )
353
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger("transformers.models.speecht5") def _a ( a :Optional[Any] , a :Tuple , a :Dict ) -> List[str]: hf_model.apply_weight_norm() a = checkpoint['''input_conv.weight_g'''] a = checkpoint['''input_conv.weight_v'''] a = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): a = checkpoint[F"""upsamples.{i}.1.weight_g"""] a = checkpoint[F"""upsamples.{i}.1.weight_v"""] a = checkpoint[F"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): a = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_g"""] a = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_v"""] a = checkpoint[F"""blocks.{i}.convs1.{j}.1.bias"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_g"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_v"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.bias"""] a = checkpoint['''output_conv.1.weight_g'''] a = checkpoint['''output_conv.1.weight_v'''] a = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def _a ( a :List[str] , a :Union[str, Any] , a :Dict , a :Dict=None , a :List[Any]=None , ) -> int: if config_path is not None: a = SpeechTaHifiGanConfig.from_pretrained(a ) else: a = SpeechTaHifiGanConfig() a = SpeechTaHifiGan(a ) a = torch.load(a ) load_weights(orig_checkpoint['''model''']['''generator'''] , a , a ) a = np.load(a ) a = stats[0].reshape(-1 ) a = stats[1].reshape(-1 ) a = torch.from_numpy(a ).float() a = torch.from_numpy(a ).float() model.save_pretrained(a ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--stats_path", required=True, default=None, type=str, help="Path to stats.npy file") 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." ) UpperCAmelCase__ = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
26
0
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex UpperCAmelCase__ = logging.getLogger(__name__) class lowercase_ : '''simple docstring''' def __init__( self : str ) ->Any: """simple docstring""" a = False def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[str] ) ->List[str]: """simple docstring""" if not self.initialized: a = RagRetriever( __UpperCAmelCase , question_encoder_tokenizer=__UpperCAmelCase , generator_tokenizer=__UpperCAmelCase , index=__UpperCAmelCase , init_retrieval=__UpperCAmelCase , ) a = True def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" self.retriever.index.init_index() def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : str , __UpperCAmelCase : Tuple ) ->List[str]: """simple docstring""" a , a = self.retriever._main_retrieve(__UpperCAmelCase , __UpperCAmelCase ) return doc_ids, retrieved_doc_embeds class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict=None ) ->Optional[Any]: """simple docstring""" if index is not None and index.is_initialized() and len(__UpperCAmelCase ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( __UpperCAmelCase , question_encoder_tokenizer=__UpperCAmelCase , generator_tokenizer=__UpperCAmelCase , index=__UpperCAmelCase , init_retrieval=__UpperCAmelCase , ) a = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : Tuple ) ->Dict: """simple docstring""" if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a , a = ray.get(random_worker.retrieve.remote(__UpperCAmelCase , __UpperCAmelCase ) ) else: a , a = self._main_retrieve(__UpperCAmelCase , __UpperCAmelCase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__UpperCAmelCase ) @classmethod def __lowerCAmelCase ( cls : List[str] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Optional[int] ) ->List[Any]: """simple docstring""" return super(__UpperCAmelCase , cls ).get_tokenizers(__UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ) @classmethod def __lowerCAmelCase ( cls : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : int ) ->str: """simple docstring""" a = kwargs.pop('''config''' , __UpperCAmelCase ) or RagConfig.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) a = RagTokenizer.from_pretrained(__UpperCAmelCase , config=__UpperCAmelCase ) a = rag_tokenizer.question_encoder a = rag_tokenizer.generator if indexed_dataset is not None: a = '''custom''' a = CustomHFIndex(config.retrieval_vector_size , __UpperCAmelCase ) else: a = cls._build_index(__UpperCAmelCase ) return cls( __UpperCAmelCase , question_encoder_tokenizer=__UpperCAmelCase , generator_tokenizer=__UpperCAmelCase , retrieval_workers=__UpperCAmelCase , index=__UpperCAmelCase , )
354
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase__ = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTBigCodeForSequenceClassification", "GPTBigCodeForTokenClassification", "GPTBigCodeForCausalLM", "GPTBigCodeModel", "GPTBigCodePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
0
def _a ( a :int , a :list ) -> List[str]: _enforce_args(a , a ) if n == 0: return 0 a = float('''-inf''' ) for i in range(1 , n + 1 ): a = max( a , prices[i - 1] + naive_cut_rod_recursive(n - i , a ) ) return max_revue def _a ( a :int , a :list ) -> int: _enforce_args(a , a ) a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a , a , a ) def _a ( a :int , a :list , a :list ) -> int: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: a = float('''-inf''' ) for i in range(1 , n + 1 ): a = max( a , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a , a ) , ) a = max_revenue return max_rev[n] def _a ( a :int , a :list ) -> str: _enforce_args(a , a ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. a = [float('''-inf''' ) for _ in range(n + 1 )] a = 0 for i in range(1 , n + 1 ): a = max_rev[i] for j in range(1 , i + 1 ): a = max(a , prices[j - 1] + max_rev[i - j] ) a = max_revenue_i return max_rev[n] def _a ( a :int , a :list ) -> List[Any]: if n < 0: a = F"""n must be greater than or equal to 0. Got n = {n}""" raise ValueError(a ) if n > len(a ): a = ( '''Each integral piece of rod must have a corresponding price. ''' F"""Got n = {n} but length of prices = {len(a )}""" ) raise ValueError(a ) def _a ( ) -> int: a = [6, 10, 12, 15, 20, 23] a = len(a ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. a = 36 a = top_down_cut_rod(a , a ) a = bottom_up_cut_rod(a , a ) a = naive_cut_rod_recursive(a , a ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
355
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def _a ( a :Tuple ) -> int: a = tmp_path / '''file.csv''' a = textwrap.dedent( '''\ header1,header2 1,2 10,20 ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :int ) -> List[str]: a = tmp_path / '''malformed_file.csv''' a = textwrap.dedent( '''\ header1,header2 1,2 10,20, ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :Dict , a :int ) -> List[str]: a = tmp_path / '''csv_with_image.csv''' a = textwrap.dedent( F"""\ image {image_file} """ ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :List[Any] ) -> Dict: a = tmp_path / '''csv_with_label.csv''' a = textwrap.dedent( '''\ label good bad good ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :Tuple ) -> Any: a = tmp_path / '''csv_with_int_list.csv''' a = textwrap.dedent( '''\ int_list 1 2 3 4 5 6 7 8 9 ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) def _a ( a :Dict , a :int , a :Union[str, Any] ) -> List[Any]: a = Csv() a = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(a , match='''Error tokenizing data''' ): for _ in generator: pass assert any( record.levelname == '''ERROR''' and '''Failed to read file''' in record.message and os.path.basename(a ) in record.message for record in caplog.records ) @require_pil def _a ( a :Dict ) -> Any: with open(a , encoding='''utf-8''' ) as f: a = f.read().splitlines()[1] a = Csv(encoding='''utf-8''' , features=Features({'''image''': Image()} ) ) a = csv._generate_tables([[csv_file_with_image]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''image''' ).type == Image()() a = pa_table.to_pydict()['''image'''] assert generated_content == [{"path": image_file, "bytes": None}] def _a ( a :Any ) -> Tuple: with open(a , encoding='''utf-8''' ) as f: a = f.read().splitlines()[1:] a = Csv(encoding='''utf-8''' , features=Features({'''label''': ClassLabel(names=['''good''', '''bad'''] )} ) ) a = csv._generate_tables([[csv_file_with_label]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''label''' ).type == ClassLabel(names=['''good''', '''bad'''] )() a = pa_table.to_pydict()['''label'''] assert generated_content == [ClassLabel(names=['''good''', '''bad'''] ).straint(a ) for label in labels] def _a ( a :Union[str, Any] ) -> Optional[Any]: a = Csv(encoding='''utf-8''' , sep=''',''' , converters={'''int_list''': lambda a : [int(a ) for i in x.split()]} ) a = csv._generate_tables([[csv_file_with_int_list]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('''int_list''' ).type ) a = pa_table.to_pydict()['''int_list'''] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
26
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''image_processor''', '''tokenizer'''] __snake_case = '''CLIPImageProcessor''' __snake_case = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Dict , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : Optional[Any] ) ->List[str]: """simple docstring""" a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __UpperCAmelCase , ) a = kwargs.pop('''feature_extractor''' ) a = 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__(__UpperCAmelCase , __UpperCAmelCase ) def __call__( self : List[str] , __UpperCAmelCase : Any=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Any=None , **__UpperCAmelCase : str ) ->Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: a = self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if images is not None: a = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is not None and images is not None: a = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__UpperCAmelCase ) , tensor_type=__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : str , **__UpperCAmelCase : Tuple ) ->Any: """simple docstring""" return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a = self.tokenizer.model_input_names a = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __UpperCAmelCase , ) return self.image_processor_class @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __UpperCAmelCase , ) return self.image_processor
356
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = torch.device("cpu") def _a ( ) -> Union[str, Any]: a = '''http://images.cocodataset.org/val2017/000000039769.jpg''' a = Image.open(requests.get(a , stream=a ).raw ) return im def _a ( a :Dict ) -> Tuple: if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1703e00, 2.1107e00, -2.0811e00, 8.8685e-01, 2.4360e-01] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9636e-01, 2.3478e-01, -1.6963e00, -1.7381e00, -8.6337e-01] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2768e-01, -4.7429e-01, -1.0897e00, -1.0248e00, 3.5523e-02] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5330e-01, 2.4211e-01, -6.0185e-01, -8.2789e-01, -6.0446e-02] ) def _a ( a :int , a :Any , a :Union[str, Any] ) -> int: a = dct.pop(a ) a = val def _a ( a :Any ) -> Dict: a = [] for k in state_dict.keys(): a = k if ".pwconv" in k: a = k_new.replace('''.pwconv''' , '''.point_wise_conv''' ) if ".dwconv" in k: a = k_new.replace('''.dwconv''' , '''.depth_wise_conv''' ) if ".Proj." in k: a = k_new.replace('''.Proj.''' , '''.proj.''' ) if "patch_embed" in k_new: a = k_new.replace('''patch_embed''' , '''swiftformer.patch_embed.patch_embedding''' ) if "network" in k_new: a = k_new.split('''.''' ) if ls[2].isdigit(): a = '''swiftformer.encoder.network.''' + ls[1] + '''.blocks.''' + ls[2] + '''.''' + '''.'''.join(ls[3:] ) else: a = k_new.replace('''network''' , '''swiftformer.encoder.network''' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def _a ( a :List[Any] , a :Tuple , a :List[str] ) -> Union[str, Any]: a = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size a = 1_000 a = '''huggingface/label-files''' a = '''imagenet-1k-id2label.json''' a = json.load(open(hf_hub_download(a , a , repo_type='''dataset''' ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": a = [3, 3, 6, 4] a = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": a = [3, 3, 9, 6] a = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": a = [4, 3, 10, 5] a = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": a = [4, 4, 12, 6] a = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('''https''' ): a = torch.hub.load_state_dict_from_url(a , map_location='''cpu''' , check_hash=a ) else: a = torch.load(a , map_location='''cpu''' ) a = checkpoint a = create_rename_keys(a ) for rename_key_src, rename_key_dest in rename_keys: rename_key(a , a , a ) # load HuggingFace model a = SwiftFormerForImageClassification(a ).eval() hf_model.load_state_dict(a ) # prepare test inputs a = prepare_img() a = ViTImageProcessor.from_pretrained('''preprocessor_config''' ) a = processor(images=a , return_tensors='''pt''' ) # compare outputs from both models a = get_expected_output(a ) a = hf_model(inputs['''pixel_values'''] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , a , atol=1e-3 ) Path(a ).mkdir(exist_ok=a ) print(F"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swiftformer_name", default="swiftformer_xs", choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"], type=str, help="Name of the SwiftFormer model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default="./converted_outputs/", type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.") UpperCAmelCase__ = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
26
0
def _a ( a :list ) -> list: a = len(a ) for i in range(1 , a ): a = collection[i] a = 0 a = i - 1 while low <= high: a = (low + high) // 2 if val < collection[mid]: a = mid - 1 else: a = mid + 1 for j in range(a , a , -1 ): a = collection[j - 1] a = val return collection if __name__ == "__main__": UpperCAmelCase__ = input("Enter numbers separated by a comma:\n").strip() UpperCAmelCase__ = [int(item) for item in user_input.split(",")] print(binary_insertion_sort(unsorted))
357
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : DDPMScheduler , __UpperCAmelCase : Optional[int] , ) ->List[str]: """simple docstring""" super().__init__() a = value_function a = unet a = scheduler a = env a = env.get_dataset() a = {} for key in self.data.keys(): try: a = self.data[key].mean() except: # noqa: E722 pass a = {} for key in self.data.keys(): try: a = self.data[key].std() except: # noqa: E722 pass a = env.observation_space.shape[0] a = env.action_space.shape[0] def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] ) ->Dict: """simple docstring""" return (x_in - self.means[key]) / self.stds[key] def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict ) ->List[str]: """simple docstring""" return x_in * self.stds[key] + self.means[key] def __lowerCAmelCase ( self : int , __UpperCAmelCase : int ) ->List[str]: """simple docstring""" if type(__UpperCAmelCase ) is dict: return {k: self.to_torch(__UpperCAmelCase ) for k, v in x_in.items()} elif torch.is_tensor(__UpperCAmelCase ): return x_in.to(self.unet.device ) return torch.tensor(__UpperCAmelCase , device=self.unet.device ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple ) ->int: """simple docstring""" for key, val in cond.items(): a = val.clone() return x_in def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = x.shape[0] a = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model a = torch.full((batch_size,) , __UpperCAmelCase , device=self.unet.device , dtype=torch.long ) for _ in range(__UpperCAmelCase ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models a = self.value_function(x.permute(0 , 2 , 1 ) , __UpperCAmelCase ).sample a = torch.autograd.grad([y.sum()] , [x] )[0] a = self.scheduler._get_variance(__UpperCAmelCase ) a = torch.exp(0.5 * posterior_variance ) a = model_std * grad a = 0 a = x.detach() a = x + scale * grad a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.unet(x.permute(0 , 2 , 1 ) , __UpperCAmelCase ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg a = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , predict_epsilon=__UpperCAmelCase )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.to_torch(__UpperCAmelCase ) return x, y def __call__( self : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int]=64 , __UpperCAmelCase : int=32 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : str=0.1 ) ->List[str]: """simple docstring""" a = self.normalize(__UpperCAmelCase , '''observations''' ) a = obs[None].repeat(__UpperCAmelCase , axis=0 ) a = {0: self.to_torch(__UpperCAmelCase )} a = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) a = randn_tensor(__UpperCAmelCase , device=self.unet.device ) a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.to_torch(__UpperCAmelCase ) # run the diffusion process a , a = self.run_diffusion(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # sort output trajectories by value a = y.argsort(0 , descending=__UpperCAmelCase ).squeeze() a = x[sorted_idx] a = sorted_values[:, :, : self.action_dim] a = actions.detach().cpu().numpy() a = self.de_normalize(__UpperCAmelCase , key='''actions''' ) # select the action with the highest value if y is not None: a = 0 else: # if we didn't run value guiding, select a random action a = np.random.randint(0 , __UpperCAmelCase ) a = denorm_actions[selected_index, 0] return denorm_actions
26
0
class lowercase_: '''simple docstring''' def __init__( self : Tuple ) ->Optional[Any]: """simple docstring""" a = {} def __lowerCAmelCase ( self : str ) ->None: """simple docstring""" print(self.vertex ) for i in self.vertex: print(__UpperCAmelCase , ''' -> ''' , ''' -> '''.join([str(__UpperCAmelCase ) for j in self.vertex[i]] ) ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : int ) ->None: """simple docstring""" if from_vertex in self.vertex: self.vertex[from_vertex].append(__UpperCAmelCase ) else: # else make a new vertex a = [to_vertex] def __lowerCAmelCase ( self : Dict ) ->None: """simple docstring""" a = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : int , __UpperCAmelCase : int , __UpperCAmelCase : list ) ->None: """simple docstring""" a = True print(__UpperCAmelCase , end=''' ''' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(__UpperCAmelCase , __UpperCAmelCase ) if __name__ == "__main__": UpperCAmelCase__ = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("DFS:") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
358
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 UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "spiece.model"} UpperCAmelCase__ = { "vocab_file": { "TsinghuaAI/CPM-Generate": "https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model", } } class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Any=True , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : List[str]="<s>" , __UpperCAmelCase : int="</s>" , __UpperCAmelCase : Any="<unk>" , __UpperCAmelCase : Optional[Any]="<sep>" , __UpperCAmelCase : int="<pad>" , __UpperCAmelCase : Any="<cls>" , __UpperCAmelCase : List[str]="<mask>" , __UpperCAmelCase : Optional[int]=["<eop>", "<eod>"] , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : Union[str, Any] , ) ->None: """simple docstring""" a = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) a = 3 a = do_lower_case a = remove_space a = keep_accents a = vocab_file a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) a = jieba a = str.maketrans(''' \n''' , '''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" return len(self.sp_model ) def __lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" a = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = self.__dict__.copy() a = None return state def __setstate__( self : List[str] , __UpperCAmelCase : Optional[int] ) ->str: """simple docstring""" a = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a = {} a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] ) ->List[str]: """simple docstring""" if self.remove_space: a = ''' '''.join(inputs.strip().split() ) else: a = inputs a = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: a = unicodedata.normalize('''NFKD''' , __UpperCAmelCase ) a = ''''''.join([c for c in outputs if not unicodedata.combining(__UpperCAmelCase )] ) if self.do_lower_case: a = outputs.lower() return outputs def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = self.preprocess_text(__UpperCAmelCase ) a = self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) a = [] for piece in pieces: if len(__UpperCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): a = self.sp_model.EncodeAsPieces(piece[:-1].replace(__UpperCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: a = cur_pieces[1:] else: a = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__UpperCAmelCase ) else: new_pieces.append(__UpperCAmelCase ) return new_pieces def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Any ) ->Any: """simple docstring""" return self.sp_model.PieceToId(__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Dict ) ->Union[str, Any]: """simple docstring""" return self.sp_model.IdToPiece(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = ''''''.join(__UpperCAmelCase ).replace(__UpperCAmelCase , ''' ''' ).strip() return out_string def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase , token_ids_a=__UpperCAmelCase , already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is not None: return ([0] * len(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] return ([0] * len(__UpperCAmelCase )) + [1, 1] def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a = os.path.join( __UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase , '''wb''' ) as fi: a = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,) def __lowerCAmelCase ( self : Any , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = super()._decode(*__UpperCAmelCase , **__UpperCAmelCase ) a = text.replace(''' ''' , '''''' ).replace('''\u2582''' , ''' ''' ).replace('''\u2583''' , '''\n''' ) return text
26
0
"""simple docstring""" import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "vocab.txt"} UpperCAmelCase__ = { "vocab_file": { "openbmb/cpm-ant-10b": "https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt", }, } UpperCAmelCase__ = { "openbmb/cpm-ant-10b": 1024, } def _a ( a :Dict ) -> List[Any]: a = collections.OrderedDict() with open(a , '''r''' , encoding='''utf-8''' ) as reader: a = reader.readlines() for index, token in enumerate(a ): a = token.rstrip('''\n''' ) a = index return vocab class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict="<unk>" , __UpperCAmelCase : str=200 ) ->Any: """simple docstring""" a = vocab a = unk_token a = max_input_chars_per_word def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Optional[Any] ) ->str: """simple docstring""" a = list(__UpperCAmelCase ) if len(__UpperCAmelCase ) > self.max_input_chars_per_word: return [self.unk_token] a = 0 a = [] while start < len(__UpperCAmelCase ): a = len(__UpperCAmelCase ) a = None while start < end: a = ''''''.join(chars[start:end] ) if substr in self.vocab: a = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(__UpperCAmelCase ) a = end return sub_tokens class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ['''input_ids''', '''attention_mask'''] __snake_case = False def __init__( self : Tuple , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[int]="<d>" , __UpperCAmelCase : int="</d>" , __UpperCAmelCase : Tuple="<s>" , __UpperCAmelCase : str="</s>" , __UpperCAmelCase : Dict="<pad>" , __UpperCAmelCase : int="<unk>" , __UpperCAmelCase : List[str]="</n>" , __UpperCAmelCase : Optional[int]="</_>" , __UpperCAmelCase : List[str]="left" , **__UpperCAmelCase : Optional[Any] , ) ->List[Any]: """simple docstring""" requires_backends(self , ['''jieba'''] ) super().__init__( bod_token=__UpperCAmelCase , eod_token=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , line_token=__UpperCAmelCase , space_token=__UpperCAmelCase , padding_side=__UpperCAmelCase , **__UpperCAmelCase , ) a = bod_token a = eod_token a = load_vocab(__UpperCAmelCase ) a = self.encoder[space_token] a = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] a = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __UpperCAmelCase : x[1] ) ) a = {v: k for k, v in self.encoder.items()} a = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" return self.encoder[self.bod_token] @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Any: """simple docstring""" return self.encoder[self.eod_token] @property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return self.encoder["\n"] @property def __lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" return len(self.encoder ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[int] ) ->str: """simple docstring""" a = [] for x in jieba.cut(__UpperCAmelCase , cut_all=__UpperCAmelCase ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(__UpperCAmelCase ) ) return output_tokens def __lowerCAmelCase ( self : Any , __UpperCAmelCase : List[Any] , **__UpperCAmelCase : Optional[Any] ) ->Optional[Any]: """simple docstring""" a = [i for i in token_ids if i >= 0] a = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[str] ) ->Optional[Any]: """simple docstring""" return token in self.encoder def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[str] ) ->str: """simple docstring""" return "".join(__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : int ) ->Optional[Any]: """simple docstring""" return self.encoder.get(__UpperCAmelCase , self.encoder.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Optional[int] ) ->List[str]: """simple docstring""" return self.decoder.get(__UpperCAmelCase , self.unk_token ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if os.path.isdir(__UpperCAmelCase ): a = os.path.join( __UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: a = (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory a = 0 if " " in self.encoder: a = self.encoder[''' '''] del self.encoder[" "] if "\n" in self.encoder: a = self.encoder['''\n'''] del self.encoder["\n"] a = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __UpperCAmelCase : x[1] ) ) with open(__UpperCAmelCase , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ''' Please check that the vocabulary is not corrupted!''' ) a = token_index writer.write(token + '''\n''' ) index += 1 return (vocab_file,) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : List[int] = None ) ->List[int]: """simple docstring""" if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase , token_ids_a=__UpperCAmelCase , already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is not None: return [1] + ([0] * len(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) return [1] + ([0] * len(__UpperCAmelCase ))
359
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def _a ( a :Union[str, Any] , a :List[Any] ) -> List[Any]: a = checkpoint a = {} a = vae_state_dict['''encoder.conv_in.weight'''] a = vae_state_dict['''encoder.conv_in.bias'''] a = vae_state_dict['''encoder.conv_out.weight'''] a = vae_state_dict['''encoder.conv_out.bias'''] a = vae_state_dict['''encoder.norm_out.weight'''] a = vae_state_dict['''encoder.norm_out.bias'''] a = vae_state_dict['''decoder.conv_in.weight'''] a = vae_state_dict['''decoder.conv_in.bias'''] a = vae_state_dict['''decoder.conv_out.weight'''] a = vae_state_dict['''decoder.conv_out.bias'''] a = vae_state_dict['''decoder.norm_out.weight'''] a = vae_state_dict['''decoder.norm_out.bias'''] a = vae_state_dict['''quant_conv.weight'''] a = vae_state_dict['''quant_conv.bias'''] a = vae_state_dict['''post_quant_conv.weight'''] a = vae_state_dict['''post_quant_conv.bias'''] # Retrieves the keys for the encoder down blocks only a = len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''encoder.down''' in layer} ) a = { layer_id: [key for key in vae_state_dict if F"""down.{layer_id}""" in key] for layer_id in range(a ) } # Retrieves the keys for the decoder up blocks only a = len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''decoder.up''' in layer} ) a = { layer_id: [key for key in vae_state_dict if F"""up.{layer_id}""" in key] for layer_id in range(a ) } for i in range(a ): a = [key for key in down_blocks[i] if F"""down.{i}""" in key and F"""down.{i}.downsample""" not in key] if F"""encoder.down.{i}.downsample.conv.weight""" in vae_state_dict: a = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.weight""" ) a = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.bias""" ) a = renew_vae_resnet_paths(a ) a = {'''old''': F"""down.{i}.block""", '''new''': F"""down_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''encoder.mid.block''' in key] a = 2 for i in range(1 , num_mid_res_blocks + 1 ): a = [key for key in mid_resnets if F"""encoder.mid.block_{i}""" in key] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""mid.block_{i}""", '''new''': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''encoder.mid.attn''' in key] a = renew_vae_attention_paths(a ) a = {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) for i in range(a ): a = num_up_blocks - 1 - i a = [ key for key in up_blocks[block_id] if F"""up.{block_id}""" in key and F"""up.{block_id}.upsample""" not in key ] if F"""decoder.up.{block_id}.upsample.conv.weight""" in vae_state_dict: a = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.weight""" ] a = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.bias""" ] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""up.{block_id}.block""", '''new''': F"""up_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''decoder.mid.block''' in key] a = 2 for i in range(1 , num_mid_res_blocks + 1 ): a = [key for key in mid_resnets if F"""decoder.mid.block_{i}""" in key] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""mid.block_{i}""", '''new''': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''decoder.mid.attn''' in key] a = renew_vae_attention_paths(a ) a = {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) return new_checkpoint def _a ( a :str , a :str , ) -> List[str]: # Only support V1 a = requests.get( ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml''' ) a = io.BytesIO(r.content ) a = OmegaConf.load(a ) a = 512 a = '''cuda''' if torch.cuda.is_available() else '''cpu''' if checkpoint_path.endswith('''safetensors''' ): from safetensors import safe_open a = {} with safe_open(a , framework='''pt''' , device='''cpu''' ) as f: for key in f.keys(): a = f.get_tensor(a ) else: a = torch.load(a , map_location=a )['''state_dict'''] # Convert the VAE model. a = create_vae_diffusers_config(a , image_size=a ) a = custom_convert_ldm_vae_checkpoint(a , a ) a = AutoencoderKL(**a ) vae.load_state_dict(a ) vae.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--vae_pt_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") UpperCAmelCase__ = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
26
0
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." )
360
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''image_processor''', '''tokenizer'''] __snake_case = '''CLIPImageProcessor''' __snake_case = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Dict , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : Optional[Any] ) ->List[str]: """simple docstring""" a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __UpperCAmelCase , ) a = kwargs.pop('''feature_extractor''' ) a = 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__(__UpperCAmelCase , __UpperCAmelCase ) def __call__( self : List[str] , __UpperCAmelCase : Any=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Any=None , **__UpperCAmelCase : str ) ->Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: a = self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if images is not None: a = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is not None and images is not None: a = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__UpperCAmelCase ) , tensor_type=__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : str , **__UpperCAmelCase : Tuple ) ->Any: """simple docstring""" return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a = self.tokenizer.model_input_names a = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __UpperCAmelCase , ) return self.image_processor_class @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __UpperCAmelCase , ) return self.image_processor
26
0
import tensorflow as tf from ...tf_utils import shape_list class lowercase_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any]=1 , __UpperCAmelCase : Any=False , **__UpperCAmelCase : str ) ->Optional[int]: """simple docstring""" super().__init__(**__UpperCAmelCase ) a = vocab_size a = d_embed a = d_proj a = cutoffs + [vocab_size] a = [0] + self.cutoffs a = div_val a = self.cutoffs[0] a = len(self.cutoffs ) - 1 a = self.shortlist_size + self.n_clusters a = keep_order a = [] a = [] def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" if self.n_clusters > 0: a = self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='''zeros''' , trainable=__UpperCAmelCase , name='''cluster_weight''' ) a = self.add_weight( shape=(self.n_clusters,) , initializer='''zeros''' , trainable=__UpperCAmelCase , name='''cluster_bias''' ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: a = self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='''zeros''' , trainable=__UpperCAmelCase , name=F"""out_projs_._{i}""" , ) self.out_projs.append(__UpperCAmelCase ) else: self.out_projs.append(__UpperCAmelCase ) a = self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='''zeros''' , trainable=__UpperCAmelCase , name=F"""out_layers_._{i}_._weight""" , ) a = self.add_weight( shape=(self.vocab_size,) , initializer='''zeros''' , trainable=__UpperCAmelCase , name=F"""out_layers_._{i}_._bias""" , ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): a , a = self.cutoff_ends[i], self.cutoff_ends[i + 1] a = self.d_embed // (self.div_val**i) a = self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='''zeros''' , trainable=__UpperCAmelCase , name=F"""out_projs_._{i}""" ) self.out_projs.append(__UpperCAmelCase ) a = self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='''zeros''' , trainable=__UpperCAmelCase , name=F"""out_layers_._{i}_._weight""" , ) a = self.add_weight( shape=(r_idx - l_idx,) , initializer='''zeros''' , trainable=__UpperCAmelCase , name=F"""out_layers_._{i}_._bias""" , ) self.out_layers.append((weight, bias) ) super().build(__UpperCAmelCase ) @staticmethod def __lowerCAmelCase ( __UpperCAmelCase : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple=None ) ->Dict: """simple docstring""" a = x if proj is not None: a = tf.einsum('''ibd,ed->ibe''' , __UpperCAmelCase , __UpperCAmelCase ) return tf.einsum('''ibd,nd->ibn''' , __UpperCAmelCase , __UpperCAmelCase ) + b @staticmethod def __lowerCAmelCase ( __UpperCAmelCase : List[Any] , __UpperCAmelCase : int ) ->List[str]: """simple docstring""" a = shape_list(__UpperCAmelCase ) a = tf.range(lp_size[0] , dtype=target.dtype ) a = tf.stack([r, target] , 1 ) return tf.gather_nd(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Any , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : Union[str, Any]=False ) ->str: """simple docstring""" a = 0 if self.n_clusters == 0: a = self._logit(__UpperCAmelCase , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] ) if target is not None: a = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__UpperCAmelCase , logits=__UpperCAmelCase ) a = tf.nn.log_softmax(__UpperCAmelCase , axis=-1 ) else: a = shape_list(__UpperCAmelCase ) a = [] a = tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): a , a = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: a = (target >= l_idx) & (target < r_idx) a = tf.where(__UpperCAmelCase ) a = tf.boolean_mask(__UpperCAmelCase , __UpperCAmelCase ) - l_idx if self.div_val == 1: a = self.out_layers[0][0][l_idx:r_idx] a = self.out_layers[0][1][l_idx:r_idx] else: a = self.out_layers[i][0] a = self.out_layers[i][1] if i == 0: a = tf.concat([cur_W, self.cluster_weight] , 0 ) a = tf.concat([cur_b, self.cluster_bias] , 0 ) a = self._logit(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , self.out_projs[0] ) a = tf.nn.log_softmax(__UpperCAmelCase ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: a = tf.boolean_mask(__UpperCAmelCase , __UpperCAmelCase ) a = self._gather_logprob(__UpperCAmelCase , __UpperCAmelCase ) else: a = self._logit(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , self.out_projs[i] ) a = tf.nn.log_softmax(__UpperCAmelCase ) a = self.cutoffs[0] + i - 1 # No probability for the head cluster a = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(__UpperCAmelCase ) if target is not None: a = tf.boolean_mask(__UpperCAmelCase , __UpperCAmelCase ) a = tf.boolean_mask(__UpperCAmelCase , __UpperCAmelCase ) a = self._gather_logprob(__UpperCAmelCase , __UpperCAmelCase ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(__UpperCAmelCase , -cur_logprob , shape_list(__UpperCAmelCase ) ) a = tf.concat(__UpperCAmelCase , axis=-1 ) if target is not None: if return_mean: a = tf.reduce_mean(__UpperCAmelCase ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(__UpperCAmelCase ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(__UpperCAmelCase , name=self.name , aggregation='''mean''' if return_mean else '''''' ) return out
361
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } UpperCAmelCase__ = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } UpperCAmelCase__ = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = ['''input_ids''', '''attention_mask'''] __snake_case = DistilBertTokenizer def __init__( self : Dict , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[int]="[UNK]" , __UpperCAmelCase : str="[SEP]" , __UpperCAmelCase : Tuple="[PAD]" , __UpperCAmelCase : Any="[CLS]" , __UpperCAmelCase : int="[MASK]" , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : str , ) ->Optional[int]: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int]=None ) ->Optional[Any]: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
26
0
import os import pytest from transformers.dynamic_module_utils import get_imports UpperCAmelCase__ = "\nimport os\n" UpperCAmelCase__ = "\ndef foo():\n import os\n return False\n" UpperCAmelCase__ = "\ndef foo():\n def bar():\n if True:\n import os\n return False\n return bar()\n" UpperCAmelCase__ = "\nimport os\n\ntry:\n import bar\nexcept ImportError:\n raise ValueError()\n" UpperCAmelCase__ = "\nimport os\n\ndef foo():\n try:\n import bar\n except ImportError:\n raise ValueError()\n" UpperCAmelCase__ = "\nimport os\n\ntry:\n import bar\nexcept (ImportError, AttributeError):\n raise ValueError()\n" UpperCAmelCase__ = "\nimport os\n\ntry:\n import bar\nexcept ImportError as e:\n raise ValueError()\n" UpperCAmelCase__ = "\nimport os\n\ntry:\n import bar\nexcept:\n raise ValueError()\n" UpperCAmelCase__ = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n raise ValueError()\n" UpperCAmelCase__ = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n x = 1\n raise ValueError()\n" UpperCAmelCase__ = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize('''case''' , a ) def _a ( a :Any , a :Optional[Any] ) -> str: a = os.path.join(a , '''test_file.py''' ) with open(a , '''w''' ) as _tmp_file: _tmp_file.write(a ) a = get_imports(a ) assert parsed_imports == ["os"]
362
from __future__ import annotations import typing from collections import Counter def _a ( a :int ) -> typing.Counter[int]: a = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(a , max_perimeter + 1 ): a = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(a ): a = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _a ( a :int = 1_000 ) -> int: a = pythagorean_triple(a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f"""Perimeter {solution()} has maximum solutions""")
26
0
from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''pixel_values'''] def __init__( self : Optional[int] , __UpperCAmelCase : bool = True , __UpperCAmelCase : Dict[str, int] = None , __UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , __UpperCAmelCase : bool = True , __UpperCAmelCase : Dict[str, int] = None , __UpperCAmelCase : bool = True , __UpperCAmelCase : Union[int, float] = 1 / 255 , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN , __UpperCAmelCase : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD , **__UpperCAmelCase : str , ) ->None: """simple docstring""" super().__init__(**__UpperCAmelCase ) a = size if size is not None else {'''shortest_edge''': 224} a = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) a = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} a = get_size_dict(__UpperCAmelCase , param_name='''crop_size''' ) a = do_resize a = size a = resample a = do_center_crop a = crop_size a = do_rescale a = rescale_factor a = do_normalize a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : np.ndarray , __UpperCAmelCase : Dict[str, int] , __UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , __UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **__UpperCAmelCase : Tuple , ) ->np.ndarray: """simple docstring""" a = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: a = int((256 / 224) * size['''shortest_edge'''] ) a = get_resize_output_image_size(__UpperCAmelCase , size=__UpperCAmelCase , default_to_square=__UpperCAmelCase ) a = {'''height''': output_size[0], '''width''': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F"""Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}""" ) return resize( __UpperCAmelCase , size=(size_dict['''height'''], size_dict['''width''']) , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : np.ndarray , __UpperCAmelCase : Dict[str, int] , __UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **__UpperCAmelCase : Optional[int] , ) ->np.ndarray: """simple docstring""" a = get_size_dict(__UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(F"""Size dict must have keys 'height' and 'width'. Got {size.keys()}""" ) return center_crop(__UpperCAmelCase , size=(size['''height'''], size['''width''']) , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : np.ndarray , __UpperCAmelCase : Union[int, float] , __UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **__UpperCAmelCase : Optional[Any] , ) ->np.ndarray: """simple docstring""" return rescale(__UpperCAmelCase , scale=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : np.ndarray , __UpperCAmelCase : Union[float, List[float]] , __UpperCAmelCase : Union[float, List[float]] , __UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **__UpperCAmelCase : Union[str, Any] , ) ->np.ndarray: """simple docstring""" return normalize(__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : ImageInput , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[Dict[str, int]] = None , __UpperCAmelCase : PILImageResampling = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[Dict[str, int]] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[float] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[Union[float, Iterable[float]]] = None , __UpperCAmelCase : Optional[Union[float, Iterable[float]]] = None , __UpperCAmelCase : Optional[TensorType] = None , __UpperCAmelCase : ChannelDimension = ChannelDimension.FIRST , **__UpperCAmelCase : List[Any] , ) ->BatchFeature: """simple docstring""" a = do_resize if do_resize is not None else self.do_resize a = resample if resample is not None else self.resample a = do_center_crop if do_center_crop is not None else self.do_center_crop a = do_rescale if do_rescale is not None else self.do_rescale a = rescale_factor if rescale_factor is not None else self.rescale_factor a = do_normalize if do_normalize is not None else self.do_normalize a = image_mean if image_mean is not None else self.image_mean a = image_std if image_std is not None else self.image_std a = size if size is not None else self.size a = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) a = crop_size if crop_size is not None else self.crop_size a = get_size_dict(__UpperCAmelCase , param_name='''crop_size''' ) a = make_list_of_images(__UpperCAmelCase ) if not valid_images(__UpperCAmelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. a = [to_numpy_array(__UpperCAmelCase ) for image in images] if do_resize: a = [self.resize(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) for image in images] if do_center_crop: a = [self.center_crop(__UpperCAmelCase , __UpperCAmelCase ) for image in images] if do_rescale: a = [self.rescale(__UpperCAmelCase , __UpperCAmelCase ) for image in images] if do_normalize: a = [self.normalize(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) for image in images] a = [to_channel_dimension_format(__UpperCAmelCase , __UpperCAmelCase ) for image in images] a = {'''pixel_values''': images} return BatchFeature(data=__UpperCAmelCase , tensor_type=__UpperCAmelCase )
363
from __future__ import annotations def _a ( a :dict , a :str ) -> set[str]: a , a = set(a ), [start] while stack: a = stack.pop() explored.add(a ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a ) return explored UpperCAmelCase__ = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, "A"))
26
0
from math import sqrt def _a ( a :int ) -> int: a = 0 for i in range(1 , int(sqrt(a ) + 1 ) ): if n % i == 0 and i != sqrt(a ): total += i + n // i elif i == sqrt(a ): total += i return total - n def _a ( a :int = 10_000 ) -> int: a = sum( i for i in range(1 , a ) if sum_of_divisors(sum_of_divisors(a ) ) == i and sum_of_divisors(a ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
364
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase__ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex UpperCAmelCase__ = 10 UpperCAmelCase__ = 256 def _a ( a :List[str] ) -> Optional[MinHash]: if len(a ) < MIN_NUM_TOKENS: return None a = MinHash(num_perm=a ) for token in set(a ): min_hash.update(token.encode() ) return min_hash def _a ( a :str ) -> Set[str]: return {t for t in NON_ALPHA.split(a ) if len(t.strip() ) > 0} class lowercase_ : '''simple docstring''' def __init__( self : Any , *, __UpperCAmelCase : float = 0.85 , ) ->Dict: """simple docstring""" a = duplication_jaccard_threshold a = NUM_PERM a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) a = defaultdict(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : MinHash ) ->None: """simple docstring""" a = self._index.query(__UpperCAmelCase ) if code_key in self._index.keys: print(F"""Duplicate key {code_key}""" ) return self._index.insert(__UpperCAmelCase , __UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__UpperCAmelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->List[List[Dict]]: """simple docstring""" a = [] for base, duplicates in self._duplicate_clusters.items(): a = [base] + list(__UpperCAmelCase ) # reformat the cluster to be a list of dict a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(__UpperCAmelCase ) return duplicate_clusters def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Dict ) ->None: """simple docstring""" a = self.get_duplicate_clusters() with open(__UpperCAmelCase , '''w''' ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def _a ( a :List[Any] ) -> List[Any]: a , a = element a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _a ( a :Type[Dataset] ) -> List[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(a , max_queue_size=10_000 ) , chunksize=100 , ): if data is not None: yield data def _a ( a :Type[Dataset] , a :float ) -> str: a = DuplicationIndex(duplication_jaccard_threshold=a ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a ) ) , max_queue_size=100 ) ): di.add(a , a ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _a ( a :str , a :str ) -> float: a = get_tokens(a ) a = get_tokens(a ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase__ = None def _a ( a :Tuple , a :Tuple ) -> Any: a = [] for elementa in cluster: a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(a , a ) >= jaccard_threshold: elementa["copies"] += 1 break else: a = 1 extremes.append(a ) return extremes def _a ( a :List[Any] , a :Optional[Any] , a :Union[str, Any] ) -> Optional[int]: global _shared_dataset a = dataset a = [] a = partial(_find_cluster_extremes_shared , jaccard_threshold=a ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( a , a , ) , total=len(a ) , ): extremes_list.append(a ) return extremes_list def _a ( a :Type[Dataset] , a :float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: a = make_duplicate_clusters(a , a ) a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} a = {} a = find_extremes(a , a , a ) for extremes in extremes_clusters: for element in extremes: a = element a = duplicate_indices - set(extreme_dict.keys() ) a = dataset.filter(lambda a , a : idx not in remove_indices , with_indices=a ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: a = element['''base_index'''] in extreme_dict if element["is_extreme"]: a = extreme_dict[element['''base_index''']]['''copies'''] print(F"""Original dataset size: {len(a )}""" ) print(F"""Number of duplicate clusters: {len(a )}""" ) print(F"""Files in duplicate cluster: {len(a )}""" ) print(F"""Unique files in duplicate cluster: {len(a )}""" ) print(F"""Filtered dataset size: {len(a )}""" ) return ds_filter, duplicate_clusters
26
0
def _a ( a :int ) -> bool: if not isinstance(a , a ): a = F"""Input value of [number={number}] must be an integer""" raise TypeError(a ) if number < 0: return False a = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
365
from math import ceil, sqrt def _a ( a :int = 1_000_000 ) -> int: a = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: a = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
26
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
366
UpperCAmelCase__ = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
26
0
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''time_series_transformer''' __snake_case = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : str , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : str = "student_t" , __UpperCAmelCase : str = "nll" , __UpperCAmelCase : int = 1 , __UpperCAmelCase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __UpperCAmelCase : Optional[Union[str, bool]] = "mean" , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : int = 32 , __UpperCAmelCase : int = 32 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : bool = True , __UpperCAmelCase : str = "gelu" , __UpperCAmelCase : int = 64 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : int = 100 , __UpperCAmelCase : float = 0.02 , __UpperCAmelCase : List[Any]=True , **__UpperCAmelCase : Dict , ) ->int: """simple docstring""" a = prediction_length a = context_length or prediction_length a = distribution_output a = loss a = input_size a = num_time_features a = lags_sequence a = scaling a = num_dynamic_real_features a = num_static_real_features a = num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(__UpperCAmelCase ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) a = cardinality else: a = [0] if embedding_dimension and num_static_categorical_features > 0: if len(__UpperCAmelCase ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) a = embedding_dimension else: a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] a = num_parallel_samples # Transformer architecture configuration a = input_size * len(__UpperCAmelCase ) + self._number_of_features a = d_model a = encoder_attention_heads a = decoder_attention_heads a = encoder_ffn_dim a = decoder_ffn_dim a = encoder_layers a = decoder_layers a = dropout a = attention_dropout a = activation_dropout a = encoder_layerdrop a = decoder_layerdrop a = activation_function a = init_std a = use_cache super().__init__(is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
367
def _a ( a :list ) -> list: if len(a ) <= 1: return lst a = 1 while i < len(a ): if lst[i - 1] <= lst[i]: i += 1 else: a , a = lst[i], lst[i - 1] i -= 1 if i == 0: a = 1 return lst if __name__ == "__main__": UpperCAmelCase__ = input("Enter numbers separated by a comma:\n").strip() UpperCAmelCase__ = [int(item) for item in user_input.split(",")] print(gnome_sort(unsorted))
26
0
"""simple docstring""" 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 UpperCAmelCase__ = 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 lowercase_ : '''simple docstring''' def __init__( self : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : Any=16 , __UpperCAmelCase : Any=13 , __UpperCAmelCase : Any=7 , __UpperCAmelCase : Optional[Any]=14 , __UpperCAmelCase : Union[str, Any]=10 , __UpperCAmelCase : Tuple=19 , __UpperCAmelCase : Any=5 , __UpperCAmelCase : Optional[int]=4 , __UpperCAmelCase : int=True , __UpperCAmelCase : List[str]=16 , __UpperCAmelCase : Tuple=2 , __UpperCAmelCase : Any=4 , __UpperCAmelCase : Tuple=4 , __UpperCAmelCase : Any="gelu" , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : Tuple=0.1 , __UpperCAmelCase : Optional[int]=[1, 2, 3, 4, 5] , __UpperCAmelCase : List[Any]=25 , __UpperCAmelCase : Union[str, Any]=5 , ) ->Optional[Any]: """simple docstring""" a = d_model a = parent a = batch_size a = prediction_length a = context_length a = cardinality a = num_time_features a = lags_sequence a = embedding_dimension a = is_training a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = context_length a = prediction_length + label_length a = label_length a = moving_average a = autocorrelation_factor def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" 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 __lowerCAmelCase ( self : str , __UpperCAmelCase : Optional[int] ) ->Dict: """simple docstring""" a = config.context_length + max(config.lags_sequence ) a = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) a = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) a = floats_tensor([self.batch_size, _past_length] ) a = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs a = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) a = floats_tensor([self.batch_size, config.prediction_length] ) a = { '''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 __lowerCAmelCase ( self : int ) ->int: """simple docstring""" a = self.get_config() a = self.prepare_autoformer_inputs_dict(__UpperCAmelCase ) return config, inputs_dict def __lowerCAmelCase ( self : str ) ->List[str]: """simple docstring""" a , a = self.prepare_config_and_inputs() return config, inputs_dict def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple ) ->Union[str, Any]: """simple docstring""" a = AutoformerModel(config=__UpperCAmelCase ).to(__UpperCAmelCase ).eval() a = model(**__UpperCAmelCase ) a = outputs.encoder_last_hidden_state a = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: a = model.get_encoder() encoder.save_pretrained(__UpperCAmelCase ) a = AutoformerEncoder.from_pretrained(__UpperCAmelCase ).to(__UpperCAmelCase ) a , a , a , a , a = model.create_network_inputs(**__UpperCAmelCase ) a , a = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) a = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) a = encoder(inputs_embeds=__UpperCAmelCase )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) a = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) a = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) a = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) a = 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: a = model.get_decoder() decoder.save_pretrained(__UpperCAmelCase ) a = AutoformerDecoder.from_pretrained(__UpperCAmelCase ).to(__UpperCAmelCase ) a = decoder( trend=__UpperCAmelCase , inputs_embeds=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class lowercase_ ( lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () __snake_case = (AutoformerForPrediction,) if is_torch_available() else () __snake_case = {'''feature-extraction''': AutoformerModel} if is_torch_available() else {} __snake_case = False __snake_case = False __snake_case = False __snake_case = False __snake_case = False __snake_case = False def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = AutoformerModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: a = model_class(__UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) a , a = model_class.from_pretrained(__UpperCAmelCase , output_loading_info=__UpperCAmelCase ) self.assertEqual(info['''missing_keys'''] , [] ) def __lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*__UpperCAmelCase ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" pass def __lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" a = inspect.signature(getattr(__UpperCAmelCase , '''forward''' ) ) # The main input is the name of the argument after `self` a = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , __UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__UpperCAmelCase ) a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = [ '''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(__UpperCAmelCase )] , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() a = True a = getattr(self.model_tester , '''seq_length''' , __UpperCAmelCase ) a = getattr(self.model_tester , '''decoder_seq_length''' , __UpperCAmelCase ) a = getattr(self.model_tester , '''encoder_seq_length''' , __UpperCAmelCase ) a = getattr(self.model_tester , '''d_model''' , __UpperCAmelCase ) a = getattr(self.model_tester , '''num_attention_heads''' , __UpperCAmelCase ) a = d_model // num_attention_heads for model_class in self.all_model_classes: a = True a = False a = True a = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__UpperCAmelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] a = True a = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) a = outputs.encoder_attentions self.assertEqual(len(__UpperCAmelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) a = len(__UpperCAmelCase ) a = 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(__UpperCAmelCase , __UpperCAmelCase ) # decoder attentions a = outputs.decoder_attentions self.assertIsInstance(__UpperCAmelCase , (list, tuple) ) self.assertEqual(len(__UpperCAmelCase ) , 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 a = outputs.cross_attentions self.assertIsInstance(__UpperCAmelCase , (list, tuple) ) self.assertEqual(len(__UpperCAmelCase ) , 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 a = True a = True a = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) ) self.assertEqual(out_len + 2 , len(__UpperCAmelCase ) ) a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__UpperCAmelCase ) , 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 __lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" super().test_retain_grad_hidden_states_attentions() def _a ( a :List[str]="train-batch.pt" ) -> List[Any]: a = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=a , repo_type='''dataset''' ) a = torch.load(a , map_location=a ) return batch @require_torch @slow class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" a = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__UpperCAmelCase ) a = prepare_batch() with torch.no_grad(): a = 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] a = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , __UpperCAmelCase ) a = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=__UpperCAmelCase ) self.assertTrue(torch.allclose(output[0, :3, :3] , __UpperCAmelCase , atol=__UpperCAmelCase ) ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__UpperCAmelCase ) a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): a = 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 a = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , __UpperCAmelCase ) a = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=__UpperCAmelCase ) self.assertTrue(torch.allclose(output[0, :3, :3] , __UpperCAmelCase , atol=__UpperCAmelCase ) ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(__UpperCAmelCase ) a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): a = 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'''] , ) a = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , __UpperCAmelCase ) a = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=__UpperCAmelCase ) a = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , __UpperCAmelCase , rtol=1e-1 ) )
368
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
0
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 DetrImageProcessor class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , __UpperCAmelCase : Any , __UpperCAmelCase : Tuple=7 , __UpperCAmelCase : str=3 , __UpperCAmelCase : Union[str, Any]=30 , __UpperCAmelCase : Optional[Any]=400 , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : int=None , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Optional[int]=1 / 255 , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Any=[0.5, 0.5, 0.5] , __UpperCAmelCase : Optional[int]=[0.5, 0.5, 0.5] , __UpperCAmelCase : Any=True , ) ->Dict: """simple docstring""" a = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1_333} a = parent a = batch_size a = num_channels a = min_resolution a = max_resolution a = do_resize a = size a = do_rescale a = rescale_factor a = do_normalize a = image_mean a = image_std a = do_pad def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __lowerCAmelCase ( self : int , __UpperCAmelCase : Any , __UpperCAmelCase : Any=False ) ->int: """simple docstring""" if not batched: a = image_inputs[0] if isinstance(__UpperCAmelCase , Image.Image ): a , a = image.size else: a , a = image.shape[1], image.shape[2] if w < h: a = int(self.size['''shortest_edge'''] * h / w ) a = self.size['''shortest_edge'''] elif w > h: a = self.size['''shortest_edge'''] a = int(self.size['''shortest_edge'''] * w / h ) else: a = self.size['''shortest_edge'''] a = self.size['''shortest_edge'''] else: a = [] for image in image_inputs: a , a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) a = max(__UpperCAmelCase , key=lambda __UpperCAmelCase : item[0] )[0] a = max(__UpperCAmelCase , key=lambda __UpperCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = DetrImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = DetrImageProcessingTester(self ) @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , '''image_mean''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''image_std''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_rescale''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''rescale_factor''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_resize''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''size''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_pad''' ) ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1_333} ) self.assertEqual(image_processor.do_pad , __UpperCAmelCase ) a = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__UpperCAmelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , __UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" pass def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values a , a = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a , a = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase ) a = image_processing(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values a , a = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a = image_processing(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values a , a = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values a , a = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a = image_processing(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values a , a = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: a = json.loads(f.read() ) a = {'''image_id''': 39_769, '''annotations''': target} # encode them a = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50''' ) a = image_processing(images=__UpperCAmelCase , annotations=__UpperCAmelCase , return_tensors='''pt''' ) # verify pixel values a = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['''pixel_values'''].shape , __UpperCAmelCase ) a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , __UpperCAmelCase , atol=1e-4 ) ) # verify area a = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , __UpperCAmelCase ) ) # verify boxes a = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , __UpperCAmelCase ) a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , __UpperCAmelCase , atol=1e-3 ) ) # verify image_id a = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , __UpperCAmelCase ) ) # verify is_crowd a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , __UpperCAmelCase ) ) # verify class_labels a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , __UpperCAmelCase ) ) # verify orig_size a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , __UpperCAmelCase ) ) # verify size a = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , __UpperCAmelCase ) ) @slow def __lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: a = json.loads(f.read() ) a = {'''file_name''': '''000000039769.png''', '''image_id''': 39_769, '''segments_info''': target} a = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them a = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50-panoptic''' ) a = image_processing(images=__UpperCAmelCase , annotations=__UpperCAmelCase , masks_path=__UpperCAmelCase , return_tensors='''pt''' ) # verify pixel values a = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['''pixel_values'''].shape , __UpperCAmelCase ) a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , __UpperCAmelCase , atol=1e-4 ) ) # verify area a = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , __UpperCAmelCase ) ) # verify boxes a = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , __UpperCAmelCase ) a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , __UpperCAmelCase , atol=1e-3 ) ) # verify image_id a = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , __UpperCAmelCase ) ) # verify is_crowd a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , __UpperCAmelCase ) ) # verify class_labels a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , __UpperCAmelCase ) ) # verify masks a = 822_873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , __UpperCAmelCase ) # verify orig_size a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , __UpperCAmelCase ) ) # verify size a = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , __UpperCAmelCase ) )
369
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = OrderedDict( [ ("audio-spectrogram-transformer", "ASTFeatureExtractor"), ("beit", "BeitFeatureExtractor"), ("chinese_clip", "ChineseCLIPFeatureExtractor"), ("clap", "ClapFeatureExtractor"), ("clip", "CLIPFeatureExtractor"), ("clipseg", "ViTFeatureExtractor"), ("conditional_detr", "ConditionalDetrFeatureExtractor"), ("convnext", "ConvNextFeatureExtractor"), ("cvt", "ConvNextFeatureExtractor"), ("data2vec-audio", "Wav2Vec2FeatureExtractor"), ("data2vec-vision", "BeitFeatureExtractor"), ("deformable_detr", "DeformableDetrFeatureExtractor"), ("deit", "DeiTFeatureExtractor"), ("detr", "DetrFeatureExtractor"), ("dinat", "ViTFeatureExtractor"), ("donut-swin", "DonutFeatureExtractor"), ("dpt", "DPTFeatureExtractor"), ("encodec", "EncodecFeatureExtractor"), ("flava", "FlavaFeatureExtractor"), ("glpn", "GLPNFeatureExtractor"), ("groupvit", "CLIPFeatureExtractor"), ("hubert", "Wav2Vec2FeatureExtractor"), ("imagegpt", "ImageGPTFeatureExtractor"), ("layoutlmv2", "LayoutLMv2FeatureExtractor"), ("layoutlmv3", "LayoutLMv3FeatureExtractor"), ("levit", "LevitFeatureExtractor"), ("maskformer", "MaskFormerFeatureExtractor"), ("mctct", "MCTCTFeatureExtractor"), ("mobilenet_v1", "MobileNetV1FeatureExtractor"), ("mobilenet_v2", "MobileNetV2FeatureExtractor"), ("mobilevit", "MobileViTFeatureExtractor"), ("nat", "ViTFeatureExtractor"), ("owlvit", "OwlViTFeatureExtractor"), ("perceiver", "PerceiverFeatureExtractor"), ("poolformer", "PoolFormerFeatureExtractor"), ("regnet", "ConvNextFeatureExtractor"), ("resnet", "ConvNextFeatureExtractor"), ("segformer", "SegformerFeatureExtractor"), ("sew", "Wav2Vec2FeatureExtractor"), ("sew-d", "Wav2Vec2FeatureExtractor"), ("speech_to_text", "Speech2TextFeatureExtractor"), ("speecht5", "SpeechT5FeatureExtractor"), ("swiftformer", "ViTFeatureExtractor"), ("swin", "ViTFeatureExtractor"), ("swinv2", "ViTFeatureExtractor"), ("table-transformer", "DetrFeatureExtractor"), ("timesformer", "VideoMAEFeatureExtractor"), ("tvlt", "TvltFeatureExtractor"), ("unispeech", "Wav2Vec2FeatureExtractor"), ("unispeech-sat", "Wav2Vec2FeatureExtractor"), ("van", "ConvNextFeatureExtractor"), ("videomae", "VideoMAEFeatureExtractor"), ("vilt", "ViltFeatureExtractor"), ("vit", "ViTFeatureExtractor"), ("vit_mae", "ViTFeatureExtractor"), ("vit_msn", "ViTFeatureExtractor"), ("wav2vec2", "Wav2Vec2FeatureExtractor"), ("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"), ("wavlm", "Wav2Vec2FeatureExtractor"), ("whisper", "WhisperFeatureExtractor"), ("xclip", "CLIPFeatureExtractor"), ("yolos", "YolosFeatureExtractor"), ] ) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _a ( a :str ) -> Any: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: a = model_type_to_module_name(a ) a = importlib.import_module(F""".{module_name}""" , '''transformers.models''' ) try: return getattr(a , a ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(a , '''__name__''' , a ) == 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. a = importlib.import_module('''transformers''' ) if hasattr(a , a ): return getattr(a , a ) return None def _a ( a :Union[str, os.PathLike] , a :Optional[Union[str, os.PathLike]] = None , a :bool = False , a :bool = False , a :Optional[Dict[str, str]] = None , a :Optional[Union[bool, str]] = None , a :Optional[str] = None , a :bool = False , **a :int , ) -> Tuple: a = get_file_from_repo( a , a , cache_dir=a , force_download=a , resume_download=a , proxies=a , use_auth_token=a , revision=a , local_files_only=a , ) 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(a , encoding='''utf-8''' ) as reader: return json.load(a ) class lowercase_ : '''simple docstring''' def __init__( self : Tuple ) ->int: """simple docstring""" raise EnvironmentError( '''AutoFeatureExtractor is designed to be instantiated ''' '''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__UpperCAmelCase ) def __lowerCAmelCase ( cls : int , __UpperCAmelCase : Optional[Any] , **__UpperCAmelCase : Dict ) ->List[Any]: """simple docstring""" a = kwargs.pop('''config''' , __UpperCAmelCase ) a = kwargs.pop('''trust_remote_code''' , __UpperCAmelCase ) a = True a , a = FeatureExtractionMixin.get_feature_extractor_dict(__UpperCAmelCase , **__UpperCAmelCase ) a = config_dict.get('''feature_extractor_type''' , __UpperCAmelCase ) a = None if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a = 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(__UpperCAmelCase , __UpperCAmelCase ): a = AutoConfig.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) # It could be in `config.feature_extractor_type`` a = getattr(__UpperCAmelCase , '''feature_extractor_type''' , __UpperCAmelCase ) if hasattr(__UpperCAmelCase , '''auto_map''' ) and "AutoFeatureExtractor" in config.auto_map: a = config.auto_map['''AutoFeatureExtractor'''] if feature_extractor_class is not None: a = feature_extractor_class_from_name(__UpperCAmelCase ) a = feature_extractor_auto_map is not None a = feature_extractor_class is not None or type(__UpperCAmelCase ) in FEATURE_EXTRACTOR_MAPPING a = resolve_trust_remote_code( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if has_remote_code and trust_remote_code: a = get_class_from_dynamic_module( __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ) a = kwargs.pop('''code_revision''' , __UpperCAmelCase ) if os.path.isdir(__UpperCAmelCase ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(__UpperCAmelCase ) in FEATURE_EXTRACTOR_MAPPING: a = FEATURE_EXTRACTOR_MAPPING[type(__UpperCAmelCase )] return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) 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 __lowerCAmelCase ( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple ) ->Optional[int]: """simple docstring""" FEATURE_EXTRACTOR_MAPPING.register(__UpperCAmelCase , __UpperCAmelCase )
26
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 UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''levit''' def __init__( self : str , __UpperCAmelCase : Dict=224 , __UpperCAmelCase : int=3 , __UpperCAmelCase : Dict=3 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : Dict=1 , __UpperCAmelCase : Optional[Any]=16 , __UpperCAmelCase : Optional[int]=[128, 256, 384] , __UpperCAmelCase : Optional[int]=[4, 8, 12] , __UpperCAmelCase : Dict=[4, 4, 4] , __UpperCAmelCase : Dict=[16, 16, 16] , __UpperCAmelCase : Optional[int]=0 , __UpperCAmelCase : Optional[int]=[2, 2, 2] , __UpperCAmelCase : Optional[int]=[2, 2, 2] , __UpperCAmelCase : Dict=0.02 , **__UpperCAmelCase : Dict , ) ->int: """simple docstring""" super().__init__(**__UpperCAmelCase ) a = image_size a = num_channels a = kernel_size a = stride a = padding a = hidden_sizes a = num_attention_heads a = depths a = key_dim a = drop_path_rate a = patch_size a = attention_ratio a = mlp_ratio a = initializer_range a = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = version.parse('''1.11''' ) @property def __lowerCAmelCase ( self : str ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __lowerCAmelCase ( self : int ) ->float: """simple docstring""" return 1e-4
370
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = BlipImageProcessor() a = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''' ) a = BertTokenizerFast.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) a = InstructBlipProcessor(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Tuple ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).tokenizer def __lowerCAmelCase ( self : int , **__UpperCAmelCase : str ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).image_processor def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->Optional[Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).qformer_tokenizer def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" a = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) self.assertIsInstance(processor.qformer_tokenizer , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) a = qformer_tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['''qformer_''' + key] ) def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Dict ) ->List[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , )
26
0
from __future__ import annotations from collections.abc import Callable def _a ( a :Callable[[int | float], int | float] , a :int | float , a :int | float , a :int = 100 , ) -> float: a = x_start a = fnc(a ) a = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area a = (x_end - x_start) / steps + xa a = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step a = xa a = fxa return area if __name__ == "__main__": def _a ( a :int ) -> Tuple: return x**3 + x**2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") UpperCAmelCase__ = 10 while i <= 100000: print(f"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
371
import math def _a ( a :int = 100 ) -> int: a = sum(i * i for i in range(1 , n + 1 ) ) a = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
26
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 UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "spiece.model"} UpperCAmelCase__ = { "vocab_file": { "TsinghuaAI/CPM-Generate": "https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model", } } class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Any=True , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : List[str]="<s>" , __UpperCAmelCase : int="</s>" , __UpperCAmelCase : Any="<unk>" , __UpperCAmelCase : Optional[Any]="<sep>" , __UpperCAmelCase : int="<pad>" , __UpperCAmelCase : Any="<cls>" , __UpperCAmelCase : List[str]="<mask>" , __UpperCAmelCase : Optional[int]=["<eop>", "<eod>"] , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : Union[str, Any] , ) ->None: """simple docstring""" a = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) a = 3 a = do_lower_case a = remove_space a = keep_accents a = vocab_file a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) a = jieba a = str.maketrans(''' \n''' , '''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" return len(self.sp_model ) def __lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" a = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = self.__dict__.copy() a = None return state def __setstate__( self : List[str] , __UpperCAmelCase : Optional[int] ) ->str: """simple docstring""" a = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a = {} a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] ) ->List[str]: """simple docstring""" if self.remove_space: a = ''' '''.join(inputs.strip().split() ) else: a = inputs a = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: a = unicodedata.normalize('''NFKD''' , __UpperCAmelCase ) a = ''''''.join([c for c in outputs if not unicodedata.combining(__UpperCAmelCase )] ) if self.do_lower_case: a = outputs.lower() return outputs def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = self.preprocess_text(__UpperCAmelCase ) a = self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) a = [] for piece in pieces: if len(__UpperCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): a = self.sp_model.EncodeAsPieces(piece[:-1].replace(__UpperCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: a = cur_pieces[1:] else: a = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__UpperCAmelCase ) else: new_pieces.append(__UpperCAmelCase ) return new_pieces def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Any ) ->Any: """simple docstring""" return self.sp_model.PieceToId(__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Dict ) ->Union[str, Any]: """simple docstring""" return self.sp_model.IdToPiece(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = ''''''.join(__UpperCAmelCase ).replace(__UpperCAmelCase , ''' ''' ).strip() return out_string def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase , token_ids_a=__UpperCAmelCase , already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is not None: return ([0] * len(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] return ([0] * len(__UpperCAmelCase )) + [1, 1] def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a = os.path.join( __UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase , '''wb''' ) as fi: a = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,) def __lowerCAmelCase ( self : Any , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = super()._decode(*__UpperCAmelCase , **__UpperCAmelCase ) a = text.replace(''' ''' , '''''' ).replace('''\u2582''' , ''' ''' ).replace('''\u2583''' , '''\n''' ) return text
350
def _a ( a :int = 600_851_475_143 ) -> int: try: a = int(a ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''' ) a = 2 a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 a = i while n % i == 0: a = n // i i += 1 return int(a ) if __name__ == "__main__": print(f"""{solution() = }""")
26
0
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class lowercase_ ( lowercase , unittest.TestCase ): __snake_case = VideoToVideoSDPipeline __snake_case = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'''video'''} ) - {'''image''', '''width''', '''height'''} __snake_case = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''video'''} ) - {'''image'''} __snake_case = PipelineTesterMixin.required_optional_params - {'''latents'''} __snake_case = False # No `output_type`. __snake_case = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" torch.manual_seed(0 ) a = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') , up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') , cross_attention_dim=32 , attention_head_dim=4 , ) a = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=__UpperCAmelCase , set_alpha_to_one=__UpperCAmelCase , ) torch.manual_seed(0 ) a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act='''gelu''' , projection_dim=512 , ) a = CLIPTextModel(__UpperCAmelCase ) a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) a = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def __lowerCAmelCase ( self : str , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any]=0 ) ->Optional[Any]: """simple docstring""" a = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''A painting of a squirrel eating a burger''', '''video''': video, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def __lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = VideoToVideoSDPipeline(**__UpperCAmelCase ) a = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_dummy_inputs(__UpperCAmelCase ) a = '''np''' a = sd_pipe(**__UpperCAmelCase ).frames a = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) a = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__UpperCAmelCase , expected_max_diff=5e-3 ) @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def __lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" pass @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' ) def __lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" pass def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" return super().test_progress_bar() @slow @skip_mps class lowercase_ ( unittest.TestCase ): def __lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" a = VideoToVideoSDPipeline.from_pretrained('''cerspense/zeroscope_v2_XL''' , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames a = torch.Generator(device='''cpu''' ).manual_seed(0 ) a = torch.randn((1, 10, 3, 1_024, 576) , generator=__UpperCAmelCase ) a = video.to('''cuda''' ) a = '''Spiderman is surfing''' a = pipe(__UpperCAmelCase , video=__UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=3 , output_type='''pt''' ).frames a = np.array([-1.0458984, -1.1279297, -0.9663086, -0.91503906, -0.75097656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
351
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ = "bart" UpperCAmelCase__ = True @st.cache(allow_output_mutation=a ) def _a ( ) -> Tuple: if LOAD_DENSE_INDEX: a = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) a = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) a = qar_model.eval() else: a , a = (None, None) if MODEL_TYPE == "bart": a = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) a = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) a = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) a = sas_model.eval() else: a , a = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def _a ( ) -> Dict: if LOAD_DENSE_INDEX: a = faiss.StandardGpuResources() a = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] a = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) a = faiss.IndexFlatIP(128 ) a = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: a , a = (None, None) a = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def _a ( ) -> Optional[int]: a = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) a = elia['''train_eli5'''] a = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) a = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = load_indexes() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = load_models() UpperCAmelCase__ , UpperCAmelCase__ = load_train_data() def _a ( a :str , a :Tuple=10 ) -> List[str]: a = embed_questions_for_retrieval([question] , a , a ) a , a = eli5_train_q_index.search(a , a ) a = [elia_train[int(a )] for i in I[0]] return nn_examples def _a ( a :str , a :Any="wiki40b" , a :int="dense" , a :Union[str, Any]=10 ) -> List[str]: if source == "none": a , a = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": a , a = query_qa_dense_index( a , a , a , a , a , a ) else: a , a = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) a = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] a = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def _a ( a :Tuple , a :int , a :int , a :Dict=64 , a :List[Any]=256 , a :List[Any]=False , a :List[Any]=2 , a :Tuple=0.95 , a :Optional[Any]=0.8 ) -> int: with torch.no_grad(): a = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=1_024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar UpperCAmelCase__ = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" UpperCAmelCase__ = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] UpperCAmelCase__ = st.sidebar.checkbox("Demo options") if demo_options: UpperCAmelCase__ = st.sidebar.selectbox( "", action_list, index=3, ) UpperCAmelCase__ = action_list.index(action_st) UpperCAmelCase__ = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) UpperCAmelCase__ = show_type == "Show full text of passages" else: UpperCAmelCase__ = 3 UpperCAmelCase__ = True UpperCAmelCase__ = st.sidebar.checkbox("Retrieval options") if retrieval_options: UpperCAmelCase__ = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) UpperCAmelCase__ = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) UpperCAmelCase__ = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: UpperCAmelCase__ = "wiki40b" UpperCAmelCase__ = "dense" UpperCAmelCase__ = "beam" UpperCAmelCase__ = 2 UpperCAmelCase__ = 64 UpperCAmelCase__ = 256 UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = st.sidebar.checkbox("Generation options") if generate_options: UpperCAmelCase__ = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) UpperCAmelCase__ = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) UpperCAmelCase__ = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ = None # start main text UpperCAmelCase__ = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] UpperCAmelCase__ = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ = st.text_input("Enter your question here:", "") else: UpperCAmelCase__ = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method="dense", n_results=10) UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method="sparse", n_results=10) UpperCAmelCase__ = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ = support_list[:10] UpperCAmelCase__ = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: UpperCAmelCase__ , UpperCAmelCase__ = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ , UpperCAmelCase__ = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): UpperCAmelCase__ = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) UpperCAmelCase__ = res[1].strip() if sec_titles == "": UpperCAmelCase__ = "[{}]({})".format(res[0], wiki_url) else: UpperCAmelCase__ = sec_titles.split(" & ") UpperCAmelCase__ = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ = find_nearest_training(question) UpperCAmelCase__ = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) UpperCAmelCase__ = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) UpperCAmelCase__ = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
26
0
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : Union[str, "sqlalchemy.sql.Selectable"] , __UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , __UpperCAmelCase : Optional[Features] = None , __UpperCAmelCase : str = None , __UpperCAmelCase : bool = False , **__UpperCAmelCase : str , ) ->Any: """simple docstring""" super().__init__(features=__UpperCAmelCase , cache_dir=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase , **__UpperCAmelCase ) a = Sql( cache_dir=__UpperCAmelCase , features=__UpperCAmelCase , sql=__UpperCAmelCase , con=__UpperCAmelCase , **__UpperCAmelCase , ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = None a = None a = None a = None self.builder.download_and_prepare( download_config=__UpperCAmelCase , download_mode=__UpperCAmelCase , verification_mode=__UpperCAmelCase , base_path=__UpperCAmelCase , ) # Build dataset for splits a = self.builder.as_dataset( split='''train''' , verification_mode=__UpperCAmelCase , in_memory=self.keep_in_memory ) return dataset class lowercase_ : '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : Dataset , __UpperCAmelCase : str , __UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[int] = None , **__UpperCAmelCase : Any , ) ->str: """simple docstring""" if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) a = dataset a = name a = con a = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE a = num_proc a = to_sql_kwargs def __lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" a = self.to_sql_kwargs.pop('''sql''' , __UpperCAmelCase ) a = self.to_sql_kwargs.pop('''con''' , __UpperCAmelCase ) a = self.to_sql_kwargs.pop('''index''' , __UpperCAmelCase ) a = self._write(index=__UpperCAmelCase , **self.to_sql_kwargs ) return written def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Tuple ) ->List[Any]: """simple docstring""" a , a , a = args a = {**to_sql_kwargs, '''if_exists''': '''append'''} if offset > 0 else to_sql_kwargs a = query_table( table=self.dataset.data , key=slice(__UpperCAmelCase , offset + self.batch_size ) , indices=self.dataset._indices , ) a = batch.to_pandas() a = df.to_sql(self.name , self.con , index=__UpperCAmelCase , **__UpperCAmelCase ) return num_rows or len(__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[Any] , **__UpperCAmelCase : List[str] ) ->int: """simple docstring""" a = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating SQL from Arrow format''' , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: a , a = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , __UpperCAmelCase , __UpperCAmelCase )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating SQL from Arrow format''' , ): written += num_rows return written
352
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ = "▁" UpperCAmelCase__ = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = BertGenerationTokenizer __snake_case = False __snake_case = True def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" super().setUp() a = BertGenerationTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = '''<s>''' a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(__UpperCAmelCase ) , 1_002 ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def __lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" a = BertGenerationTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) a = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__UpperCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [285, 46, 10, 170, 382] , ) a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) a = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) a = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" return BertGenerationTokenizer.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) @slow def __lowerCAmelCase ( self : Any ) ->str: """simple docstring""" a = '''Hello World!''' a = [18_536, 2_260, 101] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) a = [ 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, ] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @require_torch @slow def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence a = list(self.big_tokenizer.get_vocab().keys() )[:10] a = ''' '''.join(__UpperCAmelCase ) a = self.big_tokenizer.encode_plus(__UpperCAmelCase , return_tensors='''pt''' , return_token_type_ids=__UpperCAmelCase ) a = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=__UpperCAmelCase ) a = BertGenerationConfig() a = BertGenerationEncoder(__UpperCAmelCase ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__UpperCAmelCase ) model(**__UpperCAmelCase ) @slow def __lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" a = {'''input_ids''': [[39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114], [448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='''google/bert_for_seq_generation_L-24_bbc_encoder''' , revision='''c817d1fd1be2ffa69431227a1fe320544943d4db''' , )
26
0
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : str , *__UpperCAmelCase : Union[str, Any] , **__UpperCAmelCase : Tuple ) ->None: """simple docstring""" warnings.warn( '''The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use MobileViTImageProcessor instead.''' , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
353
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger("transformers.models.speecht5") def _a ( a :Optional[Any] , a :Tuple , a :Dict ) -> List[str]: hf_model.apply_weight_norm() a = checkpoint['''input_conv.weight_g'''] a = checkpoint['''input_conv.weight_v'''] a = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): a = checkpoint[F"""upsamples.{i}.1.weight_g"""] a = checkpoint[F"""upsamples.{i}.1.weight_v"""] a = checkpoint[F"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): a = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_g"""] a = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_v"""] a = checkpoint[F"""blocks.{i}.convs1.{j}.1.bias"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_g"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_v"""] a = checkpoint[F"""blocks.{i}.convs2.{j}.1.bias"""] a = checkpoint['''output_conv.1.weight_g'''] a = checkpoint['''output_conv.1.weight_v'''] a = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def _a ( a :List[str] , a :Union[str, Any] , a :Dict , a :Dict=None , a :List[Any]=None , ) -> int: if config_path is not None: a = SpeechTaHifiGanConfig.from_pretrained(a ) else: a = SpeechTaHifiGanConfig() a = SpeechTaHifiGan(a ) a = torch.load(a ) load_weights(orig_checkpoint['''model''']['''generator'''] , a , a ) a = np.load(a ) a = stats[0].reshape(-1 ) a = stats[1].reshape(-1 ) a = torch.from_numpy(a ).float() a = torch.from_numpy(a ).float() model.save_pretrained(a ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--stats_path", required=True, default=None, type=str, help="Path to stats.npy file") 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." ) UpperCAmelCase__ = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
26
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase_ ( lowercase , lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = StableDiffusionInpaintPipeline __snake_case = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS __snake_case = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __snake_case = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __snake_case = frozenset([] ) def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" torch.manual_seed(0 ) a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , 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=__UpperCAmelCase , ) a = PNDMScheduler(skip_prk_steps=__UpperCAmelCase ) torch.manual_seed(0 ) a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act='''gelu''' , projection_dim=512 , ) a = CLIPTextModel(__UpperCAmelCase ) a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) a = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Dict=0 ) ->List[Any]: """simple docstring""" a = floats_tensor((1, 3, 32, 32) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) a = image.cpu().permute(0 , 2 , 3 , 1 )[0] a = Image.fromarray(np.uinta(__UpperCAmelCase ) ).convert('''RGB''' ).resize((64, 64) ) a = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((64, 64) ) if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': init_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionInpaintPipeline(**__UpperCAmelCase ) a = sd_pipe.to(__UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_dummy_inputs(__UpperCAmelCase ) a = sd_pipe(**__UpperCAmelCase ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench.npy''' ) a = '''stabilityai/stable-diffusion-2-inpainting''' a = StableDiffusionInpaintPipeline.from_pretrained(__UpperCAmelCase , safety_checker=__UpperCAmelCase ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing() a = '''Face of a yellow cat, high resolution, sitting on a park bench''' a = torch.manual_seed(0 ) a = pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , mask_image=__UpperCAmelCase , generator=__UpperCAmelCase , output_type='''np''' , ) a = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9e-3 def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' ) a = '''stabilityai/stable-diffusion-2-inpainting''' a = StableDiffusionInpaintPipeline.from_pretrained( __UpperCAmelCase , torch_dtype=torch.floataa , safety_checker=__UpperCAmelCase , ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing() a = '''Face of a yellow cat, high resolution, sitting on a park bench''' a = torch.manual_seed(0 ) a = pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , mask_image=__UpperCAmelCase , generator=__UpperCAmelCase , output_type='''np''' , ) a = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5e-1 def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) a = '''stabilityai/stable-diffusion-2-inpainting''' a = PNDMScheduler.from_pretrained(__UpperCAmelCase , subfolder='''scheduler''' ) a = StableDiffusionInpaintPipeline.from_pretrained( __UpperCAmelCase , safety_checker=__UpperCAmelCase , scheduler=__UpperCAmelCase , torch_dtype=torch.floataa , ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() a = '''Face of a yellow cat, high resolution, sitting on a park bench''' a = torch.manual_seed(0 ) a = pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , mask_image=__UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=2 , output_type='''np''' , ) a = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
354
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase__ = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTBigCodeForSequenceClassification", "GPTBigCodeForTokenClassification", "GPTBigCodeForCausalLM", "GPTBigCodeModel", "GPTBigCodePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
0
import unittest import numpy as np def _a ( a :np.ndarray , a :np.ndarray , a :np.ndarray , a :np.ndarray | None = None , ) -> np.ndarray: a = np.shape(a ) a = np.shape(a ) a = np.shape(a ) if shape_a[0] != shape_b[0]: a = ( '''Expected the same number of rows for A and B. ''' F"""Instead found A of size {shape_a} and B of size {shape_b}""" ) raise ValueError(a ) if shape_b[1] != shape_c[1]: a = ( '''Expected the same number of columns for B and C. ''' F"""Instead found B of size {shape_b} and C of size {shape_c}""" ) raise ValueError(a ) a = pseudo_inv if a_inv is None: try: a = np.linalg.inv(a ) except np.linalg.LinAlgError: raise ValueError( '''Input matrix A is not invertible. Cannot compute Schur complement.''' ) return mat_c - mat_b.T @ a_inv @ mat_b class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Dict ) ->None: """simple docstring""" a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) a = np.array([[0, 3], [3, 0], [2, 3]] ) a = np.array([[2, 1], [6, 3]] ) a = schur_complement(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = np.block([[a, b], [b.T, c]] ) a = np.linalg.det(__UpperCAmelCase ) a = np.linalg.det(__UpperCAmelCase ) a = np.linalg.det(__UpperCAmelCase ) self.assertAlmostEqual(__UpperCAmelCase , det_a * det_s ) def __lowerCAmelCase ( self : Union[str, Any] ) ->None: """simple docstring""" a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) a = np.array([[0, 3], [3, 0], [2, 3]] ) a = np.array([[2, 1], [6, 3]] ) with self.assertRaises(__UpperCAmelCase ): schur_complement(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->None: """simple docstring""" a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) a = np.array([[0, 3], [3, 0], [2, 3]] ) a = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(__UpperCAmelCase ): schur_complement(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
355
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def _a ( a :Tuple ) -> int: a = tmp_path / '''file.csv''' a = textwrap.dedent( '''\ header1,header2 1,2 10,20 ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :int ) -> List[str]: a = tmp_path / '''malformed_file.csv''' a = textwrap.dedent( '''\ header1,header2 1,2 10,20, ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :Dict , a :int ) -> List[str]: a = tmp_path / '''csv_with_image.csv''' a = textwrap.dedent( F"""\ image {image_file} """ ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :List[Any] ) -> Dict: a = tmp_path / '''csv_with_label.csv''' a = textwrap.dedent( '''\ label good bad good ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) @pytest.fixture def _a ( a :Tuple ) -> Any: a = tmp_path / '''csv_with_int_list.csv''' a = textwrap.dedent( '''\ int_list 1 2 3 4 5 6 7 8 9 ''' ) with open(a , '''w''' ) as f: f.write(a ) return str(a ) def _a ( a :Dict , a :int , a :Union[str, Any] ) -> List[Any]: a = Csv() a = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(a , match='''Error tokenizing data''' ): for _ in generator: pass assert any( record.levelname == '''ERROR''' and '''Failed to read file''' in record.message and os.path.basename(a ) in record.message for record in caplog.records ) @require_pil def _a ( a :Dict ) -> Any: with open(a , encoding='''utf-8''' ) as f: a = f.read().splitlines()[1] a = Csv(encoding='''utf-8''' , features=Features({'''image''': Image()} ) ) a = csv._generate_tables([[csv_file_with_image]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''image''' ).type == Image()() a = pa_table.to_pydict()['''image'''] assert generated_content == [{"path": image_file, "bytes": None}] def _a ( a :Any ) -> Tuple: with open(a , encoding='''utf-8''' ) as f: a = f.read().splitlines()[1:] a = Csv(encoding='''utf-8''' , features=Features({'''label''': ClassLabel(names=['''good''', '''bad'''] )} ) ) a = csv._generate_tables([[csv_file_with_label]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('''label''' ).type == ClassLabel(names=['''good''', '''bad'''] )() a = pa_table.to_pydict()['''label'''] assert generated_content == [ClassLabel(names=['''good''', '''bad'''] ).straint(a ) for label in labels] def _a ( a :Union[str, Any] ) -> Optional[Any]: a = Csv(encoding='''utf-8''' , sep=''',''' , converters={'''int_list''': lambda a : [int(a ) for i in x.split()]} ) a = csv._generate_tables([[csv_file_with_int_list]] ) a = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('''int_list''' ).type ) a = pa_table.to_pydict()['''int_list'''] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
26
0
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''output_type''', '''return_dict''', '''callback''', '''callback_steps''', ] ) @property def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" a = UNetaDModel.from_pretrained( '''diffusers/consistency-models-test''' , subfolder='''test_unet''' , ) return unet @property def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = UNetaDModel.from_pretrained( '''diffusers/consistency-models-test''' , subfolder='''test_unet_class_cond''' , ) return unet def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Optional[Any]=False ) ->List[Any]: """simple docstring""" if class_cond: a = self.dummy_cond_unet else: a = self.dummy_uncond_unet # Default to CM multistep sampler a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) a = { '''unet''': unet, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : str , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[Any]=0 ) ->Union[str, Any]: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''batch_size''': 1, '''num_inference_steps''': None, '''timesteps''': [22, 0], '''generator''': generator, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = ConsistencyModelPipeline(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_dummy_inputs(__UpperCAmelCase ) a = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 32, 32, 3) a = image[0, -3:, -3:, -1] a = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components(class_cond=__UpperCAmelCase ) a = ConsistencyModelPipeline(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_dummy_inputs(__UpperCAmelCase ) a = 0 a = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 32, 32, 3) a = image[0, -3:, -3:, -1] a = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = ConsistencyModelPipeline(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_dummy_inputs(__UpperCAmelCase ) a = 1 a = None a = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 32, 32, 3) a = image[0, -3:, -3:, -1] a = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components(class_cond=__UpperCAmelCase ) a = ConsistencyModelPipeline(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_dummy_inputs(__UpperCAmelCase ) a = 1 a = None a = 0 a = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 32, 32, 3) a = image[0, -3:, -3:, -1] a = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Union[str, Any] ) ->Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Dict=0 , __UpperCAmelCase : Union[str, Any]=False , __UpperCAmelCase : Dict="cpu" , __UpperCAmelCase : str=torch.floataa , __UpperCAmelCase : List[Any]=(1, 3, 64, 64) ) ->List[str]: """simple docstring""" a = torch.manual_seed(__UpperCAmelCase ) a = { '''num_inference_steps''': None, '''timesteps''': [22, 0], '''class_labels''': 0, '''generator''': generator, '''output_type''': '''np''', } if get_fixed_latents: a = self.get_fixed_latents(seed=__UpperCAmelCase , device=__UpperCAmelCase , dtype=__UpperCAmelCase , shape=__UpperCAmelCase ) a = latents return inputs def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[str]=0 , __UpperCAmelCase : List[str]="cpu" , __UpperCAmelCase : Optional[int]=torch.floataa , __UpperCAmelCase : Tuple=(1, 3, 64, 64) ) ->List[Any]: """simple docstring""" if type(__UpperCAmelCase ) == str: a = torch.device(__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = randn_tensor(__UpperCAmelCase , generator=__UpperCAmelCase , device=__UpperCAmelCase , dtype=__UpperCAmelCase ) return latents def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" a = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) a = ConsistencyModelPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) pipe.to(torch_device=__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_inputs() a = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 64, 64, 3) a = image[0, -3:, -3:, -1] a = np.array([0.0888, 0.0881, 0.0666, 0.0479, 0.0292, 0.0195, 0.0201, 0.0163, 0.0254] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def __lowerCAmelCase ( self : Dict ) ->List[Any]: """simple docstring""" a = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) a = ConsistencyModelPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) pipe.to(torch_device=__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_inputs() a = 1 a = None a = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 64, 64, 3) a = image[0, -3:, -3:, -1] a = np.array([0.0340, 0.0152, 0.0063, 0.0267, 0.0221, 0.0107, 0.0416, 0.0186, 0.0217] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def __lowerCAmelCase ( self : Dict ) ->Dict: """simple docstring""" a = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) a = ConsistencyModelPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) pipe.to(torch_device=__UpperCAmelCase , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_inputs(get_fixed_latents=__UpperCAmelCase , device=__UpperCAmelCase ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__UpperCAmelCase , enable_math=__UpperCAmelCase , enable_mem_efficient=__UpperCAmelCase ): a = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 64, 64, 3) a = image[0, -3:, -3:, -1] a = np.array([0.1875, 0.1428, 0.1289, 0.2151, 0.2092, 0.1477, 0.1877, 0.1641, 0.1353] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def __lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" a = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' ) a = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) a = ConsistencyModelPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) pipe.to(torch_device=__UpperCAmelCase , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = self.get_inputs(get_fixed_latents=__UpperCAmelCase , device=__UpperCAmelCase ) a = 1 a = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=__UpperCAmelCase , enable_math=__UpperCAmelCase , enable_mem_efficient=__UpperCAmelCase ): a = pipe(**__UpperCAmelCase ).images assert image.shape == (1, 64, 64, 3) a = image[0, -3:, -3:, -1] a = np.array([0.1663, 0.1948, 0.2275, 0.1680, 0.1204, 0.1245, 0.1858, 0.1338, 0.2095] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
356
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = torch.device("cpu") def _a ( ) -> Union[str, Any]: a = '''http://images.cocodataset.org/val2017/000000039769.jpg''' a = Image.open(requests.get(a , stream=a ).raw ) return im def _a ( a :Dict ) -> Tuple: if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1703e00, 2.1107e00, -2.0811e00, 8.8685e-01, 2.4360e-01] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9636e-01, 2.3478e-01, -1.6963e00, -1.7381e00, -8.6337e-01] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2768e-01, -4.7429e-01, -1.0897e00, -1.0248e00, 3.5523e-02] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5330e-01, 2.4211e-01, -6.0185e-01, -8.2789e-01, -6.0446e-02] ) def _a ( a :int , a :Any , a :Union[str, Any] ) -> int: a = dct.pop(a ) a = val def _a ( a :Any ) -> Dict: a = [] for k in state_dict.keys(): a = k if ".pwconv" in k: a = k_new.replace('''.pwconv''' , '''.point_wise_conv''' ) if ".dwconv" in k: a = k_new.replace('''.dwconv''' , '''.depth_wise_conv''' ) if ".Proj." in k: a = k_new.replace('''.Proj.''' , '''.proj.''' ) if "patch_embed" in k_new: a = k_new.replace('''patch_embed''' , '''swiftformer.patch_embed.patch_embedding''' ) if "network" in k_new: a = k_new.split('''.''' ) if ls[2].isdigit(): a = '''swiftformer.encoder.network.''' + ls[1] + '''.blocks.''' + ls[2] + '''.''' + '''.'''.join(ls[3:] ) else: a = k_new.replace('''network''' , '''swiftformer.encoder.network''' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def _a ( a :List[Any] , a :Tuple , a :List[str] ) -> Union[str, Any]: a = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size a = 1_000 a = '''huggingface/label-files''' a = '''imagenet-1k-id2label.json''' a = json.load(open(hf_hub_download(a , a , repo_type='''dataset''' ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": a = [3, 3, 6, 4] a = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": a = [3, 3, 9, 6] a = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": a = [4, 3, 10, 5] a = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": a = [4, 4, 12, 6] a = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('''https''' ): a = torch.hub.load_state_dict_from_url(a , map_location='''cpu''' , check_hash=a ) else: a = torch.load(a , map_location='''cpu''' ) a = checkpoint a = create_rename_keys(a ) for rename_key_src, rename_key_dest in rename_keys: rename_key(a , a , a ) # load HuggingFace model a = SwiftFormerForImageClassification(a ).eval() hf_model.load_state_dict(a ) # prepare test inputs a = prepare_img() a = ViTImageProcessor.from_pretrained('''preprocessor_config''' ) a = processor(images=a , return_tensors='''pt''' ) # compare outputs from both models a = get_expected_output(a ) a = hf_model(inputs['''pixel_values'''] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , a , atol=1e-3 ) Path(a ).mkdir(exist_ok=a ) print(F"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" ) hf_model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swiftformer_name", default="swiftformer_xs", choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"], type=str, help="Name of the SwiftFormer model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default="./converted_outputs/", type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.") UpperCAmelCase__ = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
26
0
from math import asin, atan, cos, radians, sin, sqrt, tan UpperCAmelCase__ = 6378137.0 UpperCAmelCase__ = 6356752.314245 UpperCAmelCase__ = 6378137 def _a ( a :float , a :float , a :float , a :float ) -> float: a = (AXIS_A - AXIS_B) / AXIS_A a = atan((1 - flattening) * tan(radians(a ) ) ) a = atan((1 - flattening) * tan(radians(a ) ) ) a = radians(a ) a = radians(a ) # Equation a = sin((phi_a - phi_a) / 2 ) a = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda a = sqrt(sin_sq_phi + (cos(a ) * cos(a ) * sin_sq_lambda) ) return 2 * RADIUS * asin(a ) if __name__ == "__main__": import doctest doctest.testmod()
357
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : DDPMScheduler , __UpperCAmelCase : Optional[int] , ) ->List[str]: """simple docstring""" super().__init__() a = value_function a = unet a = scheduler a = env a = env.get_dataset() a = {} for key in self.data.keys(): try: a = self.data[key].mean() except: # noqa: E722 pass a = {} for key in self.data.keys(): try: a = self.data[key].std() except: # noqa: E722 pass a = env.observation_space.shape[0] a = env.action_space.shape[0] def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] ) ->Dict: """simple docstring""" return (x_in - self.means[key]) / self.stds[key] def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict ) ->List[str]: """simple docstring""" return x_in * self.stds[key] + self.means[key] def __lowerCAmelCase ( self : int , __UpperCAmelCase : int ) ->List[str]: """simple docstring""" if type(__UpperCAmelCase ) is dict: return {k: self.to_torch(__UpperCAmelCase ) for k, v in x_in.items()} elif torch.is_tensor(__UpperCAmelCase ): return x_in.to(self.unet.device ) return torch.tensor(__UpperCAmelCase , device=self.unet.device ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple ) ->int: """simple docstring""" for key, val in cond.items(): a = val.clone() return x_in def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = x.shape[0] a = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model a = torch.full((batch_size,) , __UpperCAmelCase , device=self.unet.device , dtype=torch.long ) for _ in range(__UpperCAmelCase ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models a = self.value_function(x.permute(0 , 2 , 1 ) , __UpperCAmelCase ).sample a = torch.autograd.grad([y.sum()] , [x] )[0] a = self.scheduler._get_variance(__UpperCAmelCase ) a = torch.exp(0.5 * posterior_variance ) a = model_std * grad a = 0 a = x.detach() a = x + scale * grad a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.unet(x.permute(0 , 2 , 1 ) , __UpperCAmelCase ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg a = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , predict_epsilon=__UpperCAmelCase )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.to_torch(__UpperCAmelCase ) return x, y def __call__( self : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int]=64 , __UpperCAmelCase : int=32 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : str=0.1 ) ->List[str]: """simple docstring""" a = self.normalize(__UpperCAmelCase , '''observations''' ) a = obs[None].repeat(__UpperCAmelCase , axis=0 ) a = {0: self.to_torch(__UpperCAmelCase )} a = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) a = randn_tensor(__UpperCAmelCase , device=self.unet.device ) a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.to_torch(__UpperCAmelCase ) # run the diffusion process a , a = self.run_diffusion(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # sort output trajectories by value a = y.argsort(0 , descending=__UpperCAmelCase ).squeeze() a = x[sorted_idx] a = sorted_values[:, :, : self.action_dim] a = actions.detach().cpu().numpy() a = self.de_normalize(__UpperCAmelCase , key='''actions''' ) # select the action with the highest value if y is not None: a = 0 else: # if we didn't run value guiding, select a random action a = np.random.randint(0 , __UpperCAmelCase ) a = denorm_actions[selected_index, 0] return denorm_actions
26
0
import torch def _a ( ) -> str: if torch.cuda.is_available(): a = torch.cuda.device_count() else: a = 0 print(F"""Successfully ran on {num_gpus} GPUs""" ) if __name__ == "__main__": main()
358
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 UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "spiece.model"} UpperCAmelCase__ = { "vocab_file": { "TsinghuaAI/CPM-Generate": "https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model", } } class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Any=True , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : List[str]="<s>" , __UpperCAmelCase : int="</s>" , __UpperCAmelCase : Any="<unk>" , __UpperCAmelCase : Optional[Any]="<sep>" , __UpperCAmelCase : int="<pad>" , __UpperCAmelCase : Any="<cls>" , __UpperCAmelCase : List[str]="<mask>" , __UpperCAmelCase : Optional[int]=["<eop>", "<eod>"] , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : Union[str, Any] , ) ->None: """simple docstring""" a = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) a = 3 a = do_lower_case a = remove_space a = keep_accents a = vocab_file a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) a = jieba a = str.maketrans(''' \n''' , '''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" return len(self.sp_model ) def __lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" a = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = self.__dict__.copy() a = None return state def __setstate__( self : List[str] , __UpperCAmelCase : Optional[int] ) ->str: """simple docstring""" a = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a = {} a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] ) ->List[str]: """simple docstring""" if self.remove_space: a = ''' '''.join(inputs.strip().split() ) else: a = inputs a = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: a = unicodedata.normalize('''NFKD''' , __UpperCAmelCase ) a = ''''''.join([c for c in outputs if not unicodedata.combining(__UpperCAmelCase )] ) if self.do_lower_case: a = outputs.lower() return outputs def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = self.preprocess_text(__UpperCAmelCase ) a = self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) a = [] for piece in pieces: if len(__UpperCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): a = self.sp_model.EncodeAsPieces(piece[:-1].replace(__UpperCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: a = cur_pieces[1:] else: a = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__UpperCAmelCase ) else: new_pieces.append(__UpperCAmelCase ) return new_pieces def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Any ) ->Any: """simple docstring""" return self.sp_model.PieceToId(__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Dict ) ->Union[str, Any]: """simple docstring""" return self.sp_model.IdToPiece(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" a = ''''''.join(__UpperCAmelCase ).replace(__UpperCAmelCase , ''' ''' ).strip() return out_string def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase , token_ids_a=__UpperCAmelCase , already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is not None: return ([0] * len(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] return ([0] * len(__UpperCAmelCase )) + [1, 1] def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a = os.path.join( __UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase , '''wb''' ) as fi: a = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,) def __lowerCAmelCase ( self : Any , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = super()._decode(*__UpperCAmelCase , **__UpperCAmelCase ) a = text.replace(''' ''' , '''''' ).replace('''\u2582''' , ''' ''' ).replace('''\u2583''' , '''\n''' ) return text
26
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ShapEImgaImgPipeline __snake_case = ['''image'''] __snake_case = ['''image'''] __snake_case = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" return 8 @property def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" torch.manual_seed(0 ) a = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) a = CLIPVisionModel(__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" a = CLIPImageProcessor( crop_size=224 , do_center_crop=__UpperCAmelCase , do_normalize=__UpperCAmelCase , do_resize=__UpperCAmelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def __lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" torch.manual_seed(0 ) a = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } a = PriorTransformer(**__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" torch.manual_seed(0 ) a = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } a = ShapERenderer(**__UpperCAmelCase ) return model def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" a = self.dummy_prior a = self.dummy_image_encoder a = self.dummy_image_processor a = self.dummy_renderer a = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_024 , prediction_type='''sample''' , use_karras_sigmas=__UpperCAmelCase , clip_sample=__UpperCAmelCase , clip_sample_range=1.0 , ) a = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict=0 ) ->Union[str, Any]: """simple docstring""" a = floats_tensor((1, 3, 64, 64) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase ) if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.images[0] a = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = torch_device == '''cpu''' a = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = 1 a = 2 a = self.get_dummy_inputs(__UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: a = batch_size * [inputs[key]] a = pipe(**__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) a = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) a = pipe( __UpperCAmelCase , generator=__UpperCAmelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
359
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def _a ( a :Union[str, Any] , a :List[Any] ) -> List[Any]: a = checkpoint a = {} a = vae_state_dict['''encoder.conv_in.weight'''] a = vae_state_dict['''encoder.conv_in.bias'''] a = vae_state_dict['''encoder.conv_out.weight'''] a = vae_state_dict['''encoder.conv_out.bias'''] a = vae_state_dict['''encoder.norm_out.weight'''] a = vae_state_dict['''encoder.norm_out.bias'''] a = vae_state_dict['''decoder.conv_in.weight'''] a = vae_state_dict['''decoder.conv_in.bias'''] a = vae_state_dict['''decoder.conv_out.weight'''] a = vae_state_dict['''decoder.conv_out.bias'''] a = vae_state_dict['''decoder.norm_out.weight'''] a = vae_state_dict['''decoder.norm_out.bias'''] a = vae_state_dict['''quant_conv.weight'''] a = vae_state_dict['''quant_conv.bias'''] a = vae_state_dict['''post_quant_conv.weight'''] a = vae_state_dict['''post_quant_conv.bias'''] # Retrieves the keys for the encoder down blocks only a = len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''encoder.down''' in layer} ) a = { layer_id: [key for key in vae_state_dict if F"""down.{layer_id}""" in key] for layer_id in range(a ) } # Retrieves the keys for the decoder up blocks only a = len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''decoder.up''' in layer} ) a = { layer_id: [key for key in vae_state_dict if F"""up.{layer_id}""" in key] for layer_id in range(a ) } for i in range(a ): a = [key for key in down_blocks[i] if F"""down.{i}""" in key and F"""down.{i}.downsample""" not in key] if F"""encoder.down.{i}.downsample.conv.weight""" in vae_state_dict: a = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.weight""" ) a = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.bias""" ) a = renew_vae_resnet_paths(a ) a = {'''old''': F"""down.{i}.block""", '''new''': F"""down_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''encoder.mid.block''' in key] a = 2 for i in range(1 , num_mid_res_blocks + 1 ): a = [key for key in mid_resnets if F"""encoder.mid.block_{i}""" in key] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""mid.block_{i}""", '''new''': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''encoder.mid.attn''' in key] a = renew_vae_attention_paths(a ) a = {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) for i in range(a ): a = num_up_blocks - 1 - i a = [ key for key in up_blocks[block_id] if F"""up.{block_id}""" in key and F"""up.{block_id}.upsample""" not in key ] if F"""decoder.up.{block_id}.upsample.conv.weight""" in vae_state_dict: a = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.weight""" ] a = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.bias""" ] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""up.{block_id}.block""", '''new''': F"""up_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''decoder.mid.block''' in key] a = 2 for i in range(1 , num_mid_res_blocks + 1 ): a = [key for key in mid_resnets if F"""decoder.mid.block_{i}""" in key] a = renew_vae_resnet_paths(a ) a = {'''old''': F"""mid.block_{i}""", '''new''': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) a = [key for key in vae_state_dict if '''decoder.mid.attn''' in key] a = renew_vae_attention_paths(a ) a = {'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) return new_checkpoint def _a ( a :str , a :str , ) -> List[str]: # Only support V1 a = requests.get( ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml''' ) a = io.BytesIO(r.content ) a = OmegaConf.load(a ) a = 512 a = '''cuda''' if torch.cuda.is_available() else '''cpu''' if checkpoint_path.endswith('''safetensors''' ): from safetensors import safe_open a = {} with safe_open(a , framework='''pt''' , device='''cpu''' ) as f: for key in f.keys(): a = f.get_tensor(a ) else: a = torch.load(a , map_location=a )['''state_dict'''] # Convert the VAE model. a = create_vae_diffusers_config(a , image_size=a ) a = custom_convert_ldm_vae_checkpoint(a , a ) a = AutoencoderKL(**a ) vae.load_state_dict(a ) vae.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--vae_pt_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") UpperCAmelCase__ = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
26
0
def _a ( a :str ) -> list: if n_term == "": return [] a = [] for temp in range(int(a ) ): series.append(F"""1/{temp + 1}""" if series else '''1''' ) return series if __name__ == "__main__": UpperCAmelCase__ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
360
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''image_processor''', '''tokenizer'''] __snake_case = '''CLIPImageProcessor''' __snake_case = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Dict , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : Optional[Any] ) ->List[str]: """simple docstring""" a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __UpperCAmelCase , ) a = kwargs.pop('''feature_extractor''' ) a = 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__(__UpperCAmelCase , __UpperCAmelCase ) def __call__( self : List[str] , __UpperCAmelCase : Any=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Any=None , **__UpperCAmelCase : str ) ->Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: a = self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if images is not None: a = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is not None and images is not None: a = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__UpperCAmelCase ) , tensor_type=__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : str , **__UpperCAmelCase : Tuple ) ->Any: """simple docstring""" return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a = self.tokenizer.model_input_names a = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __UpperCAmelCase , ) return self.image_processor_class @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __UpperCAmelCase , ) return self.image_processor
26
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
361
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } UpperCAmelCase__ = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } UpperCAmelCase__ = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = ['''input_ids''', '''attention_mask'''] __snake_case = DistilBertTokenizer def __init__( self : Dict , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[int]="[UNK]" , __UpperCAmelCase : str="[SEP]" , __UpperCAmelCase : Tuple="[PAD]" , __UpperCAmelCase : Any="[CLS]" , __UpperCAmelCase : int="[MASK]" , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : str , ) ->Optional[int]: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int]=None ) ->Optional[Any]: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
26
0
import random def _a ( a :int ) -> bool: a = num - 1 a = 0 while s % 2 == 0: a = s // 2 t += 1 for _ in range(5 ): a = random.randrange(2 , num - 1 ) a = pow(a , a , a ) if v != 1: a = 0 while v != (num - 1): if i == t - 1: return False else: a = i + 1 a = (v**2) % num return True def _a ( a :int ) -> bool: if num < 2: return False a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(a ) def _a ( a :int = 1_024 ) -> int: while True: a = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(a ): return num if __name__ == "__main__": UpperCAmelCase__ = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
362
from __future__ import annotations import typing from collections import Counter def _a ( a :int ) -> typing.Counter[int]: a = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(a , max_perimeter + 1 ): a = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(a ): a = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _a ( a :int = 1_000 ) -> int: a = pythagorean_triple(a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f"""Perimeter {solution()} has maximum solutions""")
26
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPTextConfig", "XCLIPVisionConfig", ], "processing_x_clip": ["XCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "XCLIPModel", "XCLIPPreTrainedModel", "XCLIPTextModel", "XCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
363
from __future__ import annotations def _a ( a :dict , a :str ) -> set[str]: a , a = set(a ), [start] while stack: a = stack.pop() explored.add(a ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a ) return explored UpperCAmelCase__ = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, "A"))
26
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } UpperCAmelCase__ = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } UpperCAmelCase__ = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = ['''input_ids''', '''attention_mask'''] __snake_case = DistilBertTokenizer def __init__( self : Dict , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[int]="[UNK]" , __UpperCAmelCase : str="[SEP]" , __UpperCAmelCase : Tuple="[PAD]" , __UpperCAmelCase : Any="[CLS]" , __UpperCAmelCase : int="[MASK]" , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : str , ) ->Optional[int]: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int]=None ) ->Optional[Any]: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
364
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase__ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex UpperCAmelCase__ = 10 UpperCAmelCase__ = 256 def _a ( a :List[str] ) -> Optional[MinHash]: if len(a ) < MIN_NUM_TOKENS: return None a = MinHash(num_perm=a ) for token in set(a ): min_hash.update(token.encode() ) return min_hash def _a ( a :str ) -> Set[str]: return {t for t in NON_ALPHA.split(a ) if len(t.strip() ) > 0} class lowercase_ : '''simple docstring''' def __init__( self : Any , *, __UpperCAmelCase : float = 0.85 , ) ->Dict: """simple docstring""" a = duplication_jaccard_threshold a = NUM_PERM a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) a = defaultdict(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : MinHash ) ->None: """simple docstring""" a = self._index.query(__UpperCAmelCase ) if code_key in self._index.keys: print(F"""Duplicate key {code_key}""" ) return self._index.insert(__UpperCAmelCase , __UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__UpperCAmelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->List[List[Dict]]: """simple docstring""" a = [] for base, duplicates in self._duplicate_clusters.items(): a = [base] + list(__UpperCAmelCase ) # reformat the cluster to be a list of dict a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(__UpperCAmelCase ) return duplicate_clusters def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Dict ) ->None: """simple docstring""" a = self.get_duplicate_clusters() with open(__UpperCAmelCase , '''w''' ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def _a ( a :List[Any] ) -> List[Any]: a , a = element a = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _a ( a :Type[Dataset] ) -> List[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(a , max_queue_size=10_000 ) , chunksize=100 , ): if data is not None: yield data def _a ( a :Type[Dataset] , a :float ) -> str: a = DuplicationIndex(duplication_jaccard_threshold=a ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a ) ) , max_queue_size=100 ) ): di.add(a , a ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _a ( a :str , a :str ) -> float: a = get_tokens(a ) a = get_tokens(a ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase__ = None def _a ( a :Tuple , a :Tuple ) -> Any: a = [] for elementa in cluster: a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(a , a ) >= jaccard_threshold: elementa["copies"] += 1 break else: a = 1 extremes.append(a ) return extremes def _a ( a :List[Any] , a :Optional[Any] , a :Union[str, Any] ) -> Optional[int]: global _shared_dataset a = dataset a = [] a = partial(_find_cluster_extremes_shared , jaccard_threshold=a ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( a , a , ) , total=len(a ) , ): extremes_list.append(a ) return extremes_list def _a ( a :Type[Dataset] , a :float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: a = make_duplicate_clusters(a , a ) a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} a = {} a = find_extremes(a , a , a ) for extremes in extremes_clusters: for element in extremes: a = element a = duplicate_indices - set(extreme_dict.keys() ) a = dataset.filter(lambda a , a : idx not in remove_indices , with_indices=a ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: a = element['''base_index'''] in extreme_dict if element["is_extreme"]: a = extreme_dict[element['''base_index''']]['''copies'''] print(F"""Original dataset size: {len(a )}""" ) print(F"""Number of duplicate clusters: {len(a )}""" ) print(F"""Files in duplicate cluster: {len(a )}""" ) print(F"""Unique files in duplicate cluster: {len(a )}""" ) print(F"""Filtered dataset size: {len(a )}""" ) return ds_filter, duplicate_clusters
26
0
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ = "▁" UpperCAmelCase__ = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = BertGenerationTokenizer __snake_case = False __snake_case = True def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" super().setUp() a = BertGenerationTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = '''<s>''' a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(__UpperCAmelCase ) , 1_002 ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def __lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" a = BertGenerationTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) a = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__UpperCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [285, 46, 10, 170, 382] , ) a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) a = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) a = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" return BertGenerationTokenizer.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''' ) @slow def __lowerCAmelCase ( self : Any ) ->str: """simple docstring""" a = '''Hello World!''' a = [18_536, 2_260, 101] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) a = [ 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, ] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @require_torch @slow def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence a = list(self.big_tokenizer.get_vocab().keys() )[:10] a = ''' '''.join(__UpperCAmelCase ) a = self.big_tokenizer.encode_plus(__UpperCAmelCase , return_tensors='''pt''' , return_token_type_ids=__UpperCAmelCase ) a = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=__UpperCAmelCase ) a = BertGenerationConfig() a = BertGenerationEncoder(__UpperCAmelCase ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__UpperCAmelCase ) model(**__UpperCAmelCase ) @slow def __lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" a = {'''input_ids''': [[39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114], [448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='''google/bert_for_seq_generation_L-24_bbc_encoder''' , revision='''c817d1fd1be2ffa69431227a1fe320544943d4db''' , )
365
from math import ceil, sqrt def _a ( a :int = 1_000_000 ) -> int: a = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: a = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
26
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision 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 LevitImageProcessor class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Dict=7 , __UpperCAmelCase : Optional[Any]=3 , __UpperCAmelCase : Union[str, Any]=18 , __UpperCAmelCase : Any=30 , __UpperCAmelCase : Optional[int]=400 , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Tuple=None , __UpperCAmelCase : str=True , __UpperCAmelCase : Any=[0.5, 0.5, 0.5] , __UpperCAmelCase : Union[str, Any]=[0.5, 0.5, 0.5] , ) ->int: """simple docstring""" a = size if size is not None else {'''shortest_edge''': 18} a = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} a = parent a = batch_size a = num_channels a = image_size a = min_resolution a = max_resolution a = do_resize a = size a = do_center_crop a = crop_size a = do_normalize a = image_mean a = image_std def __lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = LevitImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = LevitImageProcessingTester(self ) @property def __lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : Optional[Any] ) ->Optional[int]: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , '''image_mean''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''image_std''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_resize''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_center_crop''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''size''' ) ) def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) a = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" pass def __lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input a = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched a = image_processing(__UpperCAmelCase , 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def __lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input a = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched a = image_processing(__UpperCAmelCase , 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input a = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched a = image_processing(__UpperCAmelCase , 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
366
UpperCAmelCase__ = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
26
0
import enum import shutil import sys UpperCAmelCase__ , UpperCAmelCase__ = shutil.get_terminal_size() UpperCAmelCase__ = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"} class lowercase_ ( enum.Enum ): '''simple docstring''' __snake_case = 0 __snake_case = 1 def _a ( a :Dict , a :Any="" ) -> str: sys.stdout.write(str(a ) + end ) sys.stdout.flush() def _a ( a :str , a :List[Any] , a :str="" ) -> Union[str, Any]: forceWrite(F"""\u001b[{color}m{content}\u001b[0m""" , a ) def _a ( ) -> Union[str, Any]: forceWrite('''\r''' ) def _a ( a :int , a :str ) -> List[Any]: forceWrite(F"""\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}""" ) def _a ( ) -> Any: forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def _a ( ) -> int: reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
367
def _a ( a :list ) -> list: if len(a ) <= 1: return lst a = 1 while i < len(a ): if lst[i - 1] <= lst[i]: i += 1 else: a , a = lst[i], lst[i - 1] i -= 1 if i == 0: a = 1 return lst if __name__ == "__main__": UpperCAmelCase__ = input("Enter numbers separated by a comma:\n").strip() UpperCAmelCase__ = [int(item) for item in user_input.split(",")] print(gnome_sort(unsorted))
26
0
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer UpperCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase__ = "\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n >>> repo = \"openai/shap-e-img2img\"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n >>> image = load_image(image_url).convert(\"RGB\")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n ```\n" @dataclass class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = 42 class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Dict , __UpperCAmelCase : PriorTransformer , __UpperCAmelCase : CLIPVisionModel , __UpperCAmelCase : CLIPImageProcessor , __UpperCAmelCase : HeunDiscreteScheduler , __UpperCAmelCase : ShapERenderer , ) ->List[Any]: """simple docstring""" super().__init__() self.register_modules( prior=__UpperCAmelCase , image_encoder=__UpperCAmelCase , image_processor=__UpperCAmelCase , scheduler=__UpperCAmelCase , renderer=__UpperCAmelCase , ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Union[str, Any] ) ->int: """simple docstring""" if latents is None: a = randn_tensor(__UpperCAmelCase , generator=__UpperCAmelCase , device=__UpperCAmelCase , dtype=__UpperCAmelCase ) else: if latents.shape != shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) a = latents.to(__UpperCAmelCase ) a = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : List[str]=0 ) ->Tuple: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a = torch.device(F"""cuda:{gpu_id}""" ) a = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__UpperCAmelCase , __UpperCAmelCase ) @property def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" if self.device != torch.device('''meta''' ) or not hasattr(self.image_encoder , '''_hf_hook''' ): return self.device for module in self.image_encoder.modules(): if ( hasattr(__UpperCAmelCase , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , ) ->str: """simple docstring""" if isinstance(__UpperCAmelCase , __UpperCAmelCase ) and isinstance(image[0] , torch.Tensor ): a = torch.cat(__UpperCAmelCase , axis=0 ) if image[0].ndim == 4 else torch.stack(__UpperCAmelCase , axis=0 ) if not isinstance(__UpperCAmelCase , torch.Tensor ): a = self.image_processor(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values[0].unsqueeze(0 ) a = image.to(dtype=self.image_encoder.dtype , device=__UpperCAmelCase ) a = self.image_encoder(__UpperCAmelCase )['''last_hidden_state'''] a = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 a = image_embeds.repeat_interleave(__UpperCAmelCase , dim=0 ) if do_classifier_free_guidance: a = torch.zeros_like(__UpperCAmelCase ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(__UpperCAmelCase ) def __call__( self : Optional[Any] , __UpperCAmelCase : Union[PIL.Image.Image, List[PIL.Image.Image]] , __UpperCAmelCase : int = 1 , __UpperCAmelCase : int = 25 , __UpperCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : float = 4.0 , __UpperCAmelCase : int = 64 , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , ) ->Dict: """simple docstring""" if isinstance(__UpperCAmelCase , PIL.Image.Image ): a = 1 elif isinstance(__UpperCAmelCase , torch.Tensor ): a = image.shape[0] elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): a = len(__UpperCAmelCase ) else: raise ValueError( F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__UpperCAmelCase )}""" ) a = self._execution_device a = batch_size * num_images_per_prompt a = guidance_scale > 1.0 a = self._encode_image(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # prior self.scheduler.set_timesteps(__UpperCAmelCase , device=__UpperCAmelCase ) a = self.scheduler.timesteps a = self.prior.config.num_embeddings a = self.prior.config.embedding_dim a = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim a = latents.reshape(latents.shape[0] , __UpperCAmelCase , __UpperCAmelCase ) for i, t in enumerate(self.progress_bar(__UpperCAmelCase ) ): # expand the latents if we are doing classifier free guidance a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a = self.scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) a = self.prior( __UpperCAmelCase , timestep=__UpperCAmelCase , proj_embedding=__UpperCAmelCase , ).predicted_image_embedding # remove the variance a , a = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: a , a = noise_pred.chunk(2 ) a = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) a = self.scheduler.step( __UpperCAmelCase , timestep=__UpperCAmelCase , sample=__UpperCAmelCase , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=__UpperCAmelCase ) a = [] for i, latent in enumerate(__UpperCAmelCase ): print() a = self.renderer.decode( latent[None, :] , __UpperCAmelCase , size=__UpperCAmelCase , ray_batch_size=4_096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(__UpperCAmelCase ) a = torch.stack(__UpperCAmelCase ) if output_type not in ["np", "pil"]: raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}""" ) a = images.cpu().numpy() if output_type == "pil": a = [self.numpy_to_pil(__UpperCAmelCase ) for image in images] # Offload last model to CPU if hasattr(self , '''final_offload_hook''' ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=__UpperCAmelCase )
368
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
26
0
# # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def _a ( *a :List[str] ) -> List[Any]: with open(a , '''r''' ) as fh: fcntl.flock(a , fcntl.LOCK_EX ) try: print(*a ) finally: fcntl.flock(a , fcntl.LOCK_UN ) UpperCAmelCase__ = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) UpperCAmelCase__ = torch.device("cuda", local_rank) UpperCAmelCase__ = socket.gethostname() UpperCAmelCase__ = f"""[{hostname}-{local_rank}]""" try: # test distributed dist.init_process_group("nccl") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank UpperCAmelCase__ = dist.get_rank() UpperCAmelCase__ = dist.get_world_size() printflock(f"""{gpu} is OK (global rank: {rank}/{world_size})""") dist.barrier() if rank == 0: printflock(f"""pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}""") except Exception: printflock(f"""{gpu} is broken""") raise
369
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = OrderedDict( [ ("audio-spectrogram-transformer", "ASTFeatureExtractor"), ("beit", "BeitFeatureExtractor"), ("chinese_clip", "ChineseCLIPFeatureExtractor"), ("clap", "ClapFeatureExtractor"), ("clip", "CLIPFeatureExtractor"), ("clipseg", "ViTFeatureExtractor"), ("conditional_detr", "ConditionalDetrFeatureExtractor"), ("convnext", "ConvNextFeatureExtractor"), ("cvt", "ConvNextFeatureExtractor"), ("data2vec-audio", "Wav2Vec2FeatureExtractor"), ("data2vec-vision", "BeitFeatureExtractor"), ("deformable_detr", "DeformableDetrFeatureExtractor"), ("deit", "DeiTFeatureExtractor"), ("detr", "DetrFeatureExtractor"), ("dinat", "ViTFeatureExtractor"), ("donut-swin", "DonutFeatureExtractor"), ("dpt", "DPTFeatureExtractor"), ("encodec", "EncodecFeatureExtractor"), ("flava", "FlavaFeatureExtractor"), ("glpn", "GLPNFeatureExtractor"), ("groupvit", "CLIPFeatureExtractor"), ("hubert", "Wav2Vec2FeatureExtractor"), ("imagegpt", "ImageGPTFeatureExtractor"), ("layoutlmv2", "LayoutLMv2FeatureExtractor"), ("layoutlmv3", "LayoutLMv3FeatureExtractor"), ("levit", "LevitFeatureExtractor"), ("maskformer", "MaskFormerFeatureExtractor"), ("mctct", "MCTCTFeatureExtractor"), ("mobilenet_v1", "MobileNetV1FeatureExtractor"), ("mobilenet_v2", "MobileNetV2FeatureExtractor"), ("mobilevit", "MobileViTFeatureExtractor"), ("nat", "ViTFeatureExtractor"), ("owlvit", "OwlViTFeatureExtractor"), ("perceiver", "PerceiverFeatureExtractor"), ("poolformer", "PoolFormerFeatureExtractor"), ("regnet", "ConvNextFeatureExtractor"), ("resnet", "ConvNextFeatureExtractor"), ("segformer", "SegformerFeatureExtractor"), ("sew", "Wav2Vec2FeatureExtractor"), ("sew-d", "Wav2Vec2FeatureExtractor"), ("speech_to_text", "Speech2TextFeatureExtractor"), ("speecht5", "SpeechT5FeatureExtractor"), ("swiftformer", "ViTFeatureExtractor"), ("swin", "ViTFeatureExtractor"), ("swinv2", "ViTFeatureExtractor"), ("table-transformer", "DetrFeatureExtractor"), ("timesformer", "VideoMAEFeatureExtractor"), ("tvlt", "TvltFeatureExtractor"), ("unispeech", "Wav2Vec2FeatureExtractor"), ("unispeech-sat", "Wav2Vec2FeatureExtractor"), ("van", "ConvNextFeatureExtractor"), ("videomae", "VideoMAEFeatureExtractor"), ("vilt", "ViltFeatureExtractor"), ("vit", "ViTFeatureExtractor"), ("vit_mae", "ViTFeatureExtractor"), ("vit_msn", "ViTFeatureExtractor"), ("wav2vec2", "Wav2Vec2FeatureExtractor"), ("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"), ("wavlm", "Wav2Vec2FeatureExtractor"), ("whisper", "WhisperFeatureExtractor"), ("xclip", "CLIPFeatureExtractor"), ("yolos", "YolosFeatureExtractor"), ] ) UpperCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _a ( a :str ) -> Any: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: a = model_type_to_module_name(a ) a = importlib.import_module(F""".{module_name}""" , '''transformers.models''' ) try: return getattr(a , a ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(a , '''__name__''' , a ) == 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. a = importlib.import_module('''transformers''' ) if hasattr(a , a ): return getattr(a , a ) return None def _a ( a :Union[str, os.PathLike] , a :Optional[Union[str, os.PathLike]] = None , a :bool = False , a :bool = False , a :Optional[Dict[str, str]] = None , a :Optional[Union[bool, str]] = None , a :Optional[str] = None , a :bool = False , **a :int , ) -> Tuple: a = get_file_from_repo( a , a , cache_dir=a , force_download=a , resume_download=a , proxies=a , use_auth_token=a , revision=a , local_files_only=a , ) 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(a , encoding='''utf-8''' ) as reader: return json.load(a ) class lowercase_ : '''simple docstring''' def __init__( self : Tuple ) ->int: """simple docstring""" raise EnvironmentError( '''AutoFeatureExtractor is designed to be instantiated ''' '''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__UpperCAmelCase ) def __lowerCAmelCase ( cls : int , __UpperCAmelCase : Optional[Any] , **__UpperCAmelCase : Dict ) ->List[Any]: """simple docstring""" a = kwargs.pop('''config''' , __UpperCAmelCase ) a = kwargs.pop('''trust_remote_code''' , __UpperCAmelCase ) a = True a , a = FeatureExtractionMixin.get_feature_extractor_dict(__UpperCAmelCase , **__UpperCAmelCase ) a = config_dict.get('''feature_extractor_type''' , __UpperCAmelCase ) a = None if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a = 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(__UpperCAmelCase , __UpperCAmelCase ): a = AutoConfig.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) # It could be in `config.feature_extractor_type`` a = getattr(__UpperCAmelCase , '''feature_extractor_type''' , __UpperCAmelCase ) if hasattr(__UpperCAmelCase , '''auto_map''' ) and "AutoFeatureExtractor" in config.auto_map: a = config.auto_map['''AutoFeatureExtractor'''] if feature_extractor_class is not None: a = feature_extractor_class_from_name(__UpperCAmelCase ) a = feature_extractor_auto_map is not None a = feature_extractor_class is not None or type(__UpperCAmelCase ) in FEATURE_EXTRACTOR_MAPPING a = resolve_trust_remote_code( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if has_remote_code and trust_remote_code: a = get_class_from_dynamic_module( __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ) a = kwargs.pop('''code_revision''' , __UpperCAmelCase ) if os.path.isdir(__UpperCAmelCase ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(__UpperCAmelCase ) in FEATURE_EXTRACTOR_MAPPING: a = FEATURE_EXTRACTOR_MAPPING[type(__UpperCAmelCase )] return feature_extractor_class.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) 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 __lowerCAmelCase ( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple ) ->Optional[int]: """simple docstring""" FEATURE_EXTRACTOR_MAPPING.register(__UpperCAmelCase , __UpperCAmelCase )
26
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowercase_ ( unittest.TestCase ): '''simple docstring''' @slow def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" a = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__UpperCAmelCase ).to(__UpperCAmelCase ) a = AutoTokenizer.from_pretrained('''google/mt5-small''' ) a = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids a = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids a = model(input_ids.to(__UpperCAmelCase ) , labels=labels.to(__UpperCAmelCase ) ).loss a = -(labels.shape[-1] * loss.item()) a = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
370
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = BlipImageProcessor() a = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''' ) a = BertTokenizerFast.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) a = InstructBlipProcessor(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Tuple ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).tokenizer def __lowerCAmelCase ( self : int , **__UpperCAmelCase : str ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).image_processor def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->Optional[Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).qformer_tokenizer def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" a = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) self.assertIsInstance(processor.qformer_tokenizer , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) a = qformer_tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['''qformer_''' + key] ) def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Dict ) ->List[Any]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = self.get_qformer_tokenizer() a = InstructBlipProcessor( tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase , qformer_tokenizer=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual( list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values'''] , )
26
0
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class lowercase_ ( lowercase , lowercase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self : Any , __UpperCAmelCase : Union[str, Any]=2_000 , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Union[str, Any]=20 , __UpperCAmelCase : Any=1e-3 ) ->Dict: """simple docstring""" a = None a = None a = None def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, torch.device] = None ) ->Any: """simple docstring""" a = torch.linspace(1 , self.config.sampling_eps , __UpperCAmelCase , device=__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[str]=None ) ->Union[str, Any]: """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score a = ( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) a = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) a = std.flatten() while len(std.shape ) < len(score.shape ): a = std.unsqueeze(-1 ) a = -score / std # compute a = -1.0 / len(self.timesteps ) a = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) a = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): a = beta_t.unsqueeze(-1 ) a = -0.5 * beta_t * x a = torch.sqrt(__UpperCAmelCase ) a = drift - diffusion**2 * score a = x + drift * dt # add noise a = randn_tensor(x.shape , layout=x.layout , generator=__UpperCAmelCase , device=x.device , dtype=x.dtype ) a = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" return self.config.num_train_timesteps
371
import math def _a ( a :int = 100 ) -> int: a = sum(i * i for i in range(1 , n + 1 ) ) a = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
26
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Optional[Any] = StableDiffusionInpaintPipeline lowercase : int = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowercase : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase : Any = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase : int = frozenset([] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , 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=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[Any] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = 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 ) UpperCamelCase : 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 , ) UpperCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched UpperCamelCase : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[str] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert("""RGB""" ).resize((64, 64) ) UpperCamelCase : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : int = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Optional[Any] = StableDiffusionInpaintPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = sd_pipe.to(SCREAMING_SNAKE_CASE_ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = sd_pipe(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase : Any = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def a_ ( self ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self ): UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) UpperCamelCase : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" UpperCamelCase : str = StableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() UpperCamelCase : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = torch.manual_seed(0 ) UpperCamelCase : Any = pipe( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type="""np""" , ) UpperCamelCase : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9e-3 def a_ ( self ): UpperCamelCase : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) UpperCamelCase : Dict = """stabilityai/stable-diffusion-2-inpainting""" UpperCamelCase : Union[str, Any] = StableDiffusionInpaintPipeline.from_pretrained( SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa , safety_checker=SCREAMING_SNAKE_CASE_ , ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() UpperCamelCase : str = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = torch.manual_seed(0 ) UpperCamelCase : List[Any] = pipe( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type="""np""" , ) UpperCamelCase : Any = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5e-1 def a_ ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCamelCase : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : str = """stabilityai/stable-diffusion-2-inpainting""" UpperCamelCase : Dict = PNDMScheduler.from_pretrained(SCREAMING_SNAKE_CASE_ , subfolder="""scheduler""" ) UpperCamelCase : Any = StableDiffusionInpaintPipeline.from_pretrained( SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa , ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() UpperCamelCase : Dict = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : Optional[Any] = torch.manual_seed(0 ) UpperCamelCase : str = pipe( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , output_type="""np""" , ) UpperCamelCase : Tuple = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
27
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
1
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class lowerCamelCase ( unittest.TestCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): UpperCamelCase : int = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = """sshleifer/tiny-gpt2""" UpperCamelCase : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : int = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : Dict = """sgugger/tiny-distilbert-classification""" UpperCamelCase : str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , only_pretrain_model=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[Any] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : Optional[Any] = """sshleifer/tiny-gpt2""" UpperCamelCase : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : List[Any] = """sshleifer/tiny-gpt2""" UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[int] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : Any = """sshleifer/tiny-gpt2""" UpperCamelCase : List[Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Union[str, Any] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : Any = """sshleifer/tiny-gpt2""" UpperCamelCase : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def a_ ( self ): UpperCamelCase : str = """sshleifer/tiny-gpt2""" UpperCamelCase : Dict = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def a_ ( self ): UpperCamelCase : Tuple = """patrickvonplaten/t5-tiny-random""" UpperCamelCase : Any = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , configs=[config] ) UpperCamelCase : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , """Cannot do xla on CPU.""" ) def a_ ( self ): UpperCamelCase : Tuple = """sshleifer/tiny-gpt2""" UpperCamelCase : List[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , use_xla=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[str] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def a_ ( self ): UpperCamelCase : str = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=SCREAMING_SNAKE_CASE_ , save_to_csv=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , """inf_time.csv""" ) , inference_memory_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , """inf_mem.csv""" ) , env_info_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , """env.csv""" ) , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) benchmark.run() self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , """env.csv""" ) ).exists() ) def a_ ( self ): UpperCamelCase : List[str] = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(SCREAMING_SNAKE_CASE_ ): self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """sequential""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """cumulative""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """current""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(SCREAMING_SNAKE_CASE_ , """log.txt""" ) , log_print=SCREAMING_SNAKE_CASE_ , trace_memory_line_by_line=SCREAMING_SNAKE_CASE_ , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[str] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , """log.txt""" ) ).exists() )
27
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
1
"""simple docstring""" from typing import Any def A_ ( snake_case_ : list ,snake_case_ : list ,snake_case_ : dict ,snake_case_ : dict ,snake_case_ : dict ,): '''simple docstring''' _validation( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,) # Creates data structures and fill initial step UpperCamelCase : dict = {} UpperCamelCase : dict = {} for state in states_space: UpperCamelCase : int = observations_space[0] UpperCamelCase : Optional[Any] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) UpperCamelCase : List[str] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1 ,len(snake_case_ ) ): UpperCamelCase : Optional[Any] = observations_space[o] UpperCamelCase : Dict = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function UpperCamelCase : Union[str, Any] = """""" UpperCamelCase : Any = -1 for k_state in states_space: UpperCamelCase : Dict = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: UpperCamelCase : Optional[Any] = probability UpperCamelCase : Dict = k_state # Update probabilities and pointers dicts UpperCamelCase : Optional[int] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) UpperCamelCase : List[Any] = arg_max # The final observation UpperCamelCase : Union[str, Any] = observations_space[len(snake_case_ ) - 1] # argmax for given final observation UpperCamelCase : List[str] = """""" UpperCamelCase : List[Any] = -1 for k_state in states_space: UpperCamelCase : Optional[int] = probabilities[(k_state, final_observation)] if probability > max_probability: UpperCamelCase : int = probability UpperCamelCase : List[Any] = k_state UpperCamelCase : Union[str, Any] = arg_max # Process pointers backwards UpperCamelCase : Optional[int] = last_state UpperCamelCase : List[str] = [] for o in range(len(snake_case_ ) - 1 ,-1 ,-1 ): result.append(snake_case_ ) UpperCamelCase : Union[str, Any] = pointers[previous, observations_space[o]] result.reverse() return result def A_ ( snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Any ,): '''simple docstring''' _validate_not_empty( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,) _validate_lists(snake_case_ ,snake_case_ ) _validate_dicts( snake_case_ ,snake_case_ ,snake_case_ ) def A_ ( snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Any ,): '''simple docstring''' if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("""There's an empty parameter""" ) def A_ ( snake_case_ : Any ,snake_case_ : Any ): '''simple docstring''' _validate_list(snake_case_ ,"""observations_space""" ) _validate_list(snake_case_ ,"""states_space""" ) def A_ ( snake_case_ : Any ,snake_case_ : str ): '''simple docstring''' if not isinstance(_object ,snake_case_ ): UpperCamelCase : Any = f'{var_name} must be a list' raise ValueError(snake_case_ ) else: for x in _object: if not isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : List[Any] = f'{var_name} must be a list of strings' raise ValueError(snake_case_ ) def A_ ( snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Any ,): '''simple docstring''' _validate_dict(snake_case_ ,"""initial_probabilities""" ,snake_case_ ) _validate_nested_dict(snake_case_ ,"""transition_probabilities""" ) _validate_nested_dict(snake_case_ ,"""emission_probabilities""" ) def A_ ( snake_case_ : Any ,snake_case_ : str ): '''simple docstring''' _validate_dict(_object ,snake_case_ ,snake_case_ ) for x in _object.values(): _validate_dict(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) def A_ ( snake_case_ : Any ,snake_case_ : str ,snake_case_ : type ,snake_case_ : bool = False ): '''simple docstring''' if not isinstance(_object ,snake_case_ ): UpperCamelCase : str = f'{var_name} must be a dict' raise ValueError(snake_case_ ) if not all(isinstance(snake_case_ ,snake_case_ ) for x in _object ): UpperCamelCase : Dict = f'{var_name} all keys must be strings' raise ValueError(snake_case_ ) if not all(isinstance(snake_case_ ,snake_case_ ) for x in _object.values() ): UpperCamelCase : str = """nested dictionary """ if nested else """""" UpperCamelCase : Dict = f'{var_name} {nested_text}all values must be {value_type.__name__}' raise ValueError(snake_case_ ) if __name__ == "__main__": from doctest import testmod testmod()
27
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version __A : int = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''') @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The column name of the images in the files.'} ) lowercase : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'A folder containing the training data.'} ) lowercase : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'A folder containing the validation data.'} ) lowercase : Optional[float] = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) lowercase : Optional[int] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) lowercase : Optional[int] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def a_ ( self ): UpperCamelCase : List[str] = {} if self.train_dir is not None: UpperCamelCase : List[str] = self.train_dir if self.validation_dir is not None: UpperCamelCase : int = self.validation_dir UpperCamelCase : List[Any] = data_files if data_files else None @dataclass class lowerCamelCase : lowercase : str = field( default=_UpperCAmelCase , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , 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' ) } , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) lowercase : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) lowercase : str = field(default=_UpperCAmelCase , metadata={'help': 'Name or path of preprocessor config.'} ) lowercase : bool = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) lowercase : float = field( default=0.75 , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'} ) lowercase : bool = field( default=_UpperCAmelCase , metadata={'help': 'Whether or not to train with normalized pixel values as target.'} ) @dataclass class lowerCamelCase ( _UpperCAmelCase ): lowercase : float = field( default=1E-3 , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'} ) def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Any = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def A_ ( ): '''simple docstring''' # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. UpperCamelCase : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCamelCase , UpperCamelCase , UpperCamelCase : int = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[int] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_mae""" ,snake_case_ ,snake_case_ ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() UpperCamelCase : List[Any] = training_args.get_process_log_level() logger.setLevel(snake_case_ ) transformers.utils.logging.set_verbosity(snake_case_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(f'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. UpperCamelCase : int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. UpperCamelCase : Union[str, Any] = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,data_files=data_args.data_files ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,) # If we don't have a validation split, split off a percentage of train as validation. UpperCamelCase : Dict = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split ,snake_case_ ) and data_args.train_val_split > 0.0: UpperCamelCase : Any = ds["""train"""].train_test_split(data_args.train_val_split ) UpperCamelCase : int = split["""train"""] UpperCamelCase : str = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase : List[Any] = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: UpperCamelCase : Tuple = ViTMAEConfig.from_pretrained(model_args.config_name ,**snake_case_ ) elif model_args.model_name_or_path: UpperCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path ,**snake_case_ ) else: UpperCamelCase : Any = ViTMAEConfig() 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}' ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: UpperCamelCase : List[str] = ViTImageProcessor.from_pretrained(model_args.image_processor_name ,**snake_case_ ) elif model_args.model_name_or_path: UpperCamelCase : Tuple = ViTImageProcessor.from_pretrained(model_args.model_name_or_path ,**snake_case_ ) else: UpperCamelCase : Optional[Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: UpperCamelCase : Union[str, Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path ,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) ,config=snake_case_ ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) else: logger.info("""Training new model from scratch""" ) UpperCamelCase : str = ViTMAEForPreTraining(snake_case_ ) if training_args.do_train: UpperCamelCase : List[Any] = ds["""train"""].column_names else: UpperCamelCase : Optional[Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: UpperCamelCase : List[Any] = data_args.image_column_name elif "image" in column_names: UpperCamelCase : int = """image""" elif "img" in column_names: UpperCamelCase : Optional[int] = """img""" else: UpperCamelCase : List[str] = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: UpperCamelCase : Optional[Any] = image_processor.size["""shortest_edge"""] else: UpperCamelCase : List[str] = (image_processor.size["""height"""], image_processor.size["""width"""]) UpperCamelCase : List[str] = Compose( [ Lambda(lambda snake_case_ : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(snake_case_ ,scale=(0.2, 1.0) ,interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean ,std=image_processor.image_std ), ] ) def preprocess_images(snake_case_ : Optional[int] ): UpperCamelCase : Union[str, Any] = [transforms(snake_case_ ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: UpperCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(snake_case_ ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: UpperCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(snake_case_ ) # Compute absolute learning rate UpperCamelCase : List[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: UpperCamelCase : int = training_args.base_learning_rate * total_train_batch_size / 2_5_6 # Initialize our trainer UpperCamelCase : int = Trainer( model=snake_case_ ,args=snake_case_ ,train_dataset=ds["""train"""] if training_args.do_train else None ,eval_dataset=ds["""validation"""] if training_args.do_eval else None ,tokenizer=snake_case_ ,data_collator=snake_case_ ,) # Training if training_args.do_train: UpperCamelCase : Union[str, Any] = None if training_args.resume_from_checkpoint is not None: UpperCamelCase : Optional[int] = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCamelCase : int = last_checkpoint UpperCamelCase : str = trainer.train(resume_from_checkpoint=snake_case_ ) trainer.save_model() trainer.log_metrics("""train""" ,train_result.metrics ) trainer.save_metrics("""train""" ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: UpperCamelCase : str = trainer.evaluate() trainer.log_metrics("""eval""" ,snake_case_ ) trainer.save_metrics("""eval""" ,snake_case_ ) # Write model card and (optionally) push to hub UpperCamelCase : List[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case_ ) else: trainer.create_model_card(**snake_case_ ) def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
27
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
1
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : str = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
"""simple docstring""" 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 ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=(32, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = 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 ) UpperCamelCase : int = 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 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = 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=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = 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 a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) 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 .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
27
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
1
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "AAPL" ): '''simple docstring''' UpperCamelCase : Optional[Any] = f'https://in.finance.yahoo.com/quote/{symbol}?s={symbol}' UpperCamelCase : Tuple = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Any = """My(6px) Pos(r) smartphone_Mt(6px)""" return soup.find("""div""" ,class_=class_ ).find("""span""" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
27
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : 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: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # 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) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
1
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
1
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 ( _UpperCAmelCase , unittest.TestCase ): lowercase : List[Any] = RoCBertTokenizer lowercase : Tuple = None lowercase : Tuple = False lowercase : Optional[Any] = True lowercase : Dict = filter_non_english def a_ ( self ): super().setUp() UpperCamelCase : Tuple = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] UpperCamelCase : int = {} UpperCamelCase : Optional[Any] = {} for i, value in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = i UpperCamelCase : List[str] = i UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) UpperCamelCase : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Union[str, Any] = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCamelCase : List[Any] = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) def a_ ( self ): UpperCamelCase : int = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def a_ ( self ): UpperCamelCase : str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : List[Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def a_ ( self ): UpperCamelCase : Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : List[Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : List[Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def a_ ( self ): UpperCamelCase : Optional[int] = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] UpperCamelCase : str = {} for i, token in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = i UpperCamelCase : Tuple = RoCBertWordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_ , 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 a_ ( 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 a_ ( 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 a_ ( 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 a_ ( self ): UpperCamelCase : List[str] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: UpperCamelCase : Any = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def a_ ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): UpperCamelCase : int = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = f'A, naïve {tokenizer_r.mask_token} AllenNLP sentence.' UpperCamelCase : List[str] = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE_ , """do_lower_case""" ) else False UpperCamelCase : List[Any] = ( [ ((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 a_ ( self ): UpperCamelCase : Dict = ["""的""", """人""", """有"""] UpperCamelCase : Tuple = """""".join(SCREAMING_SNAKE_CASE_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): UpperCamelCase : Optional[Any] = True UpperCamelCase : str = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = False UpperCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that only the first Chinese character is not preceded by "##". UpperCamelCase : List[str] = [ f'##{token}' if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE_ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): UpperCamelCase : Optional[Any] = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCamelCase : Tuple = tokenizer.encode("""你好""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = tokenizer.encode("""你是谁""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def a_ ( self ): UpperCamelCase : Optional[int] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): UpperCamelCase : str = """你好,你是谁""" UpperCamelCase : int = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = tokenizer.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) 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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Tuple = { '''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 ( _UpperCAmelCase ): lowercase : List[Any] = 'bridgetower_vision_model' def __init__( self , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=288 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1e-05 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Union[str, Any] = num_channels UpperCamelCase : Tuple = patch_size UpperCamelCase : Any = image_size UpperCamelCase : Union[str, Any] = initializer_factor UpperCamelCase : Optional[int] = layer_norm_eps UpperCamelCase : Dict = stop_gradient UpperCamelCase : List[str] = share_layernorm UpperCamelCase : Dict = remove_last_layer @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase , UpperCamelCase : int = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if config_dict.get("""model_type""" ) == "bridgetower": UpperCamelCase : List[str] = 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(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): lowercase : int = 'bridgetower_text_model' def __init__( self , SCREAMING_SNAKE_CASE_=5_0265 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=514 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1e-05 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = hidden_size UpperCamelCase : Dict = num_hidden_layers UpperCamelCase : Union[str, Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_act UpperCamelCase : List[Any] = initializer_factor UpperCamelCase : Tuple = intermediate_size UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Optional[Any] = max_position_embeddings UpperCamelCase : List[Any] = type_vocab_size UpperCamelCase : Dict = layer_norm_eps UpperCamelCase : int = position_embedding_type UpperCamelCase : Optional[Any] = use_cache UpperCamelCase : Union[str, Any] = pad_token_id UpperCamelCase : Tuple = bos_token_id UpperCamelCase : List[Any] = eos_token_id @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase , UpperCamelCase : List[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if config_dict.get("""model_type""" ) == "bridgetower": UpperCamelCase : Optional[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(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[str] = 'bridgetower' def __init__( self , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1e-05 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="add" , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): # TODO: remove this once the Hub files are updated. UpperCamelCase : List[str] = kwargs.pop("""text_config_dict""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = kwargs.pop("""vision_config_dict""" , SCREAMING_SNAKE_CASE_ ) super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = share_cross_modal_transformer_layers UpperCamelCase : str = hidden_act UpperCamelCase : Any = hidden_size UpperCamelCase : Optional[Any] = initializer_factor UpperCamelCase : List[Any] = layer_norm_eps UpperCamelCase : Optional[Any] = share_link_tower_layers UpperCamelCase : Optional[int] = link_tower_type UpperCamelCase : Union[str, Any] = num_attention_heads UpperCamelCase : str = num_hidden_layers UpperCamelCase : Union[str, Any] = tie_word_embeddings UpperCamelCase : List[str] = init_layernorm_from_vision_encoder if text_config is None: UpperCamelCase : Any = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" ) if vision_config is None: UpperCamelCase : List[Any] = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" ) UpperCamelCase : Optional[Any] = BridgeTowerTextConfig(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = BridgeTowerVisionConfig(**SCREAMING_SNAKE_CASE_ ) @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = copy.deepcopy(self.__dict__ ) UpperCamelCase : str = self.text_config.to_dict() UpperCamelCase : int = self.vision_config.to_dict() UpperCamelCase : List[str] = self.__class__.model_type return output
27
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __A : Union[str, Any] = logging.get_logger(__name__) __A : List[str] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } __A : Optional[int] = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def A_ ( snake_case_ : Optional[int] ,snake_case_ : Optional[int] ,snake_case_ : Optional[int] ,snake_case_ : str ,snake_case_ : Optional[Any] ,snake_case_ : Optional[Any] ): '''simple docstring''' for attribute in key.split(""".""" ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models UpperCamelCase : Union[str, Any] = """lm_head""" UpperCamelCase : Union[str, Any] = getattr(snake_case_ ,snake_case_ ) if weight_type is not None: UpperCamelCase : List[str] = getattr(snake_case_ ,snake_case_ ).shape else: UpperCamelCase : Union[str, Any] = hf_pointer.shape assert hf_shape == value.shape, ( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": UpperCamelCase : Dict = value elif weight_type == "weight_g": UpperCamelCase : List[Any] = value elif weight_type == "weight_v": UpperCamelCase : Tuple = value elif weight_type == "bias": UpperCamelCase : Union[str, Any] = value else: UpperCamelCase : int = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def A_ ( snake_case_ : List[str] ,snake_case_ : Optional[int] ,snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] UpperCamelCase : List[Any] = fairseq_model.state_dict() UpperCamelCase : str = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase : Any = False if "conv_layers" in name: load_conv_layer( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,hf_model.config.feat_extract_norm == """group""" ,) UpperCamelCase : int = True else: for key, mapped_key in MAPPING.items(): UpperCamelCase : Optional[int] = """unispeech.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase : Optional[int] = True if "*" in mapped_key: UpperCamelCase : List[Any] = name.split(snake_case_ )[0].split(""".""" )[-2] UpperCamelCase : Optional[Any] = mapped_key.replace("""*""" ,snake_case_ ) if "weight_g" in name: UpperCamelCase : Optional[int] = """weight_g""" elif "weight_v" in name: UpperCamelCase : Optional[Any] = """weight_v""" elif "bias" in name: UpperCamelCase : List[Any] = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase : Optional[int] = """weight""" else: UpperCamelCase : Optional[int] = None set_recursively(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f'Unused weights: {unused_weights}' ) def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Optional[Any] ,snake_case_ : List[str] ,snake_case_ : Tuple ,snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Tuple = full_name.split("""conv_layers.""" )[-1] UpperCamelCase : List[str] = name.split(""".""" ) UpperCamelCase : Dict = int(items[0] ) UpperCamelCase : str = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) UpperCamelCase : Dict = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) UpperCamelCase : Dict = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) UpperCamelCase : Dict = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) UpperCamelCase : Optional[Any] = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def A_ ( snake_case_ : Optional[int] ,snake_case_ : List[str] ,snake_case_ : Tuple=None ,snake_case_ : List[str]=None ,snake_case_ : Union[str, Any]=True ): '''simple docstring''' if config_path is not None: UpperCamelCase : Optional[int] = UniSpeechConfig.from_pretrained(snake_case_ ) else: UpperCamelCase : Tuple = UniSpeechConfig() if is_finetuned: if dict_path: UpperCamelCase : Tuple = Dictionary.load_from_json(snake_case_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCamelCase : Union[str, Any] = target_dict.pad_index UpperCamelCase : List[Any] = target_dict.bos_index UpperCamelCase : str = target_dict.eos_index UpperCamelCase : Tuple = len(target_dict.symbols ) UpperCamelCase : Union[str, Any] = os.path.join(snake_case_ ,"""vocab.json""" ) if not os.path.isdir(snake_case_ ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(snake_case_ ) ) return os.makedirs(snake_case_ ,exist_ok=snake_case_ ) UpperCamelCase : str = target_dict.indices # fairseq has the <pad> and <s> switched UpperCamelCase : int = 4_2 UpperCamelCase : str = 4_3 with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(snake_case_ ,snake_case_ ) UpperCamelCase : Dict = WavaVecaPhonemeCTCTokenizer( snake_case_ ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="""|""" ,do_lower_case=snake_case_ ,) UpperCamelCase : List[Any] = True if config.feat_extract_norm == """layer""" else False UpperCamelCase : Optional[int] = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=1_6_0_0_0 ,padding_value=0 ,do_normalize=snake_case_ ,return_attention_mask=snake_case_ ,) UpperCamelCase : Any = WavaVecaProcessor(feature_extractor=snake_case_ ,tokenizer=snake_case_ ) processor.save_pretrained(snake_case_ ) UpperCamelCase : Optional[int] = UniSpeechForCTC(snake_case_ ) else: UpperCamelCase : Any = UniSpeechForPreTraining(snake_case_ ) if is_finetuned: UpperCamelCase , UpperCamelCase , UpperCamelCase : str = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} ) else: UpperCamelCase , UpperCamelCase , UpperCamelCase : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) UpperCamelCase : Optional[Any] = model[0].eval() recursively_load_weights(snake_case_ ,snake_case_ ,snake_case_ ) hf_unispeech.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : Optional[Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) __A : Any = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
27
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
1
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class lowerCamelCase ( _UpperCAmelCase ): def a_ ( self ): UpperCamelCase : str = tempfile.mkdtemp() UpperCamelCase : List[Any] = 8 # DPR tok UpperCamelCase : Dict = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCamelCase : Any = os.path.join(self.tmpdirname , """dpr_tokenizer""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , DPR_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] ) ) # BART tok UpperCamelCase : List[Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase : str = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase : Dict = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase : str = {"""unk_token""": """<unk>"""} UpperCamelCase : List[str] = os.path.join(self.tmpdirname , """bart_tokenizer""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def a_ ( self ): return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def a_ ( self ): return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , """bart_tokenizer""" ) ) def a_ ( self ): shutil.rmtree(self.tmpdirname ) def a_ ( self ): UpperCamelCase : int = Dataset.from_dict( { """id""": ["""0""", """1"""], """text""": ["""foo""", """bar"""], """title""": ["""Foo""", """Bar"""], """embeddings""": [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index("""embeddings""" , string_factory="""Flat""" , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_dataset() UpperCamelCase : str = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch("""transformers.models.rag.retrieval_rag.load_dataset""" ) as mock_load_dataset: UpperCamelCase : Any = dataset UpperCamelCase : Tuple = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = self.get_dummy_dataset() UpperCamelCase : List[str] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="""custom""" , ) if from_disk: UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , """dataset""" ) UpperCamelCase : Union[str, Any] = os.path.join(self.tmpdirname , """index.faiss""" ) dataset.get_index("""embeddings""" ).save(os.path.join(self.tmpdirname , """index.faiss""" ) ) dataset.drop_index("""embeddings""" ) dataset.save_to_disk(os.path.join(self.tmpdirname , """dataset""" ) ) del dataset UpperCamelCase : int = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: UpperCamelCase : str = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , SCREAMING_SNAKE_CASE_ ) , ) return retriever def a_ ( self ): UpperCamelCase : int = Dataset.from_dict( { """id""": ["""0""", """1"""], """text""": ["""foo""", """bar"""], """title""": ["""Foo""", """Bar"""], """embeddings""": [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index("""embeddings""" , string_factory="""Flat""" , metric_type=faiss.METRIC_INNER_PRODUCT ) UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , """hf_bert_base.hnswSQ8_correct_phi_128.c_index""" ) dataset.save_faiss_index("""embeddings""" , index_file_name + """.index.dpr""" ) pickle.dump(dataset["""id"""] , open(index_file_name + """.index_meta.dpr""" , """wb""" ) ) UpperCamelCase : List[Any] = os.path.join(self.tmpdirname , """psgs_w100.tsv.pkl""" ) UpperCamelCase : Dict = {sample["""id"""]: [sample["""text"""], sample["""title"""]] for sample in dataset} pickle.dump(SCREAMING_SNAKE_CASE_ , open(SCREAMING_SNAKE_CASE_ , """wb""" ) ) UpperCamelCase : Optional[Any] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="""legacy""" , index_path=self.tmpdirname , ) UpperCamelCase : Optional[int] = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def a_ ( self ): UpperCamelCase : Any = 1 UpperCamelCase : List[Any] = self.get_dummy_canonical_hf_index_retriever() UpperCamelCase : Optional[int] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase , UpperCamelCase , UpperCamelCase : Tuple = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("""transformers.models.rag.retrieval_rag.load_dataset""" ) as mock_load_dataset: UpperCamelCase : Dict = self.get_dummy_dataset() retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase : Optional[Any] = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def a_ ( self ): UpperCamelCase : Optional[int] = 1 UpperCamelCase : List[str] = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase , UpperCamelCase , UpperCamelCase : Tuple = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def a_ ( self ): UpperCamelCase : Tuple = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase : str = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def a_ ( self ): UpperCamelCase : Union[str, Any] = 1 UpperCamelCase : List[str] = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase , UpperCamelCase , UpperCamelCase : str = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def a_ ( self ): UpperCamelCase : Tuple = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase : List[Any] = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def a_ ( self ): UpperCamelCase : Optional[Any] = 1 UpperCamelCase : List[str] = self.get_dummy_legacy_index_retriever() UpperCamelCase : Dict = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase , UpperCamelCase , UpperCamelCase : Union[str, Any] = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""text"""] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]["""text"""][0] , """bar""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""text"""][0] , """foo""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def a_ ( self ): UpperCamelCase : Optional[int] = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase : Optional[Any] = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def a_ ( self ): import torch UpperCamelCase : str = 1 UpperCamelCase : List[Any] = self.get_dummy_canonical_hf_index_retriever() UpperCamelCase : Tuple = [[5, 7], [10, 11]] UpperCamelCase : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase : Any = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = ( out["""context_input_ids"""], out["""context_attention_mask"""], out["""retrieved_doc_embeds"""], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) UpperCamelCase : Dict = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Union[str, Any] = ( # noqa: F841 out["""context_input_ids"""], out["""context_attention_mask"""], out["""retrieved_doc_embeds"""], out["""doc_ids"""], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def a_ ( self ): UpperCamelCase : Tuple = self.get_dpr_ctx_encoder_tokenizer() UpperCamelCase : Optional[int] = 1 UpperCamelCase : int = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) retriever.set_ctx_encoder_tokenizer(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = [[5, 7], [10, 11]] UpperCamelCase : List[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) UpperCamelCase : Any = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual( len(SCREAMING_SNAKE_CASE_ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("""tokenized_doc_ids""", """tokenized_doc_attention_mask""") ) , SCREAMING_SNAKE_CASE_ ) # check for doc token related keys in dictionary.
27
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
1
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : Tuple = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) UpperCamelCase : Dict = get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(SCREAMING_SNAKE_CASE_ ) , torch_builtin(SCREAMING_SNAKE_CASE_ ) ) ) self.assertFalse(torch.allclose(gelu_python(SCREAMING_SNAKE_CASE_ ) , gelu_new(SCREAMING_SNAKE_CASE_ ) ) ) def a_ ( self ): UpperCamelCase : Optional[Any] = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) UpperCamelCase : Union[str, Any] = get_activation("""gelu""" ) UpperCamelCase : List[Any] = get_activation("""gelu_10""" ) UpperCamelCase : Optional[Any] = torch_builtin(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = geluaa(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(SCREAMING_SNAKE_CASE_ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def a_ ( self ): get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): get_activation("""bogus""" ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): get_activation(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = get_activation("""gelu""" ) UpperCamelCase : Union[str, Any] = 1 UpperCamelCase : int = get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = acta.a
27
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase , UpperCamelCase : Optional[Any] = [], [] while len(snake_case_ ) > 1: UpperCamelCase , UpperCamelCase : Optional[Any] = min(snake_case_ ), max(snake_case_ ) start.append(snake_case_ ) end.append(snake_case_ ) collection.remove(snake_case_ ) collection.remove(snake_case_ ) end.reverse() return start + collection + end if __name__ == "__main__": __A : Union[str, Any] = input('''Enter numbers separated by a comma:\n''').strip() __A : Union[str, Any] = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
27
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A : Dict = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[int] = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __A : Tuple = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ ): super().__init__() UpperCamelCase : Optional[int] = nn.ModuleList(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = True , ): for i, (image, scale, controlnet) in enumerate(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.nets ) ): UpperCamelCase , UpperCamelCase : str = controlnet( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) # merge samples if i == 0: UpperCamelCase , UpperCamelCase : List[str] = down_samples, mid_sample else: UpperCamelCase : int = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , ): UpperCamelCase : Dict = 0 UpperCamelCase : Any = save_directory for controlnet in self.nets: controlnet.save_pretrained( SCREAMING_SNAKE_CASE_ , is_main_process=SCREAMING_SNAKE_CASE_ , save_function=SCREAMING_SNAKE_CASE_ , safe_serialization=SCREAMING_SNAKE_CASE_ , variant=SCREAMING_SNAKE_CASE_ , ) idx += 1 UpperCamelCase : str = model_path_to_save + f'_{idx}' @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = 0 UpperCamelCase : Optional[int] = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... UpperCamelCase : Tuple = pretrained_model_path while os.path.isdir(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = ControlNetModel.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) controlnets.append(SCREAMING_SNAKE_CASE_ ) idx += 1 UpperCamelCase : Tuple = pretrained_model_path + f'_{idx}' logger.info(f'{len(SCREAMING_SNAKE_CASE_ )} controlnets loaded from {pretrained_model_path}.' ) if len(SCREAMING_SNAKE_CASE_ ) == 0: raise ValueError( f'No ControlNets found under {os.path.dirname(SCREAMING_SNAKE_CASE_ )}. Expected at least {pretrained_model_path + "_0"}.' ) return cls(SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Union[str, Any] = {'''configuration_wavlm''': ['''WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WavLMConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ '''WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''WavLMForAudioFrameClassification''', '''WavLMForCTC''', '''WavLMForSequenceClassification''', '''WavLMForXVector''', '''WavLMModel''', '''WavLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys __A : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : str = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
1
"""simple docstring""" def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = 0 # if input_string is "aba" than new_input_string become "a|b|a" UpperCamelCase : List[Any] = """""" UpperCamelCase : Optional[int] = """""" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(snake_case_ ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring UpperCamelCase , UpperCamelCase : Optional[Any] = 0, 0 # length[i] shows the length of palindromic substring with center i UpperCamelCase : Optional[int] = [1 for i in range(len(snake_case_ ) )] # for each character in new_string find corresponding palindromic string UpperCamelCase : List[Any] = 0 for j in range(len(snake_case_ ) ): UpperCamelCase : List[Any] = 1 if j > r else min(length[l + r - j] // 2 ,r - j + 1 ) while ( j - k >= 0 and j + k < len(snake_case_ ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 UpperCamelCase : Dict = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: UpperCamelCase : int = j - k + 1 # noqa: E741 UpperCamelCase : str = j + k - 1 # update max_length and start position if max_length < length[j]: UpperCamelCase : Tuple = length[j] UpperCamelCase : List[Any] = j # create that string UpperCamelCase : int = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
27
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
1
"""simple docstring""" from math import ceil def A_ ( snake_case_ : List[str] ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = list(range(0 ,snake_case_ ) ) UpperCamelCase : Optional[Any] = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check UpperCamelCase : str = [] for i in device_map_blocks: if device_map_blocks.count(snake_case_ ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(snake_case_ ) # Missing blocks UpperCamelCase : Union[str, Any] = [i for i in blocks if i not in device_map_blocks] UpperCamelCase : Optional[int] = [i for i in device_map_blocks if i not in blocks] if len(snake_case_ ) != 0: raise ValueError( """Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device.""" """ These attention blocks were specified more than once: """ + str(snake_case_ ) ) if len(snake_case_ ) != 0: raise ValueError( """There are attention blocks for this model that are not specified in the device_map. Add these attention """ """blocks to a device on the device_map: """ + str(snake_case_ ) ) if len(snake_case_ ) != 0: raise ValueError( """The device_map contains more attention blocks than this model has. Remove these from the device_map:""" + str(snake_case_ ) ) def A_ ( snake_case_ : Optional[int] ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : str = list(range(snake_case_ ) ) UpperCamelCase : List[Any] = int(ceil(n_layers / len(snake_case_ ) ) ) UpperCamelCase : List[Any] = [layers[i : i + n_blocks] for i in range(0 ,snake_case_ ,snake_case_ )] return dict(zip(snake_case_ ,snake_case_ ) )
27
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
1
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
1