code stringlengths 82 54.1k | code_codestyle int64 0 699 | style_context stringlengths 111 35.6k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
'''simple docstring'''
import argparse
import torch
from transformers import (
SpeechTaConfig,
SpeechTaFeatureExtractor,
SpeechTaForSpeechToSpeech,
SpeechTaForSpeechToText,
SpeechTaForTextToSpeech,
SpeechTaProcessor,
SpeechTaTokenizer,
logging,
)
from transformers.tokenization_utils import AddedToken
logging.set_verbosity_info()
__magic_name__ : Union[str, Any] =logging.get_logger('transformers.models.speecht5')
__magic_name__ : List[Any] ={
'speech_encoder_prenet.layer_norm': 'speecht5.encoder.prenet.feature_projection.layer_norm',
'speech_encoder_prenet.post_extract_proj': 'speecht5.encoder.prenet.feature_projection.projection',
'speech_encoder_prenet.pos_conv.0': 'speecht5.encoder.prenet.pos_conv_embed.conv',
'speech_encoder_prenet.mask_emb': 'speecht5.encoder.prenet.masked_spec_embed',
}
__magic_name__ : List[str] ={
'text_encoder_prenet.encoder_prenet.0': 'speecht5.encoder.prenet.embed_tokens',
'text_encoder_prenet.encoder_prenet.1.alpha': 'speecht5.encoder.prenet.encode_positions.alpha',
}
__magic_name__ : List[Any] ={
'speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0': 'speecht5.decoder.prenet.layers.0',
'speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0': 'speecht5.decoder.prenet.layers.1',
'speech_decoder_prenet.decoder_prenet.0.1': 'speecht5.decoder.prenet.final_layer',
'speech_decoder_prenet.decoder_prenet.1.alpha': 'speecht5.decoder.prenet.encode_positions.alpha',
'speech_decoder_prenet.spkembs_layer.0': 'speecht5.decoder.prenet.speaker_embeds_layer',
}
__magic_name__ : Optional[Any] ={
'speech_decoder_postnet.feat_out': 'speech_decoder_postnet.feat_out',
'speech_decoder_postnet.prob_out': 'speech_decoder_postnet.prob_out',
'speech_decoder_postnet.postnet.postnet.0.0': 'speech_decoder_postnet.layers.0.conv',
'speech_decoder_postnet.postnet.postnet.0.1': 'speech_decoder_postnet.layers.0.batch_norm',
'speech_decoder_postnet.postnet.postnet.1.0': 'speech_decoder_postnet.layers.1.conv',
'speech_decoder_postnet.postnet.postnet.1.1': 'speech_decoder_postnet.layers.1.batch_norm',
'speech_decoder_postnet.postnet.postnet.2.0': 'speech_decoder_postnet.layers.2.conv',
'speech_decoder_postnet.postnet.postnet.2.1': 'speech_decoder_postnet.layers.2.batch_norm',
'speech_decoder_postnet.postnet.postnet.3.0': 'speech_decoder_postnet.layers.3.conv',
'speech_decoder_postnet.postnet.postnet.3.1': 'speech_decoder_postnet.layers.3.batch_norm',
'speech_decoder_postnet.postnet.postnet.4.0': 'speech_decoder_postnet.layers.4.conv',
'speech_decoder_postnet.postnet.postnet.4.1': 'speech_decoder_postnet.layers.4.batch_norm',
}
__magic_name__ : Optional[Any] ={
'text_decoder_prenet.embed_tokens': 'speecht5.decoder.prenet.embed_tokens',
}
__magic_name__ : Any ={
'text_decoder_postnet.output_projection': 'text_decoder_postnet.lm_head',
}
__magic_name__ : Optional[int] ={
'encoder.layers.*.self_attn.k_proj': 'speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj',
'encoder.layers.*.self_attn.v_proj': 'speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj',
'encoder.layers.*.self_attn.q_proj': 'speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj',
'encoder.layers.*.self_attn.out_proj': 'speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj',
'encoder.layers.*.self_attn_layer_norm': 'speecht5.encoder.wrapped_encoder.layers.*.layer_norm',
'encoder.layers.*.fc1': 'speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense',
'encoder.layers.*.fc2': 'speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense',
'encoder.layers.*.final_layer_norm': 'speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm',
'encoder.layer_norm': 'speecht5.encoder.wrapped_encoder.layer_norm',
'encoder.pos_emb.pe_k': 'speecht5.encoder.wrapped_encoder.embed_positions.pe_k',
}
__magic_name__ : List[Any] ={
'decoder.layers.*.self_attn.k_proj': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj',
'decoder.layers.*.self_attn.v_proj': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj',
'decoder.layers.*.self_attn.q_proj': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj',
'decoder.layers.*.self_attn.out_proj': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj',
'decoder.layers.*.self_attn_layer_norm': 'speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm',
'decoder.layers.*.encoder_attn.k_proj': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj',
'decoder.layers.*.encoder_attn.v_proj': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj',
'decoder.layers.*.encoder_attn.q_proj': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj',
'decoder.layers.*.encoder_attn.out_proj': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj',
'decoder.layers.*.encoder_attn_layer_norm': 'speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm',
'decoder.layers.*.fc1': 'speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense',
'decoder.layers.*.fc2': 'speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense',
'decoder.layers.*.final_layer_norm': 'speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm',
}
__magic_name__ : Tuple ={
**MAPPING_SPEECH_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_TEXT_DECODER_PRENET,
**MAPPING_TEXT_DECODER_POSTNET,
}
__magic_name__ : List[Any] ={
**MAPPING_TEXT_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_SPEECH_DECODER_PRENET,
**MAPPING_SPEECH_DECODER_POSTNET,
}
__magic_name__ : Union[str, Any] ={
**MAPPING_SPEECH_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_SPEECH_DECODER_PRENET,
**MAPPING_SPEECH_DECODER_POSTNET,
}
__magic_name__ : List[str] =[]
__magic_name__ : List[Any] =[
'encoder.version',
'encoder.layers.*.norm_k.weight',
'encoder.layers.*.norm_k.bias',
'decoder.version',
'decoder.layers.*.norm_k.weight',
'decoder.layers.*.norm_k.bias',
'decoder.pos_emb.pe_k',
'speech_encoder_prenet.embed_positions._float_tensor',
'text_decoder_prenet.embed_positions._float_tensor',
]
__magic_name__ : Tuple =IGNORE_KEYS + [
'encoder.proj',
'text_encoder_prenet.*',
'speech_decoder_prenet.*',
'speech_decoder_postnet.*',
]
__magic_name__ : Optional[int] =IGNORE_KEYS + [
'encoder.proj',
'speech_encoder_prenet.*',
'text_decoder_prenet.*',
'text_decoder_postnet.*',
]
__magic_name__ : Optional[Any] =IGNORE_KEYS + [
'encoder.proj',
'text_encoder_prenet.*',
'text_decoder_prenet.*',
'text_decoder_postnet.*',
]
def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : List[str] ):
'''simple docstring'''
for attribute in key.split("." ):
__magic_name__ = getattr(lowerCamelCase_ , lowerCamelCase_ )
if weight_type is not None:
__magic_name__ = getattr(lowerCamelCase_ , lowerCamelCase_ ).shape
else:
__magic_name__ = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'
F' {value.shape} for {full_name}' )
if weight_type == "weight":
__magic_name__ = value
elif weight_type == "weight_g":
__magic_name__ = value
elif weight_type == "weight_v":
__magic_name__ = value
elif weight_type == "bias":
__magic_name__ = value
elif weight_type == "running_mean":
__magic_name__ = value
elif weight_type == "running_var":
__magic_name__ = value
elif weight_type == "num_batches_tracked":
__magic_name__ = value
else:
__magic_name__ = value
logger.info(F'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' )
def __snake_case ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : Dict ):
'''simple docstring'''
for key in ignore_keys:
if key.endswith(".*" ):
if name.startswith(key[:-1] ):
return True
elif ".*." in key:
__magic_name__ , __magic_name__ = key.split(".*." )
if prefix in name and suffix in name:
return True
elif key in name:
return True
return False
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = []
if task == "s2t":
__magic_name__ = hf_model.speechta.encoder.prenet.feature_encoder
__magic_name__ = MAPPING_S2T
__magic_name__ = IGNORE_KEYS_S2T
elif task == "t2s":
__magic_name__ = None
__magic_name__ = MAPPING_T2S
__magic_name__ = IGNORE_KEYS_T2S
elif task == "s2s":
__magic_name__ = hf_model.speechta.encoder.prenet.feature_encoder
__magic_name__ = MAPPING_S2S
__magic_name__ = IGNORE_KEYS_S2S
else:
raise ValueError(F'Unsupported task: {task}' )
for name, value in fairseq_dict.items():
if should_ignore(lowerCamelCase_ , lowerCamelCase_ ):
logger.info(F'{name} was ignored' )
continue
__magic_name__ = False
if "conv_layers" in name:
load_conv_layer(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , hf_model.config.feat_extract_norm == "group" , )
__magic_name__ = True
else:
for key, mapped_key in MAPPING.items():
# mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if "*" in key:
__magic_name__ , __magic_name__ = key.split(".*." )
if prefix in name and suffix in name:
__magic_name__ = suffix
# if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
if key in name:
__magic_name__ = True
if "*" in mapped_key:
__magic_name__ = name.split(lowerCamelCase_ )[0].split("." )[-2]
__magic_name__ = mapped_key.replace("*" , lowerCamelCase_ )
if "weight_g" in name:
__magic_name__ = "weight_g"
elif "weight_v" in name:
__magic_name__ = "weight_v"
elif "bias" in name:
__magic_name__ = "bias"
elif "weight" in name:
__magic_name__ = "weight"
elif "running_mean" in name:
__magic_name__ = "running_mean"
elif "running_var" in name:
__magic_name__ = "running_var"
elif "num_batches_tracked" in name:
__magic_name__ = "num_batches_tracked"
else:
__magic_name__ = None
set_recursively(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
continue
if not is_used:
unused_weights.append(lowerCamelCase_ )
logger.warning(F'Unused weights: {unused_weights}' )
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = full_name.split("conv_layers." )[-1]
__magic_name__ = name.split("." )
__magic_name__ = int(items[0] )
__magic_name__ = int(items[1] )
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
F'{full_name} has size {value.shape}, but'
F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' )
__magic_name__ = value
logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
F'{full_name} has size {value.shape}, but'
F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' )
__magic_name__ = value
logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
F'{full_name} has size {value.shape}, but'
F' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.' )
__magic_name__ = value
logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
F'{full_name} has size {value.shape}, but'
F' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.' )
__magic_name__ = value
logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' )
else:
unused_weights.append(lowerCamelCase_ )
@torch.no_grad()
def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : List[str] , lowerCamelCase_ : Dict=None , lowerCamelCase_ : List[str]=None , lowerCamelCase_ : List[Any]=None , ):
'''simple docstring'''
if config_path is not None:
__magic_name__ = SpeechTaConfig.from_pretrained(lowerCamelCase_ )
else:
__magic_name__ = SpeechTaConfig()
if task == "s2t":
__magic_name__ = config.max_text_positions
__magic_name__ = SpeechTaForSpeechToText(lowerCamelCase_ )
elif task == "t2s":
__magic_name__ = 1876
__magic_name__ = 600
__magic_name__ = config.max_speech_positions
__magic_name__ = SpeechTaForTextToSpeech(lowerCamelCase_ )
elif task == "s2s":
__magic_name__ = 1876
__magic_name__ = config.max_speech_positions
__magic_name__ = SpeechTaForSpeechToSpeech(lowerCamelCase_ )
else:
raise ValueError(F'Unknown task name: {task}' )
if vocab_path:
__magic_name__ = SpeechTaTokenizer(lowerCamelCase_ , model_max_length=config.max_text_positions )
# Mask token behaves like a normal word, i.e. include the space before it
__magic_name__ = AddedToken("<mask>" , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ )
__magic_name__ = mask_token
tokenizer.add_special_tokens({"mask_token": mask_token} )
tokenizer.add_tokens(["<ctc_blank>"] )
__magic_name__ = SpeechTaFeatureExtractor()
__magic_name__ = SpeechTaProcessor(tokenizer=lowerCamelCase_ , feature_extractor=lowerCamelCase_ )
processor.save_pretrained(lowerCamelCase_ )
__magic_name__ = torch.load(lowerCamelCase_ )
recursively_load_weights(fairseq_checkpoint["model"] , lowerCamelCase_ , lowerCamelCase_ )
model.save_pretrained(lowerCamelCase_ )
if repo_id:
print("Pushing to the hub..." )
processor.push_to_hub(lowerCamelCase_ )
model.push_to_hub(lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : Optional[Any] =argparse.ArgumentParser()
parser.add_argument(
'--task',
default='s2t',
type=str,
help='Type of the SpeechT5 model you\'d like to convert. Should be one of \'s2t\', \'t2s\', \'s2s\'.',
)
parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to fairseq checkpoint')
parser.add_argument('--vocab_path', default=None, type=str, help='Path to SentencePiece model')
parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
parser.add_argument(
'--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.'
)
parser.add_argument(
'--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.'
)
__magic_name__ : List[Any] =parser.parse_args()
convert_speechta_checkpoint(
args.task,
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.config_path,
args.vocab_path,
args.push_to_hub,
)
| 664 |
'''simple docstring'''
from __future__ import annotations
from typing import Any
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None:
__magic_name__ , __magic_name__ = row, column
__magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )]
def __str__( self : Optional[Any] ) -> str:
__magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n'
# Make string identifier
__magic_name__ = 0
for row_vector in self.array:
for obj in row_vector:
__magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) )
__magic_name__ = f'%{max_element_length}s'
# Make string and return
def single_line(_lowerCamelCase : list[float] ) -> str:
nonlocal string_format_identifier
__magic_name__ = "["
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector )
line += "]"
return line
s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array )
return s
def __repr__( self : Optional[int] ) -> str:
return str(self )
def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool:
if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2):
return False
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
return False
else:
return True
def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any:
assert self.validate_indicies(_lowerCamelCase )
return self.array[loc[0]][loc[1]]
def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None:
assert self.validate_indicies(_lowerCamelCase )
__magic_name__ = value
def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix:
assert isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == another.row and self.column == another.column
# Add
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] + another[r, c]
return result
def __neg__( self : int ) -> Matrix:
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = -self[r, c]
return result
def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix:
return self + (-another)
def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix:
if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] * another
return result
elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication
assert self.column == another.row
__magic_name__ = Matrix(self.row , another.column )
for r in range(self.row ):
for c in range(another.column ):
for i in range(self.column ):
result[r, c] += self[r, i] * another[i, c]
return result
else:
__magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})'
raise TypeError(_lowerCamelCase )
def __A ( self : Optional[int] ) -> Matrix:
__magic_name__ = Matrix(self.column , self.row )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c]
return result
def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any:
assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == self.column == u.row == v.row # u, v should be column vector
assert u.column == v.column == 1 # u, v should be column vector
# Calculate
__magic_name__ = v.transpose()
__magic_name__ = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
# Testing
if __name__ == "__main__":
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Matrix(3 , 3 , 0 )
for i in range(3 ):
__magic_name__ = 1
print(F'a^(-1) is {ainv}' )
# u, v
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5
print(F'u is {u}' )
print(F'v is {v}' )
print(F'uv^T is {u * v.transpose()}' )
# Sherman Morrison
print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' )
def __snake_case ( ):
'''simple docstring'''
import doctest
doctest.testmod()
testa()
| 664 | 1 |
'''simple docstring'''
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available
from ...utils import OptionalDependencyNotAvailable
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
else:
from .notes_encoder import SpectrogramNotesEncoder
from .continous_encoder import SpectrogramContEncoder
from .pipeline_spectrogram_diffusion import (
SpectrogramContEncoder,
SpectrogramDiffusionPipeline,
TaFilmDecoder,
)
try:
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
else:
from .midi_utils import MidiProcessor
| 664 |
'''simple docstring'''
import argparse
import logging
from collections import namedtuple
import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer # The authors' implementation
from transformers import BertTokenizer
logging.basicConfig(level=logging.INFO)
__magic_name__ : List[Any] =logging.getLogger(__name__)
__magic_name__ : int ='Hello world! cécé herlolip'
__magic_name__ : List[Any] =namedtuple(
'BertAbsConfig',
[
'temp_dir',
'large',
'use_bert_emb',
'finetune_bert',
'encoder',
'share_emb',
'max_pos',
'enc_layers',
'enc_hidden_size',
'enc_heads',
'enc_ff_size',
'enc_dropout',
'dec_layers',
'dec_hidden_size',
'dec_heads',
'dec_ff_size',
'dec_dropout',
],
)
def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ):
'''simple docstring'''
__magic_name__ = BertAbsConfig(
temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , )
__magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage )
__magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ )
original.eval()
__magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) )
new_model.eval()
# -------------------
# Convert the weights
# -------------------
logging.info("convert the model" )
new_model.bert.load_state_dict(original.bert.state_dict() )
new_model.decoder.load_state_dict(original.decoder.state_dict() )
new_model.generator.load_state_dict(original.generator.state_dict() )
# ----------------------------------
# Make sure the outpus are identical
# ----------------------------------
logging.info("Make sure that the models' outputs are identical" )
__magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" )
# prepare the model inputs
__magic_name__ = tokenizer.encode("This is sample éàalj'-." )
encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
__magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." )
decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
# failsafe to make sure the weights reset does not affect the
# loaded weights.
assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0
# forward pass
__magic_name__ = encoder_input_ids
__magic_name__ = decoder_input_ids
__magic_name__ = __magic_name__ = None
__magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = None
# The original model does not apply the geneator layer immediatly but rather in
# the beam search (where it combines softmax + linear layer). Since we already
# apply the softmax in our generation process we only apply the linear layer here.
# We make sure that the outputs of the full stack are identical
__magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = original.generator(lowerCamelCase_ )
__magic_name__ = new_model(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = new_model.generator(lowerCamelCase_ )
__magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if are_identical:
logging.info("all weights are equal up to 1e-3" )
else:
raise ValueError("the weights are different. The new model is likely different from the original one." )
# The model has been saved with torch.save(model) and this is bound to the exact
# directory structure. We save the state_dict instead.
logging.info("saving the model's state dictionary" )
torch.save(
new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" )
if __name__ == "__main__":
__magic_name__ : Dict =argparse.ArgumentParser()
parser.add_argument(
'--bertabs_checkpoint_path',
default=None,
type=str,
required=True,
help='Path the official PyTorch dump.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
required=True,
help='Path to the output PyTorch model.',
)
__magic_name__ : Any =parser.parse_args()
convert_bertabs_checkpoints(
args.bertabs_checkpoint_path,
args.pytorch_dump_folder_path,
)
| 664 | 1 |
'''simple docstring'''
import random
def __snake_case ( lowerCamelCase_ : list , lowerCamelCase_ : int ):
'''simple docstring'''
__magic_name__ , __magic_name__ , __magic_name__ = [], [], []
for element in data:
if element < pivot:
less.append(lowerCamelCase_ )
elif element > pivot:
greater.append(lowerCamelCase_ )
else:
equal.append(lowerCamelCase_ )
return less, equal, greater
def __snake_case ( lowerCamelCase_ : list , lowerCamelCase_ : int ):
'''simple docstring'''
if index >= len(lowerCamelCase_ ) or index < 0:
return None
__magic_name__ = items[random.randint(0 , len(lowerCamelCase_ ) - 1 )]
__magic_name__ = 0
__magic_name__ , __magic_name__ , __magic_name__ = _partition(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = len(lowerCamelCase_ )
__magic_name__ = len(lowerCamelCase_ )
# index is the pivot
if m <= index < m + count:
return pivot
# must be in smaller
elif m > index:
return quick_select(lowerCamelCase_ , lowerCamelCase_ )
# must be in larger
else:
return quick_select(lowerCamelCase_ , index - (m + count) )
| 664 |
'''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.generation import DisjunctiveConstraint
@require_torch
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : List[str] ) -> str:
# For consistency across different places the DisjunctiveConstraint is called,
# dc.token_ids is a list of integers. It is also initialized only by integers.
__magic_name__ = [[1, 2, 4], [1, 2, 3, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] )
def __A ( self : List[Any] ) -> str:
# We can't have constraints that are complete subsets of another. This leads to a preverse
# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
__magic_name__ = [[1, 2], [1, 2, 3, 4]]
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(_lowerCamelCase ) # fails here
def __A ( self : List[Any] ) -> int:
__magic_name__ = [[1, 2, 3], [1, 2, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 )
__magic_name__ = stepped is True and completed is True and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 3] )
def __A ( self : Any ) -> Union[str, Any]:
__magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2, 4] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 4, 5] )
dc.reset()
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 3 )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 2 )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.remaining() == 0 )
self.assertTrue(dc.current_seq == [1, 2, 5] )
| 664 | 1 |
'''simple docstring'''
from dataclasses import dataclass, field
from typing import Tuple
from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments
if is_tf_available():
import tensorflow as tf
__magic_name__ : List[str] =logging.get_logger(__name__)
@dataclass
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = [
'''no_inference''',
'''no_cuda''',
'''no_tpu''',
'''no_speed''',
'''no_memory''',
'''no_env_print''',
'''no_multi_process''',
]
def __init__( self : List[Any] , **_lowerCamelCase : Dict ) -> Optional[int]:
for deprecated_arg in self.deprecated_args:
if deprecated_arg in kwargs:
__magic_name__ = deprecated_arg[3:]
__magic_name__ = not kwargs.pop(_lowerCamelCase )
logger.warning(
f'{deprecated_arg} is depreciated. Please use --no-{positive_arg} or'
f' {positive_arg}={kwargs[positive_arg]}' )
__magic_name__ = kwargs.pop("tpu_name" , self.tpu_name )
__magic_name__ = kwargs.pop("device_idx" , self.device_idx )
__magic_name__ = kwargs.pop("eager_mode" , self.eager_mode )
__magic_name__ = kwargs.pop("use_xla" , self.use_xla )
super().__init__(**_lowerCamelCase )
UpperCAmelCase__ : str = field(
default=A , metadata={'''help''': '''Name of TPU'''} , )
UpperCAmelCase__ : int = field(
default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , )
UpperCAmelCase__ : bool = field(default=A , metadata={'''help''': '''Benchmark models in eager model.'''} )
UpperCAmelCase__ : bool = field(
default=A , metadata={
'''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.'''
} , )
@cached_property
def __A ( self : Tuple ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]:
requires_backends(self , ["tf"] )
__magic_name__ = None
if self.tpu:
try:
if self.tpu_name:
__magic_name__ = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name )
else:
__magic_name__ = tf.distribute.cluster_resolver.TPUClusterResolver()
except ValueError:
__magic_name__ = None
return tpu
@cached_property
def __A ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]:
requires_backends(self , ["tf"] )
if self.is_tpu:
tf.config.experimental_connect_to_cluster(self._setup_tpu )
tf.tpu.experimental.initialize_tpu_system(self._setup_tpu )
__magic_name__ = tf.distribute.TPUStrategy(self._setup_tpu )
else:
# currently no multi gpu is allowed
if self.is_gpu:
# TODO: Currently only single GPU is supported
tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU" )
__magic_name__ = tf.distribute.OneDeviceStrategy(device=f'/gpu:{self.device_idx}' )
else:
tf.config.set_visible_devices([] , "GPU" ) # disable GPU
__magic_name__ = tf.distribute.OneDeviceStrategy(device=f'/cpu:{self.device_idx}' )
return strategy
@property
def __A ( self : Union[str, Any] ) -> bool:
requires_backends(self , ["tf"] )
return self._setup_tpu is not None
@property
def __A ( self : str ) -> "tf.distribute.Strategy":
requires_backends(self , ["tf"] )
return self._setup_strategy
@property
def __A ( self : Any ) -> Any:
requires_backends(self , ["tf"] )
return tf.config.list_physical_devices("GPU" )
@property
def __A ( self : Union[str, Any] ) -> int:
requires_backends(self , ["tf"] )
if self.cuda:
return len(self.gpu_list )
return 0
@property
def __A ( self : List[Any] ) -> bool:
return self.n_gpu > 0
| 664 |
'''simple docstring'''
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
__magic_name__ : Dict ={
'return_dict': False,
'output_hidden_states': True,
'output_attentions': True,
'torchscript': True,
'torch_dtype': 'float16',
'use_bfloat16': True,
'tf_legacy_loss': True,
'pruned_heads': {'a': 1},
'tie_word_embeddings': False,
'is_decoder': True,
'cross_attention_hidden_size': 1_28,
'add_cross_attention': True,
'tie_encoder_decoder': True,
'max_length': 50,
'min_length': 3,
'do_sample': True,
'early_stopping': True,
'num_beams': 3,
'num_beam_groups': 3,
'diversity_penalty': 0.5,
'temperature': 2.0,
'top_k': 10,
'top_p': 0.7,
'typical_p': 0.2,
'repetition_penalty': 0.8,
'length_penalty': 0.8,
'no_repeat_ngram_size': 5,
'encoder_no_repeat_ngram_size': 5,
'bad_words_ids': [1, 2, 3],
'num_return_sequences': 3,
'chunk_size_feed_forward': 5,
'output_scores': True,
'return_dict_in_generate': True,
'forced_bos_token_id': 2,
'forced_eos_token_id': 3,
'remove_invalid_values': True,
'architectures': ['BertModel'],
'finetuning_task': 'translation',
'id2label': {0: 'label'},
'label2id': {'label': '0'},
'tokenizer_class': 'BertTokenizerFast',
'prefix': 'prefix',
'bos_token_id': 6,
'pad_token_id': 7,
'eos_token_id': 8,
'sep_token_id': 9,
'decoder_start_token_id': 10,
'exponential_decay_length_penalty': (5, 1.0_1),
'suppress_tokens': [0, 1],
'begin_suppress_tokens': 2,
'task_specific_params': {'translation': 'some_params'},
'problem_type': 'regression',
}
@is_staging_test
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def __A ( cls : Any ) -> Union[str, Any]:
__magic_name__ = TOKEN
HfFolder.save_token(_lowerCamelCase )
@classmethod
def __A ( cls : Any ) -> Tuple:
try:
delete_repo(token=cls._token , repo_id="test-config" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-config-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-config" )
except HTTPError:
pass
def __A ( self : Optional[Any] ) -> Dict:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("test-config" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="test-config" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : str ) -> Optional[int]:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-config-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
_lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : Optional[int] ) -> Union[str, Any]:
CustomConfig.register_for_auto_class()
__magic_name__ = CustomConfig(attribute=42 )
config.push_to_hub("test-dynamic-config" , use_auth_token=self._token )
# This has added the proper auto_map field to the config
self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} )
__magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase )
# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
self.assertEqual(new_config.__class__.__name__ , "CustomConfig" )
self.assertEqual(new_config.attribute , 42 )
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Optional[Any]:
__magic_name__ = GPTaConfig()
# attempt to modify each of int/float/bool/str config records and verify they were updated
__magic_name__ = c.n_embd + 1 # int
__magic_name__ = c.resid_pdrop + 1.0 # float
__magic_name__ = not c.scale_attn_weights # bool
__magic_name__ = c.summary_type + "foo" # str
c.update_from_string(
f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' )
self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" )
self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" )
self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" )
self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" )
def __A ( self : List[Any] ) -> Union[str, Any]:
__magic_name__ = PretrainedConfig()
__magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to addin config_common_kwargs above.
self.assertListEqual(
_lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] )
__magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )]
if len(_lowerCamelCase ) > 0:
raise ValueError(
"The following keys are set with the default values in"
" `test_configuration_common.config_common_kwargs` pick another value for them:"
f' {", ".join(_lowerCamelCase )}.' )
def __A ( self : List[Any] ) -> List[Any]:
with self.assertRaises(_lowerCamelCase ):
# config is in subfolder, the following should not work without specifying the subfolder
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" )
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" )
self.assertIsNotNone(_lowerCamelCase )
def __A ( self : Tuple ) -> int:
# A mock response for an HTTP head request to emulate server down
__magic_name__ = mock.Mock()
__magic_name__ = 5_00
__magic_name__ = {}
__magic_name__ = HTTPError
__magic_name__ = {}
# Download this model to make sure it's in the cache.
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head:
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
def __A ( self : Union[str, Any] ) -> Dict:
# This test is for deprecated behavior and can be removed in v5
__magic_name__ = BertConfig.from_pretrained(
"https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" )
def __A ( self : Dict ) -> Optional[int]:
__magic_name__ = AutoConfig.from_pretrained("bert-base-cased" )
__magic_name__ = ["config.4.0.0.json"]
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(_lowerCamelCase )
__magic_name__ = 2
json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) )
# This should pick the new configuration file as the version of Transformers is > 4.0.0
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
__magic_name__ = ["config.42.0.0.json"]
__magic_name__ = 7_68
configuration.save_pretrained(_lowerCamelCase )
shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) )
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 7_68 )
def __A ( self : Optional[int] ) -> str:
# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
__magic_name__ = "hf-internal-testing/test-two-configs"
import transformers as new_transformers
__magic_name__ = "v4.0.0"
__magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained(
_lowerCamelCase , return_unused_kwargs=_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(_lowerCamelCase , {} )
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
__magic_name__ = "v3.0.0"
__magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(old_configuration.hidden_size , 7_68 )
| 664 | 1 |
'''simple docstring'''
from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import MagicMock, patch
from transformers import AutoModel, TFAutoModel
from transformers.onnx import FeaturesManager
from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch
@require_torch
@require_tf
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : Dict ) -> Union[str, Any]:
__magic_name__ = SMALL_MODEL_IDENTIFIER
__magic_name__ = "pt"
__magic_name__ = "tf"
def __A ( self : int , _lowerCamelCase : Tuple ) -> str:
__magic_name__ = AutoModel.from_pretrained(self.test_model )
model_pt.save_pretrained(_lowerCamelCase )
def __A ( self : Any , _lowerCamelCase : List[str] ) -> Dict:
__magic_name__ = TFAutoModel.from_pretrained(self.test_model , from_pt=_lowerCamelCase )
model_tf.save_pretrained(_lowerCamelCase )
def __A ( self : Dict ) -> Union[str, Any]:
__magic_name__ = "mock_framework"
# Framework provided - return whatever the user provides
__magic_name__ = FeaturesManager.determine_framework(self.test_model , _lowerCamelCase )
self.assertEqual(_lowerCamelCase , _lowerCamelCase )
# Local checkpoint and framework provided - return provided framework
# PyTorch checkpoint
with TemporaryDirectory() as local_pt_ckpt:
self._setup_pt_ckpt(_lowerCamelCase )
__magic_name__ = FeaturesManager.determine_framework(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(_lowerCamelCase , _lowerCamelCase )
# TensorFlow checkpoint
with TemporaryDirectory() as local_tf_ckpt:
self._setup_tf_ckpt(_lowerCamelCase )
__magic_name__ = FeaturesManager.determine_framework(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(_lowerCamelCase , _lowerCamelCase )
def __A ( self : Dict ) -> int:
# PyTorch checkpoint
with TemporaryDirectory() as local_pt_ckpt:
self._setup_pt_ckpt(_lowerCamelCase )
__magic_name__ = FeaturesManager.determine_framework(_lowerCamelCase )
self.assertEqual(_lowerCamelCase , self.framework_pt )
# TensorFlow checkpoint
with TemporaryDirectory() as local_tf_ckpt:
self._setup_tf_ckpt(_lowerCamelCase )
__magic_name__ = FeaturesManager.determine_framework(_lowerCamelCase )
self.assertEqual(_lowerCamelCase , self.framework_tf )
# Invalid local checkpoint
with TemporaryDirectory() as local_invalid_ckpt:
with self.assertRaises(_lowerCamelCase ):
__magic_name__ = FeaturesManager.determine_framework(_lowerCamelCase )
def __A ( self : Tuple ) -> List[Any]:
__magic_name__ = MagicMock(return_value=_lowerCamelCase )
with patch("transformers.onnx.features.is_tf_available" , _lowerCamelCase ):
__magic_name__ = FeaturesManager.determine_framework(self.test_model )
self.assertEqual(_lowerCamelCase , self.framework_pt )
# PyTorch not in environment -> use TensorFlow
__magic_name__ = MagicMock(return_value=_lowerCamelCase )
with patch("transformers.onnx.features.is_torch_available" , _lowerCamelCase ):
__magic_name__ = FeaturesManager.determine_framework(self.test_model )
self.assertEqual(_lowerCamelCase , self.framework_tf )
# Both in environment -> use PyTorch
__magic_name__ = MagicMock(return_value=_lowerCamelCase )
__magic_name__ = MagicMock(return_value=_lowerCamelCase )
with patch("transformers.onnx.features.is_tf_available" , _lowerCamelCase ), patch(
"transformers.onnx.features.is_torch_available" , _lowerCamelCase ):
__magic_name__ = FeaturesManager.determine_framework(self.test_model )
self.assertEqual(_lowerCamelCase , self.framework_pt )
# Both not in environment -> raise error
__magic_name__ = MagicMock(return_value=_lowerCamelCase )
__magic_name__ = MagicMock(return_value=_lowerCamelCase )
with patch("transformers.onnx.features.is_tf_available" , _lowerCamelCase ), patch(
"transformers.onnx.features.is_torch_available" , _lowerCamelCase ):
with self.assertRaises(_lowerCamelCase ):
__magic_name__ = FeaturesManager.determine_framework(self.test_model )
| 664 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision
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 DPTImageProcessor
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict:
__magic_name__ = size if size is not None else {"height": 18, "width": 18}
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = num_channels
__magic_name__ = image_size
__magic_name__ = min_resolution
__magic_name__ = max_resolution
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = do_normalize
__magic_name__ = image_mean
__magic_name__ = image_std
def __A ( self : int ) -> List[str]:
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
@require_torch
@require_vision
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None
def __A ( self : Dict ) -> Any:
__magic_name__ = DPTImageProcessingTester(self )
@property
def __A ( self : str ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : Tuple ) -> List[str]:
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) )
self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "size" ) )
def __A ( self : List[str] ) -> List[Any]:
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"height": 18, "width": 18} )
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {"height": 42, "width": 42} )
def __A ( self : Union[str, Any] ) -> List[str]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Dict ) -> Optional[Any]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Optional[int] ) -> Dict:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
def __snake_case ( lowerCamelCase_ : list[int] ):
'''simple docstring'''
if not nums:
return 0
__magic_name__ = nums[0]
__magic_name__ = 0
for num in nums[1:]:
__magic_name__ , __magic_name__ = (
max_excluding + num,
max(lowerCamelCase_ , lowerCamelCase_ ),
)
return max(lowerCamelCase_ , lowerCamelCase_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 |
'''simple docstring'''
import numpy
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None:
__magic_name__ = input_array
# Random initial weights are assigned where first argument is the
# number of nodes in previous layer and second argument is the
# number of nodes in the next layer.
# Random initial weights are assigned.
# self.input_array.shape[1] is used to represent number of nodes in input layer.
# First hidden layer consists of 4 nodes.
__magic_name__ = numpy.random.rand(
self.input_array.shape[1] , 4 )
# Random initial values for the first hidden layer.
# First hidden layer has 4 nodes.
# Second hidden layer has 3 nodes.
__magic_name__ = numpy.random.rand(
4 , 3 )
# Random initial values for the second hidden layer.
# Second hidden layer has 3 nodes.
# Output layer has 1 node.
__magic_name__ = numpy.random.rand(3 , 1 )
# Real output values provided.
__magic_name__ = output_array
# Predicted output values by the neural network.
# Predicted_output array initially consists of zeroes.
__magic_name__ = numpy.zeros(output_array.shape )
def __A ( self : int ) -> numpy.ndarray:
__magic_name__ = sigmoid(
numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) )
# layer_between_first_hidden_layer_and_second_hidden_layer is the layer
# connecting the first hidden set of nodes with the second hidden set of nodes.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
# layer_between_second_hidden_layer_and_output is the layer connecting
# second hidden layer with the output node.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return self.layer_between_second_hidden_layer_and_output
def __A ( self : Dict ) -> None:
__magic_name__ = numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , )
__magic_name__ = numpy.dot(
self.layer_between_input_and_first_hidden_layer.T , numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , )
__magic_name__ = numpy.dot(
self.input_array.T , numpy.dot(
numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , )
* sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , )
self.input_layer_and_first_hidden_layer_weights += (
updated_input_layer_and_first_hidden_layer_weights
)
self.first_hidden_layer_and_second_hidden_layer_weights += (
updated_first_hidden_layer_and_second_hidden_layer_weights
)
self.second_hidden_layer_and_output_layer_weights += (
updated_second_hidden_layer_and_output_layer_weights
)
def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None:
for iteration in range(1 , iterations + 1 ):
__magic_name__ = self.feedforward()
self.back_propagation()
if give_loss:
__magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) )
print(f'Iteration {iteration} Loss: {loss}' )
def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int:
__magic_name__ = input_arr
__magic_name__ = sigmoid(
numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return int(self.layer_between_second_hidden_layer_and_output > 0.6 )
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return 1 / (1 + numpy.exp(-value ))
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return (value) * (1 - (value))
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = numpy.array(
(
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
) , dtype=numpy.floataa , )
# True output values for the given input values.
__magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa )
# Calling neural network class.
__magic_name__ = TwoHiddenLayerNeuralNetwork(
input_array=lowerCamelCase_ , output_array=lowerCamelCase_ )
# Calling training function.
# Set give_loss to True if you want to see loss in every iteration.
neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ )
return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) )
if __name__ == "__main__":
example()
| 664 | 1 |
'''simple docstring'''
import functools
import logging
import os
import sys
import threading
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
__magic_name__ : Tuple =threading.Lock()
__magic_name__ : Optional[logging.Handler] =None
__magic_name__ : List[str] ={
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
}
__magic_name__ : str =logging.WARNING
__magic_name__ : Any =True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '
F'has to be one of: { ", ".join(log_levels.keys() ) }' )
return _default_log_level
def __snake_case ( ):
'''simple docstring'''
return __name__.split("." )[0]
def __snake_case ( ):
'''simple docstring'''
return logging.getLogger(_get_library_name() )
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
__magic_name__ = logging.StreamHandler() # Set sys.stderr as stream.
__magic_name__ = sys.stderr.flush
# Apply our default configuration to the library root logger.
__magic_name__ = _get_library_root_logger()
library_root_logger.addHandler(_default_handler )
library_root_logger.setLevel(_get_default_logging_level() )
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if not _default_handler:
return
__magic_name__ = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler )
library_root_logger.setLevel(logging.NOTSET )
__magic_name__ = None
def __snake_case ( ):
'''simple docstring'''
return log_levels
def __snake_case ( lowerCamelCase_ : Optional[str] = None ):
'''simple docstring'''
if name is None:
__magic_name__ = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def __snake_case ( lowerCamelCase_ : int ):
'''simple docstring'''
_configure_library_root_logger()
_get_library_root_logger().setLevel(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
__magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" )
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ )
if no_advisory_warnings:
return
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : int =warning_advice
@functools.lru_cache(lowerCamelCase_ )
def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ):
'''simple docstring'''
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : Optional[int] =warning_once
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument
__magic_name__ = args[0] if args else None
def __iter__( self : int ) -> Tuple:
return iter(self._iterator )
def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]:
def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument
return
return empty_fn
def __enter__( self : Optional[Any] ) -> Any:
return self
def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict:
return
class UpperCamelCase_ :
"""simple docstring"""
def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]:
if _tqdm_active:
return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase )
else:
return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]:
__magic_name__ = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : str ) -> Any:
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
__magic_name__ : List[Any] =_tqdm_cls()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
return bool(_tqdm_active )
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = True
hf_hub_utils.enable_progress_bars()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = False
hf_hub_utils.disable_progress_bars()
| 664 |
'''simple docstring'''
import torch
from transformers import AutoModel
class UpperCamelCase_ ( torch.nn.Module ):
"""simple docstring"""
def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]:
super(_lowerCamelCase , self ).__init__()
__magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase )
__magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 )
__magic_name__ = torch.nn.Softmax(dim=1 )
def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]:
return self.bert(**_lowerCamelCase ).last_hidden_state
def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict:
return token_embeddings.sum(2 , keepdim=_lowerCamelCase )
def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]:
return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]:
__magic_name__ = W_supports["sizes"].tolist()
__magic_name__ = W_supports["start_token_id"].item()
__magic_name__ = W_supports["end_token_id"].item()
del W_supports["sizes"]
del W_supports["start_token_id"]
del W_supports["end_token_id"]
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = None
__magic_name__ = None
__magic_name__ = W_supports["input_ids"] == start_token_id
__magic_name__ = W_supports["input_ids"] == end_token_id
for i, size in enumerate(_lowerCamelCase ):
if i == 0:
__magic_name__ = 0
else:
__magic_name__ = support_sizes[i - 1]
__magic_name__ = S[s : s + size][start_token_masks[s : s + size]]
__magic_name__ = S[s : s + size][end_token_masks[s : s + size]]
__magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 )
__magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 )
if p_starts is not None:
__magic_name__ = torch.vstack((p_starts, p_start) )
__magic_name__ = torch.vstack((p_ends, p_end) )
else:
__magic_name__ = p_start
__magic_name__ = p_end
return p_starts, p_ends
| 664 | 1 |
'''simple docstring'''
import argparse
import os
from io import BytesIO
from pathlib import Path
import requests
from clip_retrieval.clip_client import ClipClient
from PIL import Image
from tqdm import tqdm
def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
__magic_name__ = 1.5
__magic_name__ = int(factor * num_class_images )
__magic_name__ = ClipClient(
url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCamelCase_ , aesthetic_weight=0.1 )
os.makedirs(F'{class_data_dir}/images' , exist_ok=lowerCamelCase_ )
if len(list(Path(F'{class_data_dir}/images' ).iterdir() ) ) >= num_class_images:
return
while True:
__magic_name__ = client.query(text=lowerCamelCase_ )
if len(lowerCamelCase_ ) >= factor * num_class_images or num_images > 1e4:
break
else:
__magic_name__ = int(factor * num_images )
__magic_name__ = ClipClient(
url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCamelCase_ , aesthetic_weight=0.1 , )
__magic_name__ = 0
__magic_name__ = 0
__magic_name__ = tqdm(desc="downloading real regularization images" , total=lowerCamelCase_ )
with open(F'{class_data_dir}/caption.txt' , "w" ) as fa, open(F'{class_data_dir}/urls.txt' , "w" ) as fa, open(
F'{class_data_dir}/images.txt' , "w" ) as fa:
while total < num_class_images:
__magic_name__ = class_images[count]
count += 1
try:
__magic_name__ = requests.get(images["url"] )
if img.status_code == 200:
__magic_name__ = Image.open(BytesIO(img.content ) )
with open(F'{class_data_dir}/images/{total}.jpg' , "wb" ) as f:
f.write(img.content )
fa.write(images["caption"] + "\n" )
fa.write(images["url"] + "\n" )
fa.write(F'{class_data_dir}/images/{total}.jpg' + "\n" )
total += 1
pbar.update(1 )
else:
continue
except Exception:
continue
return
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = argparse.ArgumentParser("" , add_help=lowerCamelCase_ )
parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCamelCase_ , type=lowerCamelCase_ )
parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCamelCase_ , type=lowerCamelCase_ )
parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCamelCase_ )
return parser.parse_args()
if __name__ == "__main__":
__magic_name__ : List[str] =parse_args()
retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
| 664 |
'''simple docstring'''
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401
deprecate(
'stable diffusion controlnet',
'0.22.0',
'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.',
standard_warn=False,
stacklevel=3,
)
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = get_failure_array(lowerCamelCase_ )
# 2) Step through text searching for pattern
__magic_name__ , __magic_name__ = 0, 0 # index into text, pattern
while i < len(lowerCamelCase_ ):
if pattern[j] == text[i]:
if j == (len(lowerCamelCase_ ) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
__magic_name__ = failure[j - 1]
continue
i += 1
return False
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = [0]
__magic_name__ = 0
__magic_name__ = 1
while j < len(lowerCamelCase_ ):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
__magic_name__ = failure[i - 1]
continue
j += 1
failure.append(lowerCamelCase_ )
return failure
if __name__ == "__main__":
# Test 1)
__magic_name__ : List[str] ='abc1abc12'
__magic_name__ : Tuple ='alskfjaldsabc1abc1abc12k23adsfabcabc'
__magic_name__ : Optional[int] ='alskfjaldsk23adsfabcabc'
assert kmp(pattern, texta) and not kmp(pattern, texta)
# Test 2)
__magic_name__ : str ='ABABX'
__magic_name__ : List[Any] ='ABABZABABYABABX'
assert kmp(pattern, text)
# Test 3)
__magic_name__ : Optional[int] ='AAAB'
__magic_name__ : List[Any] ='ABAAAAAB'
assert kmp(pattern, text)
# Test 4)
__magic_name__ : str ='abcdabcy'
__magic_name__ : str ='abcxabcdabxabcdabcdabcy'
assert kmp(pattern, text)
# Test 5)
__magic_name__ : Union[str, Any] ='aabaabaaa'
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| 664 |
'''simple docstring'''
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ )
__magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ )
__magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ )
__magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"]
if config.model_type == "t5":
__magic_name__ = "SelfAttention"
if config.model_type == "longt5" and config.encoder_attention_type == "local":
__magic_name__ = "LocalSelfAttention"
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = "TransientGlobalSelfAttention"
else:
raise ValueError(
"Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"
" attribute with a value from ['local', 'transient-global]." )
# Encoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
if split_mlp_wi:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_global_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = tax_mlp_layer_norm
__magic_name__ = flax_model_encoder_layer_block
# Only for layer 0:
__magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_global_rel_embedding
# Assigning
__magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"]
__magic_name__ = tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
"scale"
]
# Encoder-Decoder-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]
__magic_name__ = tax_enc_dec_attention_module["key"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["out"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["query"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
# MLP
if split_mlp_wi:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_pre_attention_layer_norm
__magic_name__ = tax_enc_dec_attention_key
__magic_name__ = tax_enc_dec_attention_out
__magic_name__ = tax_enc_dec_attention_query
__magic_name__ = tax_enc_dec_attention_value
__magic_name__ = tax_cross_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = txa_mlp_layer_norm
__magic_name__ = flax_model_decoder_layer_block
# Decoder Normalization
__magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"]
__magic_name__ = txa_decoder_norm
# Only for layer 0:
__magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_decoder_rel_embedding
# Token Embeddings
__magic_name__ = tax_model["target"]["token_embedder"]["embedding"]
__magic_name__ = txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
__magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"]
flax_model.save_pretrained(lowerCamelCase_ )
print("T5X Model was sucessfully converted!" )
if __name__ == "__main__":
__magic_name__ : Optional[Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.'
)
parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.')
parser.add_argument(
'--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.'
)
__magic_name__ : Optional[int] =parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
__magic_name__ : Tuple ={'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : str =['DeiTFeatureExtractor']
__magic_name__ : List[Any] =['DeiTImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : List[Any] =[
'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'DeiTForImageClassification',
'DeiTForImageClassificationWithTeacher',
'DeiTForMaskedImageModeling',
'DeiTModel',
'DeiTPreTrainedModel',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Dict =[
'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFDeiTForImageClassification',
'TFDeiTForImageClassificationWithTeacher',
'TFDeiTForMaskedImageModeling',
'TFDeiTModel',
'TFDeiTPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_deit import DeiTFeatureExtractor
from .image_processing_deit import DeiTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_deit import (
DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
DeiTForImageClassification,
DeiTForImageClassificationWithTeacher,
DeiTForMaskedImageModeling,
DeiTModel,
DeiTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_deit import (
TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDeiTForImageClassification,
TFDeiTForImageClassificationWithTeacher,
TFDeiTForMaskedImageModeling,
TFDeiTModel,
TFDeiTPreTrainedModel,
)
else:
import sys
__magic_name__ : List[str] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class UpperCamelCase_ ( unittest.TestCase , A ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Any:
__magic_name__ = load_tool("text-to-speech" )
self.tool.setup()
def __A ( self : Union[str, Any] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
def __A ( self : List[str] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
| 664 | 1 |
'''simple docstring'''
import os
import tempfile
import unittest
from pathlib import Path
from transformers import AutoConfig, is_torch_available
from transformers.testing_utils import require_torch, torch_device
if is_torch_available():
from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments
@require_torch
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] , _lowerCamelCase : str ) -> Any:
for model_result in results.values():
for batch_size, sequence_length in zip(model_result["bs"] , model_result["ss"] ):
__magic_name__ = model_result["result"][batch_size][sequence_length]
self.assertIsNotNone(_lowerCamelCase )
def __A ( self : str ) -> Dict:
__magic_name__ = "sshleifer/tiny-gpt2"
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase )
__magic_name__ = 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 : str ) -> Union[str, Any]:
__magic_name__ = "sgugger/tiny-distilbert-classification"
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , only_pretrain_model=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase )
__magic_name__ = 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 : Any ) -> Dict:
__magic_name__ = "sshleifer/tiny-gpt2"
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , torchscript=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase )
__magic_name__ = benchmark.run()
self.check_results_dict_not_empty(results.time_inference_result )
self.check_results_dict_not_empty(results.memory_inference_result )
@unittest.skipIf(torch_device == "cpu" , "Cant do half precision" )
def __A ( self : int ) -> Any:
__magic_name__ = "sshleifer/tiny-gpt2"
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , fpaa=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase )
__magic_name__ = 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 : Tuple ) -> Optional[Any]:
__magic_name__ = "sshleifer/tiny-gpt2"
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
# set architectures equal to `None`
__magic_name__ = None
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase , configs=[config] )
__magic_name__ = 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 : Optional[Any] ) -> Any:
__magic_name__ = "sshleifer/tiny-gpt2"
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase )
__magic_name__ = benchmark.run()
self.check_results_dict_not_empty(results.time_train_result )
self.check_results_dict_not_empty(results.memory_train_result )
@unittest.skipIf(torch_device == "cpu" , "Can't do half precision" )
def __A ( self : List[str] ) -> int:
__magic_name__ = "sshleifer/tiny-gpt2"
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_lowerCamelCase , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase )
__magic_name__ = 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 : List[str] ) -> Dict:
__magic_name__ = "sshleifer/tiny-gpt2"
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase , configs=[config] )
__magic_name__ = 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 : int ) -> List[Any]:
__magic_name__ = "sshleifer/tinier_bart"
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase , configs=[config] )
__magic_name__ = 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 : Tuple ) -> Optional[Any]:
__magic_name__ = "sshleifer/tiny-gpt2"
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase , configs=[config] )
__magic_name__ = 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 : List[Any] ) -> List[str]:
__magic_name__ = "sshleifer/tinier_bart"
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase , configs=[config] )
__magic_name__ = 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 : int ) -> int:
__magic_name__ = "sshleifer/tiny-gpt2"
with tempfile.TemporaryDirectory() as tmp_dir:
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , save_to_csv=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_lowerCamelCase , "inf_time.csv" ) , train_memory_csv_file=os.path.join(_lowerCamelCase , "train_mem.csv" ) , inference_memory_csv_file=os.path.join(_lowerCamelCase , "inf_mem.csv" ) , train_time_csv_file=os.path.join(_lowerCamelCase , "train_time.csv" ) , env_info_csv_file=os.path.join(_lowerCamelCase , "env.csv" ) , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase )
benchmark.run()
self.assertTrue(Path(os.path.join(_lowerCamelCase , "inf_time.csv" ) ).exists() )
self.assertTrue(Path(os.path.join(_lowerCamelCase , "train_time.csv" ) ).exists() )
self.assertTrue(Path(os.path.join(_lowerCamelCase , "inf_mem.csv" ) ).exists() )
self.assertTrue(Path(os.path.join(_lowerCamelCase , "train_mem.csv" ) ).exists() )
self.assertTrue(Path(os.path.join(_lowerCamelCase , "env.csv" ) ).exists() )
def __A ( self : Optional[int] ) -> Optional[int]:
__magic_name__ = "sshleifer/tiny-gpt2"
def _check_summary_is_not_empty(_lowerCamelCase : Union[str, Any] ):
self.assertTrue(hasattr(_lowerCamelCase , "sequential" ) )
self.assertTrue(hasattr(_lowerCamelCase , "cumulative" ) )
self.assertTrue(hasattr(_lowerCamelCase , "current" ) )
self.assertTrue(hasattr(_lowerCamelCase , "total" ) )
with tempfile.TemporaryDirectory() as tmp_dir:
__magic_name__ = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_lowerCamelCase , "log.txt" ) , log_print=_lowerCamelCase , trace_memory_line_by_line=_lowerCamelCase , multi_process=_lowerCamelCase , )
__magic_name__ = PyTorchBenchmark(_lowerCamelCase )
__magic_name__ = benchmark.run()
_check_summary_is_not_empty(result.inference_summary )
_check_summary_is_not_empty(result.train_summary )
self.assertTrue(Path(os.path.join(_lowerCamelCase , "log.txt" ) ).exists() )
| 664 |
'''simple docstring'''
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
__magic_name__ : Dict =re.compile('[^A-Za-z_0-9]')
# parameters used in DuplicationIndex
__magic_name__ : int =10
__magic_name__ : Union[str, Any] =2_56
def __snake_case ( lowerCamelCase_ : List[str] ):
'''simple docstring'''
if len(lowerCamelCase_ ) < MIN_NUM_TOKENS:
return None
__magic_name__ = MinHash(num_perm=lowerCamelCase_ )
for token in set(lowerCamelCase_ ):
min_hash.update(token.encode() )
return min_hash
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0}
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *,
_lowerCamelCase : float = 0.85 , ) -> Optional[Any]:
__magic_name__ = duplication_jaccard_threshold
__magic_name__ = NUM_PERM
__magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm )
__magic_name__ = defaultdict(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None:
__magic_name__ = self._index.query(_lowerCamelCase )
if code_key in self._index.keys:
print(f'Duplicate key {code_key}' )
return
self._index.insert(_lowerCamelCase , _lowerCamelCase )
if len(_lowerCamelCase ) > 0:
for base_duplicate in close_duplicates:
if base_duplicate in self._duplicate_clusters:
self._duplicate_clusters[base_duplicate].add(_lowerCamelCase )
break
else:
self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase )
def __A ( self : Union[str, Any] ) -> List[List[Dict]]:
__magic_name__ = []
for base, duplicates in self._duplicate_clusters.items():
__magic_name__ = [base] + list(_lowerCamelCase )
# reformat the cluster to be a list of dict
__magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster]
duplicate_clusters.append(_lowerCamelCase )
return duplicate_clusters
def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None:
__magic_name__ = self.get_duplicate_clusters()
with open(_lowerCamelCase , "w" ) as f:
json.dump(_lowerCamelCase , _lowerCamelCase )
def __snake_case ( lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ , __magic_name__ = element
__magic_name__ = 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 __snake_case ( lowerCamelCase_ : Type[Dataset] ):
'''simple docstring'''
with mp.Pool() as pool:
for data in pool.imap_unordered(
_compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ):
if data is not None:
yield data
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ):
'''simple docstring'''
__magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ )
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ):
di.add(lowerCamelCase_ , lowerCamelCase_ )
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
return di.get_duplicate_clusters()
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = get_tokens(lowerCamelCase_ )
__magic_name__ = get_tokens(lowerCamelCase_ )
return len(tokensa & tokensa ) / len(tokensa | tokensa )
__magic_name__ : List[str] =None
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = []
for elementa in cluster:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
for elementa in extremes:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold:
elementa["copies"] += 1
break
else:
__magic_name__ = 1
extremes.append(lowerCamelCase_ )
return extremes
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
global _shared_dataset
__magic_name__ = dataset
__magic_name__ = []
__magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ )
with mp.Pool() as pool:
for extremes in tqdm(
pool.imap_unordered(
lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ):
extremes_list.append(lowerCamelCase_ )
return extremes_list
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ):
'''simple docstring'''
__magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster}
__magic_name__ = {}
__magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
for extremes in extremes_clusters:
for element in extremes:
__magic_name__ = element
__magic_name__ = duplicate_indices - set(extreme_dict.keys() )
__magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ )
# update duplicate_clusters
for cluster in duplicate_clusters:
for element in cluster:
__magic_name__ = element["base_index"] in extreme_dict
if element["is_extreme"]:
__magic_name__ = extreme_dict[element["base_index"]]["copies"]
print(F'Original dataset size: {len(lowerCamelCase_ )}' )
print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' )
print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Filtered dataset size: {len(lowerCamelCase_ )}' )
return ds_filter, duplicate_clusters
| 664 | 1 |
'''simple docstring'''
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : torch.FloatTensor
class UpperCamelCase_ ( A , A ):
"""simple docstring"""
@register_to_config
def __init__( self : Tuple , _lowerCamelCase : int = 3 , _lowerCamelCase : int = 3 , _lowerCamelCase : Tuple[str] = ("DownEncoderBlock2D",) , _lowerCamelCase : Tuple[str] = ("UpDecoderBlock2D",) , _lowerCamelCase : Tuple[int] = (64,) , _lowerCamelCase : int = 1 , _lowerCamelCase : str = "silu" , _lowerCamelCase : int = 3 , _lowerCamelCase : int = 32 , _lowerCamelCase : int = 2_56 , _lowerCamelCase : int = 32 , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : float = 0.18_215 , _lowerCamelCase : str = "group" , ) -> Dict:
super().__init__()
# pass init params to Encoder
__magic_name__ = Encoder(
in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , down_block_types=_lowerCamelCase , block_out_channels=_lowerCamelCase , layers_per_block=_lowerCamelCase , act_fn=_lowerCamelCase , norm_num_groups=_lowerCamelCase , double_z=_lowerCamelCase , )
__magic_name__ = vq_embed_dim if vq_embed_dim is not None else latent_channels
__magic_name__ = nn.Convad(_lowerCamelCase , _lowerCamelCase , 1 )
__magic_name__ = VectorQuantizer(_lowerCamelCase , _lowerCamelCase , beta=0.25 , remap=_lowerCamelCase , sane_index_shape=_lowerCamelCase )
__magic_name__ = nn.Convad(_lowerCamelCase , _lowerCamelCase , 1 )
# pass init params to Decoder
__magic_name__ = Decoder(
in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , up_block_types=_lowerCamelCase , block_out_channels=_lowerCamelCase , layers_per_block=_lowerCamelCase , act_fn=_lowerCamelCase , norm_num_groups=_lowerCamelCase , norm_type=_lowerCamelCase , )
@apply_forward_hook
def __A ( self : int , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : bool = True ) -> VQEncoderOutput:
__magic_name__ = self.encoder(_lowerCamelCase )
__magic_name__ = self.quant_conv(_lowerCamelCase )
if not return_dict:
return (h,)
return VQEncoderOutput(latents=_lowerCamelCase )
@apply_forward_hook
def __A ( self : Dict , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : bool = False , _lowerCamelCase : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]:
# also go through quantization layer
if not force_not_quantize:
__magic_name__ , __magic_name__ , __magic_name__ = self.quantize(_lowerCamelCase )
else:
__magic_name__ = h
__magic_name__ = self.post_quant_conv(_lowerCamelCase )
__magic_name__ = self.decoder(_lowerCamelCase , quant if self.config.norm_type == "spatial" else None )
if not return_dict:
return (dec,)
return DecoderOutput(sample=_lowerCamelCase )
def __A ( self : Union[str, Any] , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]:
__magic_name__ = sample
__magic_name__ = self.encode(_lowerCamelCase ).latents
__magic_name__ = self.decode(_lowerCamelCase ).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=_lowerCamelCase )
| 664 |
'''simple docstring'''
import argparse
import os
import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn
from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
if version.parse(nlp.__version__) != version.parse('0.8.3'):
raise Exception('requires gluonnlp == 0.8.3')
if version.parse(mx.__version__) != version.parse('1.5.0'):
raise Exception('requires mxnet == 1.5.0')
logging.set_verbosity_info()
__magic_name__ : Optional[int] =logging.get_logger(__name__)
__magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!'
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = {
"attention_cell": "multi_head",
"num_layers": 4,
"units": 1024,
"hidden_size": 768,
"max_length": 512,
"num_heads": 8,
"scaled": True,
"dropout": 0.1,
"use_residual": True,
"embed_size": 1024,
"embed_dropout": 0.1,
"word_embed": None,
"layer_norm_eps": 1e-5,
"token_type_vocab_size": 2,
}
__magic_name__ = bort_4_8_768_1024_hparams
# Let's construct the original Bort model here
# Taken from official BERT implementation, see:
# https://github.com/alexa/bort/blob/master/bort/bort.py
__magic_name__ = BERTEncoder(
attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , )
# Vocab information needs to be fetched first
# It's the same as RoBERTa, so RobertaTokenizer can be used later
__magic_name__ = "openwebtext_ccnews_stories_books_cased"
# Specify download folder to Gluonnlp's vocab
__magic_name__ = os.path.join(get_home_dir() , "models" )
__magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ )
__magic_name__ = nlp.model.BERTModel(
lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , )
original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ )
__magic_name__ = original_bort._collect_params_with_prefix()
# Build our config 🤗
__magic_name__ = {
"architectures": ["BertForMaskedLM"],
"attention_probs_dropout_prob": predefined_args["dropout"],
"hidden_act": "gelu",
"hidden_dropout_prob": predefined_args["dropout"],
"hidden_size": predefined_args["embed_size"],
"initializer_range": 0.02,
"intermediate_size": predefined_args["hidden_size"],
"layer_norm_eps": predefined_args["layer_norm_eps"],
"max_position_embeddings": predefined_args["max_length"],
"model_type": "bort",
"num_attention_heads": predefined_args["num_heads"],
"num_hidden_layers": predefined_args["num_layers"],
"pad_token_id": 1, # 2 = BERT, 1 = RoBERTa
"type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa
"vocab_size": len(lowerCamelCase_ ),
}
__magic_name__ = BertConfig.from_dict(lowerCamelCase_ )
__magic_name__ = BertForMaskedLM(lowerCamelCase_ )
hf_bort_model.eval()
# Parameter mapping table (Gluonnlp to Transformers)
# * denotes layer index
#
# | Gluon Parameter | Transformers Parameter
# | -------------------------------------------------------------- | ----------------------
# | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias`
# | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight`
# | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight`
# | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
# | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight`
# | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight`
# | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias`
# | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight`
# Helper function to convert MXNET Arrays to PyTorch
def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter:
return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) )
# Check param shapes and map new HF param back
def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ):
__magic_name__ = hf_param.shape
__magic_name__ = to_torch(params[gluon_param] )
__magic_name__ = gluon_param.shape
assert (
shape_hf == shape_gluon
), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers'
return gluon_param
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" )
# Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
__magic_name__ = torch.zeros_like(
hf_bort_model.bert.embeddings.token_type_embeddings.weight.data )
for i in range(hf_bort_config.num_hidden_layers ):
__magic_name__ = hf_bort_model.bert.encoder.layer[i]
# self attention
__magic_name__ = layer.attention.self
__magic_name__ = check_and_map_params(
self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' )
__magic_name__ = check_and_map_params(
self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' )
__magic_name__ = check_and_map_params(
self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' )
__magic_name__ = check_and_map_params(
self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' )
__magic_name__ = check_and_map_params(
self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' )
__magic_name__ = check_and_map_params(
self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' )
# self attention output
__magic_name__ = layer.attention.output
__magic_name__ = check_and_map_params(
self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' )
__magic_name__ = check_and_map_params(
self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' )
# intermediate
__magic_name__ = layer.intermediate
__magic_name__ = check_and_map_params(
intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' )
__magic_name__ = check_and_map_params(
intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' )
# output
__magic_name__ = layer.output
__magic_name__ = check_and_map_params(
bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' )
__magic_name__ = check_and_map_params(
bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' )
# Save space and energy 🎄
hf_bort_model.half()
# Compare output of both models
__magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" )
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"]
# Get gluon output
__magic_name__ = mx.nd.array([input_ids] )
__magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] )
# Get Transformer output (save and reload model again)
hf_bort_model.save_pretrained(lowerCamelCase_ )
__magic_name__ = BertModel.from_pretrained(lowerCamelCase_ )
hf_bort_model.eval()
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" )
__magic_name__ = hf_bort_model(**lowerCamelCase_ )[0]
__magic_name__ = output_gluon[0].asnumpy()
__magic_name__ = output_hf[0].detach().numpy()
__magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item()
__magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if success:
print("✔️ Both model do output the same tensors" )
else:
print("❌ Both model do **NOT** output the same tensors" )
print("Absolute difference is:" , lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : int =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
__magic_name__ : Optional[Any] =parser.parse_args()
convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : Any ): # noqa: E741
'''simple docstring'''
__magic_name__ = len(lowerCamelCase_ )
__magic_name__ = 0
__magic_name__ = [0] * n
__magic_name__ = [False] * n
__magic_name__ = [False] * n
def dfs(lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[int] ):
if parent == root:
out_edge_count += 1
__magic_name__ = True
__magic_name__ = at
for to in l[at]:
if to == parent:
pass
elif not visited[to]:
__magic_name__ = dfs(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = min(low[at] , low[to] )
# AP found via bridge
if at < low[to]:
__magic_name__ = True
# AP found via cycle
if at == low[to]:
__magic_name__ = True
else:
__magic_name__ = min(low[at] , lowerCamelCase_ )
return out_edge_count
for i in range(lowerCamelCase_ ):
if not visited[i]:
__magic_name__ = 0
__magic_name__ = dfs(lowerCamelCase_ , lowerCamelCase_ , -1 , lowerCamelCase_ )
__magic_name__ = out_edge_count > 1
for x in range(len(lowerCamelCase_ ) ):
if is_art[x] is True:
print(lowerCamelCase_ )
# Adjacency list of graph
__magic_name__ : List[str] ={
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
3: [2, 4],
4: [3],
5: [2, 6, 8],
6: [5, 7],
7: [6, 8],
8: [5, 7],
}
compute_ap(data)
| 664 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ):
'''simple docstring'''
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive" )
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) )
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1" ) )
for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 | 1 |
'''simple docstring'''
import os
import unittest
from transformers import MobileBertTokenizer, MobileBertTokenizerFast
from transformers.models.bert.tokenization_bert import (
VOCAB_FILES_NAMES,
BasicTokenizer,
WordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = MobileBertTokenizer
UpperCAmelCase__ : int = MobileBertTokenizerFast
UpperCAmelCase__ : int = True
UpperCAmelCase__ : Any = True
UpperCAmelCase__ : str = filter_non_english
UpperCAmelCase__ : Optional[Any] = '''google/mobilebert-uncased'''
def __A ( self : Optional[int] ) -> int:
super().setUp()
__magic_name__ = [
"[UNK]",
"[CLS]",
"[SEP]",
"[PAD]",
"[MASK]",
"want",
"##want",
"##ed",
"wa",
"un",
"runn",
"##ing",
",",
"low",
"lowest",
]
__magic_name__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) )
__magic_name__ = [
(tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped
for tokenizer_def in self.tokenizers_list
]
def __A ( self : List[Any] , _lowerCamelCase : Optional[int] ) -> Dict:
__magic_name__ = "UNwant\u00E9d,running"
__magic_name__ = "unwanted, running"
return input_text, output_text
def __A ( self : str ) -> str:
__magic_name__ = self.tokenizer_class(self.vocab_file )
__magic_name__ = tokenizer.tokenize("UNwant\u00E9d,running" )
self.assertListEqual(_lowerCamelCase , ["un", "##want", "##ed", ",", "runn", "##ing"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [9, 6, 7, 12, 10, 11] )
def __A ( self : Optional[Any] ) -> Optional[int]:
if not self.test_rust_tokenizer:
return
__magic_name__ = self.get_tokenizer()
__magic_name__ = self.get_rust_tokenizer()
__magic_name__ = "UNwant\u00E9d,running"
__magic_name__ = tokenizer.tokenize(_lowerCamelCase )
__magic_name__ = rust_tokenizer.tokenize(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
__magic_name__ = rust_tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = self.get_rust_tokenizer()
__magic_name__ = tokenizer.encode(_lowerCamelCase )
__magic_name__ = rust_tokenizer.encode(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
# With lower casing
__magic_name__ = self.get_tokenizer(do_lower_case=_lowerCamelCase )
__magic_name__ = self.get_rust_tokenizer(do_lower_case=_lowerCamelCase )
__magic_name__ = "UNwant\u00E9d,running"
__magic_name__ = tokenizer.tokenize(_lowerCamelCase )
__magic_name__ = rust_tokenizer.tokenize(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
__magic_name__ = rust_tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = self.get_rust_tokenizer()
__magic_name__ = tokenizer.encode(_lowerCamelCase )
__magic_name__ = rust_tokenizer.encode(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
def __A ( self : List[str] ) -> Dict:
__magic_name__ = BasicTokenizer()
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] )
def __A ( self : Any ) -> Tuple:
__magic_name__ = BasicTokenizer(do_lower_case=_lowerCamelCase )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __A ( self : Any ) -> List[Any]:
__magic_name__ = BasicTokenizer(do_lower_case=_lowerCamelCase , strip_accents=_lowerCamelCase )
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 : Tuple ) -> Any:
__magic_name__ = BasicTokenizer(do_lower_case=_lowerCamelCase , strip_accents=_lowerCamelCase )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __A ( self : Union[str, Any] ) -> str:
__magic_name__ = BasicTokenizer(do_lower_case=_lowerCamelCase )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __A ( self : Tuple ) -> Tuple:
__magic_name__ = BasicTokenizer(do_lower_case=_lowerCamelCase )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] )
def __A ( self : Any ) -> Optional[Any]:
__magic_name__ = BasicTokenizer(do_lower_case=_lowerCamelCase , strip_accents=_lowerCamelCase )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] )
def __A ( self : Tuple ) -> Optional[int]:
__magic_name__ = BasicTokenizer(do_lower_case=_lowerCamelCase , strip_accents=_lowerCamelCase )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] )
def __A ( self : List[str] ) -> Optional[int]:
__magic_name__ = BasicTokenizer(do_lower_case=_lowerCamelCase , never_split=["[UNK]"] )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] )
def __A ( self : Tuple ) -> Optional[int]:
__magic_name__ = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
__magic_name__ = {}
for i, token in enumerate(_lowerCamelCase ):
__magic_name__ = i
__magic_name__ = WordpieceTokenizer(vocab=_lowerCamelCase , 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 : str ) -> Dict:
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 : Union[str, Any] ) -> int:
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 : int ) -> Tuple:
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 : str ) -> Union[str, Any]:
__magic_name__ = self.get_tokenizer()
__magic_name__ = self.get_rust_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(_lowerCamelCase ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] )
self.assertListEqual(
[rust_tokenizer.tokenize(_lowerCamelCase ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] )
@slow
def __A ( self : int ) -> Any:
__magic_name__ = self.tokenizer_class.from_pretrained("google/mobilebert-uncased" )
__magic_name__ = tokenizer.encode("sequence builders" , add_special_tokens=_lowerCamelCase )
__magic_name__ = tokenizer.encode("multi-sequence build" , add_special_tokens=_lowerCamelCase )
__magic_name__ = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase )
__magic_name__ = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase )
assert encoded_sentence == [1_01] + text + [1_02]
assert encoded_pair == [1_01] + text + [1_02] + text_a + [1_02]
def __A ( self : Optional[int] ) -> Optional[Any]:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ):
__magic_name__ = self.rust_tokenizer_class.from_pretrained(_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = f'A, naïve {tokenizer_r.mask_token} AllenNLP sentence.'
__magic_name__ = tokenizer_r.encode_plus(
_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_offsets_mapping=_lowerCamelCase , add_special_tokens=_lowerCamelCase , )
__magic_name__ = tokenizer_r.do_lower_case if hasattr(_lowerCamelCase , "do_lower_case" ) else False
__magic_name__ = (
[
((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 : Tuple ) -> Dict:
__magic_name__ = ["的", "人", "有"]
__magic_name__ = "".join(_lowerCamelCase )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ):
__magic_name__ = True
__magic_name__ = self.tokenizer_class.from_pretrained(_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = self.rust_tokenizer_class.from_pretrained(_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = tokenizer_p.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
__magic_name__ = tokenizer_r.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
__magic_name__ = tokenizer_r.convert_ids_to_tokens(_lowerCamelCase )
__magic_name__ = tokenizer_p.convert_ids_to_tokens(_lowerCamelCase )
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = False
__magic_name__ = self.rust_tokenizer_class.from_pretrained(_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = self.tokenizer_class.from_pretrained(_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = tokenizer_r.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
__magic_name__ = tokenizer_p.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
__magic_name__ = tokenizer_r.convert_ids_to_tokens(_lowerCamelCase )
__magic_name__ = tokenizer_p.convert_ids_to_tokens(_lowerCamelCase )
# it is expected that only the first Chinese character is not preceded by "##".
__magic_name__ = [
f'##{token}' if idx != 0 else token for idx, token in enumerate(_lowerCamelCase )
]
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
| 664 |
'''simple docstring'''
import functools
import logging
import os
import sys
import threading
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
__magic_name__ : Tuple =threading.Lock()
__magic_name__ : Optional[logging.Handler] =None
__magic_name__ : List[str] ={
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
}
__magic_name__ : str =logging.WARNING
__magic_name__ : Any =True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '
F'has to be one of: { ", ".join(log_levels.keys() ) }' )
return _default_log_level
def __snake_case ( ):
'''simple docstring'''
return __name__.split("." )[0]
def __snake_case ( ):
'''simple docstring'''
return logging.getLogger(_get_library_name() )
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
__magic_name__ = logging.StreamHandler() # Set sys.stderr as stream.
__magic_name__ = sys.stderr.flush
# Apply our default configuration to the library root logger.
__magic_name__ = _get_library_root_logger()
library_root_logger.addHandler(_default_handler )
library_root_logger.setLevel(_get_default_logging_level() )
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if not _default_handler:
return
__magic_name__ = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler )
library_root_logger.setLevel(logging.NOTSET )
__magic_name__ = None
def __snake_case ( ):
'''simple docstring'''
return log_levels
def __snake_case ( lowerCamelCase_ : Optional[str] = None ):
'''simple docstring'''
if name is None:
__magic_name__ = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def __snake_case ( lowerCamelCase_ : int ):
'''simple docstring'''
_configure_library_root_logger()
_get_library_root_logger().setLevel(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
__magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" )
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ )
if no_advisory_warnings:
return
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : int =warning_advice
@functools.lru_cache(lowerCamelCase_ )
def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ):
'''simple docstring'''
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : Optional[int] =warning_once
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument
__magic_name__ = args[0] if args else None
def __iter__( self : int ) -> Tuple:
return iter(self._iterator )
def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]:
def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument
return
return empty_fn
def __enter__( self : Optional[Any] ) -> Any:
return self
def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict:
return
class UpperCamelCase_ :
"""simple docstring"""
def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]:
if _tqdm_active:
return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase )
else:
return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]:
__magic_name__ = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : str ) -> Any:
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
__magic_name__ : List[Any] =_tqdm_cls()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
return bool(_tqdm_active )
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = True
hf_hub_utils.enable_progress_bars()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = False
hf_hub_utils.disable_progress_bars()
| 664 | 1 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__magic_name__ : Tuple ={'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Optional[int] =[
'MRA_PRETRAINED_MODEL_ARCHIVE_LIST',
'MraForMaskedLM',
'MraForMultipleChoice',
'MraForQuestionAnswering',
'MraForSequenceClassification',
'MraForTokenClassification',
'MraLayer',
'MraModel',
'MraPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mra import (
MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
MraForMaskedLM,
MraForMultipleChoice,
MraForQuestionAnswering,
MraForSequenceClassification,
MraForTokenClassification,
MraLayer,
MraModel,
MraPreTrainedModel,
)
else:
import sys
__magic_name__ : Optional[int] =_LazyModule(__name__, globals()['__file__'], _import_structure)
| 664 |
'''simple docstring'''
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : str =[
'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST',
'FocalNetForImageClassification',
'FocalNetForMaskedImageModeling',
'FocalNetBackbone',
'FocalNetModel',
'FocalNetPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_focalnet import (
FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST,
FocalNetBackbone,
FocalNetForImageClassification,
FocalNetForMaskedImageModeling,
FocalNetModel,
FocalNetPreTrainedModel,
)
else:
import sys
__magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 | 1 |
'''simple docstring'''
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
__magic_name__ : Dict ={
'return_dict': False,
'output_hidden_states': True,
'output_attentions': True,
'torchscript': True,
'torch_dtype': 'float16',
'use_bfloat16': True,
'tf_legacy_loss': True,
'pruned_heads': {'a': 1},
'tie_word_embeddings': False,
'is_decoder': True,
'cross_attention_hidden_size': 1_28,
'add_cross_attention': True,
'tie_encoder_decoder': True,
'max_length': 50,
'min_length': 3,
'do_sample': True,
'early_stopping': True,
'num_beams': 3,
'num_beam_groups': 3,
'diversity_penalty': 0.5,
'temperature': 2.0,
'top_k': 10,
'top_p': 0.7,
'typical_p': 0.2,
'repetition_penalty': 0.8,
'length_penalty': 0.8,
'no_repeat_ngram_size': 5,
'encoder_no_repeat_ngram_size': 5,
'bad_words_ids': [1, 2, 3],
'num_return_sequences': 3,
'chunk_size_feed_forward': 5,
'output_scores': True,
'return_dict_in_generate': True,
'forced_bos_token_id': 2,
'forced_eos_token_id': 3,
'remove_invalid_values': True,
'architectures': ['BertModel'],
'finetuning_task': 'translation',
'id2label': {0: 'label'},
'label2id': {'label': '0'},
'tokenizer_class': 'BertTokenizerFast',
'prefix': 'prefix',
'bos_token_id': 6,
'pad_token_id': 7,
'eos_token_id': 8,
'sep_token_id': 9,
'decoder_start_token_id': 10,
'exponential_decay_length_penalty': (5, 1.0_1),
'suppress_tokens': [0, 1],
'begin_suppress_tokens': 2,
'task_specific_params': {'translation': 'some_params'},
'problem_type': 'regression',
}
@is_staging_test
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def __A ( cls : Any ) -> Union[str, Any]:
__magic_name__ = TOKEN
HfFolder.save_token(_lowerCamelCase )
@classmethod
def __A ( cls : Any ) -> Tuple:
try:
delete_repo(token=cls._token , repo_id="test-config" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-config-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-config" )
except HTTPError:
pass
def __A ( self : Optional[Any] ) -> Dict:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("test-config" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="test-config" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : str ) -> Optional[int]:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-config-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
_lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : Optional[int] ) -> Union[str, Any]:
CustomConfig.register_for_auto_class()
__magic_name__ = CustomConfig(attribute=42 )
config.push_to_hub("test-dynamic-config" , use_auth_token=self._token )
# This has added the proper auto_map field to the config
self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} )
__magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase )
# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
self.assertEqual(new_config.__class__.__name__ , "CustomConfig" )
self.assertEqual(new_config.attribute , 42 )
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Optional[Any]:
__magic_name__ = GPTaConfig()
# attempt to modify each of int/float/bool/str config records and verify they were updated
__magic_name__ = c.n_embd + 1 # int
__magic_name__ = c.resid_pdrop + 1.0 # float
__magic_name__ = not c.scale_attn_weights # bool
__magic_name__ = c.summary_type + "foo" # str
c.update_from_string(
f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' )
self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" )
self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" )
self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" )
self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" )
def __A ( self : List[Any] ) -> Union[str, Any]:
__magic_name__ = PretrainedConfig()
__magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to addin config_common_kwargs above.
self.assertListEqual(
_lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] )
__magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )]
if len(_lowerCamelCase ) > 0:
raise ValueError(
"The following keys are set with the default values in"
" `test_configuration_common.config_common_kwargs` pick another value for them:"
f' {", ".join(_lowerCamelCase )}.' )
def __A ( self : List[Any] ) -> List[Any]:
with self.assertRaises(_lowerCamelCase ):
# config is in subfolder, the following should not work without specifying the subfolder
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" )
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" )
self.assertIsNotNone(_lowerCamelCase )
def __A ( self : Tuple ) -> int:
# A mock response for an HTTP head request to emulate server down
__magic_name__ = mock.Mock()
__magic_name__ = 5_00
__magic_name__ = {}
__magic_name__ = HTTPError
__magic_name__ = {}
# Download this model to make sure it's in the cache.
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head:
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
def __A ( self : Union[str, Any] ) -> Dict:
# This test is for deprecated behavior and can be removed in v5
__magic_name__ = BertConfig.from_pretrained(
"https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" )
def __A ( self : Dict ) -> Optional[int]:
__magic_name__ = AutoConfig.from_pretrained("bert-base-cased" )
__magic_name__ = ["config.4.0.0.json"]
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(_lowerCamelCase )
__magic_name__ = 2
json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) )
# This should pick the new configuration file as the version of Transformers is > 4.0.0
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
__magic_name__ = ["config.42.0.0.json"]
__magic_name__ = 7_68
configuration.save_pretrained(_lowerCamelCase )
shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) )
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 7_68 )
def __A ( self : Optional[int] ) -> str:
# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
__magic_name__ = "hf-internal-testing/test-two-configs"
import transformers as new_transformers
__magic_name__ = "v4.0.0"
__magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained(
_lowerCamelCase , return_unused_kwargs=_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(_lowerCamelCase , {} )
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
__magic_name__ = "v3.0.0"
__magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(old_configuration.hidden_size , 7_68 )
| 664 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__magic_name__ : Optional[Any] ={
'configuration_longformer': [
'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'LongformerConfig',
'LongformerOnnxConfig',
],
'tokenization_longformer': ['LongformerTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : int =['LongformerTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Dict =[
'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'LongformerForMaskedLM',
'LongformerForMultipleChoice',
'LongformerForQuestionAnswering',
'LongformerForSequenceClassification',
'LongformerForTokenClassification',
'LongformerModel',
'LongformerPreTrainedModel',
'LongformerSelfAttention',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Tuple =[
'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFLongformerForMaskedLM',
'TFLongformerForMultipleChoice',
'TFLongformerForQuestionAnswering',
'TFLongformerForSequenceClassification',
'TFLongformerForTokenClassification',
'TFLongformerModel',
'TFLongformerPreTrainedModel',
'TFLongformerSelfAttention',
]
if TYPE_CHECKING:
from .configuration_longformer import (
LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
LongformerConfig,
LongformerOnnxConfig,
)
from .tokenization_longformer import LongformerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_longformer_fast import LongformerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_longformer import (
LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
LongformerForMaskedLM,
LongformerForMultipleChoice,
LongformerForQuestionAnswering,
LongformerForSequenceClassification,
LongformerForTokenClassification,
LongformerModel,
LongformerPreTrainedModel,
LongformerSelfAttention,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_longformer import (
TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLongformerForMaskedLM,
TFLongformerForMultipleChoice,
TFLongformerForQuestionAnswering,
TFLongformerForSequenceClassification,
TFLongformerForTokenClassification,
TFLongformerModel,
TFLongformerPreTrainedModel,
TFLongformerSelfAttention,
)
else:
import sys
__magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 | 1 |
'''simple docstring'''
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be trained.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''./''' , metadata={'''help''': '''Save dir where model repo is cloned and models updates are saved to.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot-clean-train''' , metadata={'''help''': '''Name or path of training dataset.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot-clean-valid''' , metadata={'''help''': '''Name or path of validation dataset.'''} )
UpperCAmelCase__ : Optional[int] = field(default=2 , metadata={'''help''': '''Batch size for training.'''} )
UpperCAmelCase__ : Optional[int] = field(default=2 , metadata={'''help''': '''Batch size for evaluation.'''} )
UpperCAmelCase__ : Optional[float] = field(default=0.1 , metadata={'''help''': '''Value of weight decay.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=1_0000 , metadata={'''help''': '''Size of buffer used to shuffle streaming dataset.'''} )
UpperCAmelCase__ : Optional[float] = field(default=2e-4 , metadata={'''help''': '''Learning rate fo training.'''} )
UpperCAmelCase__ : Optional[str] = field(default='''cosine''' , metadata={'''help''': '''Learning rate.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=750 , metadata={'''help''': '''Number of warmup steps in the learning rate schedule.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=16 , metadata={'''help''': '''Number of gradient accumulation steps.'''} )
UpperCAmelCase__ : Optional[bool] = field(
default=A , metadata={'''help''': '''Use gradient checkpointing to reduce memory footprint.'''} )
UpperCAmelCase__ : Optional[int] = field(default=5_0000 , metadata={'''help''': '''Maximum number of training steps.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=-1 , metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''} )
UpperCAmelCase__ : Optional[int] = field(default=1024 , metadata={'''help''': '''Sequence lengths used for training.'''} )
UpperCAmelCase__ : Optional[int] = field(default=1 , metadata={'''help''': '''Training seed.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=1024 , metadata={'''help''': '''Interval to save checkpoints. Measured as number of forward passes not training steps.'''} , )
UpperCAmelCase__ : Optional[str] = field(
default=A , metadata={'''help''': '''States path if the training should continue from a checkpoint folder.'''} )
UpperCAmelCase__ : Optional[bool] = field(default=A , metadata={'''help''': '''If True the data is pretokenized.'''} )
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be evaluated.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot-clean-valid''' , metadata={'''help''': '''Name or path of validation dataset.'''} )
UpperCAmelCase__ : Optional[int] = field(default=2 , metadata={'''help''': '''Batch size used for evaluation.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=-1 , metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''} )
UpperCAmelCase__ : Optional[int] = field(default=1024 , metadata={'''help''': '''Length of sequences to be evaluated.'''} )
UpperCAmelCase__ : Optional[int] = field(default=1 , metadata={'''help''': '''Random seed used for evaluation.'''} )
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be evaluated.'''} )
UpperCAmelCase__ : Optional[int] = field(default=A , metadata={'''help''': '''Number of workers used for code evaluation.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=A , metadata={'''help''': '''The number of human-eval tasks to run. If not included all tasks are evaluated.'''} , )
UpperCAmelCase__ : Optional[bool] = field(
default=A , metadata={'''help''': '''Sample from the language model\'s output distribution.'''} )
UpperCAmelCase__ : Optional[float] = field(default=0.2 , metadata={'''help''': '''Sampling temperature used for generation.'''} )
UpperCAmelCase__ : Optional[int] = field(default=256 , metadata={'''help''': '''Maximum number of newly generated tokens.'''} )
UpperCAmelCase__ : Optional[int] = field(default=0 , metadata={'''help''': '''Top-k parameter used for generation.'''} )
UpperCAmelCase__ : Optional[float] = field(default=0.95 , metadata={'''help''': '''Top-p parameter used for nucleus sampling.'''} )
UpperCAmelCase__ : Optional[int] = field(default=10 , metadata={'''help''': '''Number of generations to run in parallel.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=200 , metadata={'''help''': '''Number of completions to generate for each sample.'''} )
UpperCAmelCase__ : Optional[int] = field(default=1 , metadata={'''help''': '''Random seed used for evaluation.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''eval_results.json''' , metadata={'''help''': '''Random seed used for evaluation.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''0''' , metadata={'''help''': '''Allow `code_eval` to execute Python code on machine'''} )
UpperCAmelCase__ : Optional[int] = field(
default=-1 , metadata={
'''help''': (
'''Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive'''
''' number corresponds to which GPU device id to run on.'''
)
} , )
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : Optional[int] = field(
default=A , metadata={
'''help''': '''The number of CPU cores to use for parallel preprocessing. Default uses the maximum available.'''
} , )
UpperCAmelCase__ : Optional[str] = field(
default='''transformersbook/codeparrot''' , metadata={'''help''': '''Folder or name of dataset to process.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot-clean''' , metadata={'''help''': '''Folder to save processed processed dataset.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=10_0000 , metadata={'''help''': '''Number of files to save per JSON output file.'''} )
UpperCAmelCase__ : Optional[str] = field(default='''content''' , metadata={'''help''': '''Column containing text data to process.'''} )
UpperCAmelCase__ : Optional[float] = field(
default=1000 , metadata={'''help''': '''Maximum line length in file, otherwise file is filtered.'''} )
UpperCAmelCase__ : Optional[float] = field(
default=100 , metadata={'''help''': '''Maximum mean line length in file, otherwise file is filtered.'''} )
UpperCAmelCase__ : Optional[float] = field(
default=0.25 , metadata={'''help''': '''Maximum fraction of non-alphanumeric characters, otherwise file is filtered.'''} )
UpperCAmelCase__ : Optional[float] = field(
default=1.5 , metadata={'''help''': '''Minimum character token ratio for the file, otherwise file is filtered.'''} )
UpperCAmelCase__ : Optional[float] = field(
default=0.7 , metadata={'''help''': '''Probability for filtering config, test and uncommon files.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot''' , metadata={'''help''': '''Name or path to the tokenizer.'''} , )
UpperCAmelCase__ : Optional[bool] = field(
default=A , metadata={'''help''': '''If True, near-duplicate samples are removed.'''} )
UpperCAmelCase__ : Optional[float] = field(
default=0.85 , metadata={'''help''': '''Jaccard threshold for near-duplicate samples.'''} )
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : Optional[str] = field(
default='''gpt2''' , metadata={'''help''': '''Base tokenizer to build new tokenizer from.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''transformersbook/codeparrot-train''' , metadata={'''help''': '''Dataset to train tokenizer on.'''} )
UpperCAmelCase__ : Optional[str] = field(default='''content''' , metadata={'''help''': '''Column containing text data to process.'''} )
UpperCAmelCase__ : Optional[int] = field(default=20_0000 , metadata={'''help''': '''Number of examples to train tokenizer on.'''} )
UpperCAmelCase__ : Optional[int] = field(
default=3_2768 , metadata={'''help''': '''Number of examples to train the tokenizer on.'''} )
UpperCAmelCase__ : Optional[str] = field(default='''codeparrot''' , metadata={'''help''': '''Name of new tokenizer.'''} )
UpperCAmelCase__ : Optional[bool] = field(default=A , metadata={'''help''': '''Push saved tokenizer to the hub.'''} )
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot''' , metadata={'''help''': '''Name or path to the tokenizer.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot-clean-train''' , metadata={'''help''': '''Name or path to the dataset to pretokenize.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''tokenized-codeparrot-train''' , metadata={'''help''': '''Repo name of the pretokenized data.'''} )
UpperCAmelCase__ : Optional[int] = field(default=A , metadata={'''help''': '''Number of workers used for code evaluation.'''} )
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : Optional[str] = field(
default='''gpt2-large''' , metadata={'''help''': '''Configuration to use for model initialization.'''} )
UpperCAmelCase__ : Optional[str] = field(
default='''codeparrot/codeparrot''' , metadata={'''help''': '''Tokenizer attached to model.'''} )
UpperCAmelCase__ : Optional[str] = field(default='''codeparrot''' , metadata={'''help''': '''Name of the created model.'''} )
UpperCAmelCase__ : Optional[bool] = field(default=A , metadata={'''help''': '''Push saved tokenizer to the hub.'''} )
| 664 |
'''simple docstring'''
import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'):
__magic_name__ : str ={
'linear': PIL.Image.Resampling.BILINEAR,
'bilinear': PIL.Image.Resampling.BILINEAR,
'bicubic': PIL.Image.Resampling.BICUBIC,
'lanczos': PIL.Image.Resampling.LANCZOS,
'nearest': PIL.Image.Resampling.NEAREST,
}
else:
__magic_name__ : Tuple ={
'linear': PIL.Image.LINEAR,
'bilinear': PIL.Image.BILINEAR,
'bicubic': PIL.Image.BICUBIC,
'lanczos': PIL.Image.LANCZOS,
'nearest': PIL.Image.NEAREST,
}
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = (images / 2 + 0.5).clamp(0 , 1 )
__magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
__magic_name__ = numpy_to_pil(lowerCamelCase_ )
return images
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
if images.ndim == 3:
__magic_name__ = images[None, ...]
__magic_name__ = (images * 255).round().astype("uint8" )
if images.shape[-1] == 1:
# special case for grayscale (single channel) images
__magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images]
else:
__magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images]
return pil_images
| 664 | 1 |
'''simple docstring'''
import string
import numpy
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ):
'''simple docstring'''
return b if a == 0 else greatest_common_divisor(b % a , lowerCamelCase_ )
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : str = string.ascii_uppercase + string.digits
# This cipher takes alphanumerics into account
# i.e. a total of 36 characters
# take x and return x % len(key_string)
UpperCAmelCase__ : List[str] = numpy.vectorize(lambda A : x % 36 )
UpperCAmelCase__ : Optional[int] = numpy.vectorize(A )
def __init__( self : List[str] , _lowerCamelCase : numpy.ndarray ) -> None:
__magic_name__ = self.modulus(_lowerCamelCase ) # mod36 calc's on the encrypt key
self.check_determinant() # validate the determinant of the encryption key
__magic_name__ = encrypt_key.shape[0]
def __A ( self : Union[str, Any] , _lowerCamelCase : str ) -> int:
return self.key_string.index(_lowerCamelCase )
def __A ( self : str , _lowerCamelCase : int ) -> str:
return self.key_string[round(_lowerCamelCase )]
def __A ( self : str ) -> None:
__magic_name__ = round(numpy.linalg.det(self.encrypt_key ) )
if det < 0:
__magic_name__ = det % len(self.key_string )
__magic_name__ = len(self.key_string )
if greatest_common_divisor(_lowerCamelCase , len(self.key_string ) ) != 1:
__magic_name__ = (
f'determinant modular {req_l} of encryption key({det}) '
f'is not co prime w.r.t {req_l}.\nTry another key.'
)
raise ValueError(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : str ) -> str:
__magic_name__ = [char for char in text.upper() if char in self.key_string]
__magic_name__ = chars[-1]
while len(_lowerCamelCase ) % self.break_key != 0:
chars.append(_lowerCamelCase )
return "".join(_lowerCamelCase )
def __A ( self : Optional[int] , _lowerCamelCase : str ) -> str:
__magic_name__ = self.process_text(text.upper() )
__magic_name__ = ""
for i in range(0 , len(_lowerCamelCase ) - self.break_key + 1 , self.break_key ):
__magic_name__ = text[i : i + self.break_key]
__magic_name__ = [self.replace_letters(_lowerCamelCase ) for char in batch]
__magic_name__ = numpy.array([vec] ).T
__magic_name__ = self.modulus(self.encrypt_key.dot(_lowerCamelCase ) ).T.tolist()[
0
]
__magic_name__ = "".join(
self.replace_digits(_lowerCamelCase ) for num in batch_encrypted )
encrypted += encrypted_batch
return encrypted
def __A ( self : Optional[int] ) -> numpy.ndarray:
__magic_name__ = round(numpy.linalg.det(self.encrypt_key ) )
if det < 0:
__magic_name__ = det % len(self.key_string )
__magic_name__ = None
for i in range(len(self.key_string ) ):
if (det * i) % len(self.key_string ) == 1:
__magic_name__ = i
break
__magic_name__ = (
det_inv
* numpy.linalg.det(self.encrypt_key )
* numpy.linalg.inv(self.encrypt_key )
)
return self.to_int(self.modulus(_lowerCamelCase ) )
def __A ( self : List[str] , _lowerCamelCase : str ) -> str:
__magic_name__ = self.make_decrypt_key()
__magic_name__ = self.process_text(text.upper() )
__magic_name__ = ""
for i in range(0 , len(_lowerCamelCase ) - self.break_key + 1 , self.break_key ):
__magic_name__ = text[i : i + self.break_key]
__magic_name__ = [self.replace_letters(_lowerCamelCase ) for char in batch]
__magic_name__ = numpy.array([vec] ).T
__magic_name__ = self.modulus(decrypt_key.dot(_lowerCamelCase ) ).T.tolist()[0]
__magic_name__ = "".join(
self.replace_digits(_lowerCamelCase ) for num in batch_decrypted )
decrypted += decrypted_batch
return decrypted
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = int(input("Enter the order of the encryption key: " ) )
__magic_name__ = []
print("Enter each row of the encryption key with space separated integers" )
for _ in range(lowerCamelCase_ ):
__magic_name__ = [int(lowerCamelCase_ ) for x in input().split()]
hill_matrix.append(lowerCamelCase_ )
__magic_name__ = HillCipher(numpy.array(lowerCamelCase_ ) )
print("Would you like to encrypt or decrypt some text? (1 or 2)" )
__magic_name__ = input("\n1. Encrypt\n2. Decrypt\n" )
if option == "1":
__magic_name__ = input("What text would you like to encrypt?: " )
print("Your encrypted text is:" )
print(hc.encrypt(lowerCamelCase_ ) )
elif option == "2":
__magic_name__ = input("What text would you like to decrypt?: " )
print("Your decrypted text is:" )
print(hc.decrypt(lowerCamelCase_ ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 664 |
'''simple docstring'''
from typing import Dict
import numpy as np
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException
if is_tf_available():
import tensorflow as tf
from ..tf_utils import stable_softmax
if is_torch_available():
import torch
__magic_name__ : Optional[Any] =logging.get_logger(__name__)
@add_end_docstrings(
A , r'''
top_k (`int`, defaults to 5):
The number of predictions to return.
targets (`str` or `List[str]`, *optional*):
When passed, the model will limit the scores to the passed targets instead of looking up in the whole
vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
token will be used (with a warning, and that might be slower).
''' , )
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray:
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
elif self.framework == "pt":
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase )
else:
raise ValueError("Unsupported framework" )
return masked_index
def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray:
__magic_name__ = self.get_masked_index(_lowerCamelCase )
__magic_name__ = np.prod(masked_index.shape )
if numel < 1:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , )
def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
for model_input in model_inputs:
self._ensure_exactly_one_mask_token(model_input["input_ids"][0] )
else:
for input_ids in model_inputs["input_ids"]:
self._ensure_exactly_one_mask_token(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]:
if return_tensors is None:
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase )
self.ensure_exactly_one_mask_token(_lowerCamelCase )
return model_inputs
def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]:
__magic_name__ = self.model(**_lowerCamelCase )
__magic_name__ = model_inputs["input_ids"]
return model_outputs
def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict:
# Cap top_k if there are targets
if target_ids is not None and target_ids.shape[0] < top_k:
__magic_name__ = target_ids.shape[0]
__magic_name__ = model_outputs["input_ids"][0]
__magic_name__ = model_outputs["logits"]
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]
__magic_name__ = outputs.numpy()
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 )
if target_ids is not None:
__magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) )
__magic_name__ = tf.expand_dims(_lowerCamelCase , 0 )
__magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase )
__magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy()
else:
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 )
# Fill mask pipeline supports only one ${mask_token} per sample
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = logits.softmax(dim=-1 )
if target_ids is not None:
__magic_name__ = probs[..., target_ids]
__magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase )
__magic_name__ = []
__magic_name__ = values.shape[0] == 1
for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ):
__magic_name__ = []
for v, p in zip(_values , _predictions ):
# Copy is important since we're going to modify this array in place
__magic_name__ = input_ids.numpy().copy()
if target_ids is not None:
__magic_name__ = target_ids[p].tolist()
__magic_name__ = p
# Filter padding out:
__magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )]
# Originally we skip special tokens to give readable output.
# For multi masks though, the other [MASK] would be removed otherwise
# making the output look odd, so we add them back
__magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase )
__magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence}
row.append(_lowerCamelCase )
result.append(_lowerCamelCase )
if single_mask:
return result[0]
return result
def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = [targets]
try:
__magic_name__ = self.tokenizer.get_vocab()
except Exception:
__magic_name__ = {}
__magic_name__ = []
for target in targets:
__magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase )
if id_ is None:
__magic_name__ = self.tokenizer(
_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"]
if len(_lowerCamelCase ) == 0:
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
"We cannot replace it with anything meaningful, ignoring it" )
continue
__magic_name__ = input_ids[0]
# XXX: If users encounter this pass
# it becomes pretty slow, so let's make sure
# The warning enables them to fix the input to
# get faster performance.
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' )
target_ids.append(id_ )
__magic_name__ = list(set(_lowerCamelCase ) )
if len(_lowerCamelCase ) == 0:
raise ValueError("At least one target must be provided when passed." )
__magic_name__ = np.array(_lowerCamelCase )
return target_ids
def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple:
__magic_name__ = {}
if targets is not None:
__magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = target_ids
if top_k is not None:
__magic_name__ = top_k
if self.tokenizer.mask_token_id is None:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." )
return {}, {}, postprocess_params
def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]:
__magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase )
if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1:
return outputs[0]
return outputs
| 664 | 1 |
'''simple docstring'''
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.:
# python ./utils/get_modified_files.py utils src tests examples
#
# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered
# since the output of this script is fed into Makefile commands it doesn't print a newline after the results
import re
import subprocess
import sys
__magic_name__ : List[str] =subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8')
__magic_name__ : str =subprocess.check_output(F'''git diff --name-only {fork_point_sha}'''.split()).decode('utf-8').split()
__magic_name__ : Optional[int] ='|'.join(sys.argv[1:])
__magic_name__ : Optional[int] =re.compile(RF'''^({joined_dirs}).*?\.py$''')
__magic_name__ : Union[str, Any] =[x for x in modified_files if regex.match(x)]
print(' '.join(relevant_modified_files), end='')
| 664 |
'''simple docstring'''
from __future__ import annotations
def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ):
'''simple docstring'''
if len(lowerCamelCase_ ) < k or k < 0:
raise ValueError("Invalid Input" )
__magic_name__ = __magic_name__ = sum(array[:k] )
for i in range(len(lowerCamelCase_ ) - k ):
__magic_name__ = current_sum - array[i] + array[i + k]
__magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ )
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
__magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)]
__magic_name__ : List[str] =randint(0, 1_10)
print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
| 664 | 1 |
'''simple docstring'''
import re
import string
from collections import Counter
import sacrebleu
import sacremoses
from packaging import version
import datasets
__magic_name__ : List[str] ='\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n journal = {Transactions of the Association for Computational Linguistics},\n volume = {4},\n year={2016},\n url = {https://www.aclweb.org/anthology/Q16-1029},\n pages = {401--415\n},\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n'
__magic_name__ : List[str] ='\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n'
__magic_name__ : str ='\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n sources: list of source sentences where each sentence should be a string.\n predictions: list of predicted sentences where each sentence should be a string.\n references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n sari: sari score\n sacrebleu: sacrebleu score\n exact: exact score\n\nExamples:\n >>> sources=["About 95 species are currently accepted ."]\n >>> predictions=["About 95 you now get in ."]\n >>> references=[["About 95 species are currently known ."]]\n >>> wiki_split = datasets.load_metric("wiki_split")\n >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n >>> print(results)\n {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}\n'
def __snake_case ( lowerCamelCase_ : Any ):
'''simple docstring'''
def remove_articles(lowerCamelCase_ : Dict ):
__magic_name__ = re.compile(R"\b(a|an|the)\b" , re.UNICODE )
return re.sub(lowerCamelCase_ , " " , lowerCamelCase_ )
def white_space_fix(lowerCamelCase_ : Union[str, Any] ):
return " ".join(text.split() )
def remove_punc(lowerCamelCase_ : str ):
__magic_name__ = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowerCamelCase_ : Tuple ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_ ) ) ) )
def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : str ):
'''simple docstring'''
return int(normalize_answer(lowerCamelCase_ ) == normalize_answer(lowerCamelCase_ ) )
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = [any(compute_exact(lowerCamelCase_ , lowerCamelCase_ ) for ref in refs ) for pred, refs in zip(lowerCamelCase_ , lowerCamelCase_ )]
return (sum(lowerCamelCase_ ) / len(lowerCamelCase_ )) * 100
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : int , lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
__magic_name__ = [rgram for rgrams in rgramslist for rgram in rgrams]
__magic_name__ = Counter(lowerCamelCase_ )
__magic_name__ = Counter(lowerCamelCase_ )
__magic_name__ = Counter()
for sgram, scount in sgramcounter.items():
__magic_name__ = scount * numref
__magic_name__ = Counter(lowerCamelCase_ )
__magic_name__ = Counter()
for cgram, ccount in cgramcounter.items():
__magic_name__ = ccount * numref
# KEEP
__magic_name__ = sgramcounter_rep & cgramcounter_rep
__magic_name__ = keepgramcounter_rep & rgramcounter
__magic_name__ = sgramcounter_rep & rgramcounter
__magic_name__ = 0
__magic_name__ = 0
for keepgram in keepgramcountergood_rep:
keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
# Fix an alleged bug [2] in the keep score computation.
# keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
keeptmpscorea += keepgramcountergood_rep[keepgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__magic_name__ = 1
__magic_name__ = 1
if len(lowerCamelCase_ ) > 0:
__magic_name__ = keeptmpscorea / len(lowerCamelCase_ )
if len(lowerCamelCase_ ) > 0:
# Fix an alleged bug [2] in the keep score computation.
# keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
__magic_name__ = keeptmpscorea / sum(keepgramcounterall_rep.values() )
__magic_name__ = 0
if keepscore_precision > 0 or keepscore_recall > 0:
__magic_name__ = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)
# DELETION
__magic_name__ = sgramcounter_rep - cgramcounter_rep
__magic_name__ = delgramcounter_rep - rgramcounter
__magic_name__ = sgramcounter_rep - rgramcounter
__magic_name__ = 0
__magic_name__ = 0
for delgram in delgramcountergood_rep:
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__magic_name__ = 1
if len(lowerCamelCase_ ) > 0:
__magic_name__ = deltmpscorea / len(lowerCamelCase_ )
# ADDITION
__magic_name__ = set(lowerCamelCase_ ) - set(lowerCamelCase_ )
__magic_name__ = set(lowerCamelCase_ ) & set(lowerCamelCase_ )
__magic_name__ = set(lowerCamelCase_ ) - set(lowerCamelCase_ )
__magic_name__ = 0
for addgram in addgramcountergood:
addtmpscore += 1
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__magic_name__ = 1
__magic_name__ = 1
if len(lowerCamelCase_ ) > 0:
__magic_name__ = addtmpscore / len(lowerCamelCase_ )
if len(lowerCamelCase_ ) > 0:
__magic_name__ = addtmpscore / len(lowerCamelCase_ )
__magic_name__ = 0
if addscore_precision > 0 or addscore_recall > 0:
__magic_name__ = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)
return (keepscore, delscore_precision, addscore)
def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str] ):
'''simple docstring'''
__magic_name__ = len(lowerCamelCase_ )
__magic_name__ = ssent.split(" " )
__magic_name__ = csent.split(" " )
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
for rsent in rsents:
__magic_name__ = rsent.split(" " )
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
ragramslist.append(lowerCamelCase_ )
for i in range(0 , len(lowerCamelCase_ ) - 1 ):
if i < len(lowerCamelCase_ ) - 1:
__magic_name__ = ragrams[i] + " " + ragrams[i + 1]
ragrams.append(lowerCamelCase_ )
if i < len(lowerCamelCase_ ) - 2:
__magic_name__ = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2]
ragrams.append(lowerCamelCase_ )
if i < len(lowerCamelCase_ ) - 3:
__magic_name__ = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3]
ragrams.append(lowerCamelCase_ )
ragramslist.append(lowerCamelCase_ )
ragramslist.append(lowerCamelCase_ )
ragramslist.append(lowerCamelCase_ )
for i in range(0 , len(lowerCamelCase_ ) - 1 ):
if i < len(lowerCamelCase_ ) - 1:
__magic_name__ = sagrams[i] + " " + sagrams[i + 1]
sagrams.append(lowerCamelCase_ )
if i < len(lowerCamelCase_ ) - 2:
__magic_name__ = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2]
sagrams.append(lowerCamelCase_ )
if i < len(lowerCamelCase_ ) - 3:
__magic_name__ = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3]
sagrams.append(lowerCamelCase_ )
for i in range(0 , len(lowerCamelCase_ ) - 1 ):
if i < len(lowerCamelCase_ ) - 1:
__magic_name__ = cagrams[i] + " " + cagrams[i + 1]
cagrams.append(lowerCamelCase_ )
if i < len(lowerCamelCase_ ) - 2:
__magic_name__ = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2]
cagrams.append(lowerCamelCase_ )
if i < len(lowerCamelCase_ ) - 3:
__magic_name__ = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3]
cagrams.append(lowerCamelCase_ )
((__magic_name__) , (__magic_name__) , (__magic_name__)) = SARIngram(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
((__magic_name__) , (__magic_name__) , (__magic_name__)) = SARIngram(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
((__magic_name__) , (__magic_name__) , (__magic_name__)) = SARIngram(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
((__magic_name__) , (__magic_name__) , (__magic_name__)) = SARIngram(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = sum([keepascore, keepascore, keepascore, keepascore] ) / 4
__magic_name__ = sum([delascore, delascore, delascore, delascore] ) / 4
__magic_name__ = sum([addascore, addascore, addascore, addascore] ) / 4
__magic_name__ = (avgkeepscore + avgdelscore + avgaddscore) / 3
return finalscore
def __snake_case ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : bool = True , lowerCamelCase_ : str = "13a" , lowerCamelCase_ : bool = True ):
'''simple docstring'''
if lowercase:
__magic_name__ = sentence.lower()
if tokenizer in ["13a", "intl"]:
if version.parse(sacrebleu.__version__ ).major >= 2:
__magic_name__ = sacrebleu.metrics.bleu._get_tokenizer(lowerCamelCase_ )()(lowerCamelCase_ )
else:
__magic_name__ = sacrebleu.TOKENIZERS[tokenizer]()(lowerCamelCase_ )
elif tokenizer == "moses":
__magic_name__ = sacremoses.MosesTokenizer().tokenize(lowerCamelCase_ , return_str=lowerCamelCase_ , escape=lowerCamelCase_ )
elif tokenizer == "penn":
__magic_name__ = sacremoses.MosesTokenizer().penn_tokenize(lowerCamelCase_ , return_str=lowerCamelCase_ )
else:
__magic_name__ = sentence
if not return_str:
__magic_name__ = normalized_sent.split()
return normalized_sent
def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : List[str] ):
'''simple docstring'''
if not (len(lowerCamelCase_ ) == len(lowerCamelCase_ ) == len(lowerCamelCase_ )):
raise ValueError("Sources length must match predictions and references lengths." )
__magic_name__ = 0
for src, pred, refs in zip(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ):
sari_score += SARIsent(normalize(lowerCamelCase_ ) , normalize(lowerCamelCase_ ) , [normalize(lowerCamelCase_ ) for sent in refs] )
__magic_name__ = sari_score / len(lowerCamelCase_ )
return 100 * sari_score
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : int , lowerCamelCase_ : List[str]="exp" , lowerCamelCase_ : Optional[Any]=None , lowerCamelCase_ : Optional[Any]=False , lowerCamelCase_ : int=False , lowerCamelCase_ : Dict=False , ):
'''simple docstring'''
__magic_name__ = len(references[0] )
if any(len(lowerCamelCase_ ) != references_per_prediction for refs in references ):
raise ValueError("Sacrebleu requires the same number of references for each prediction" )
__magic_name__ = [[refs[i] for refs in references] for i in range(lowerCamelCase_ )]
__magic_name__ = sacrebleu.corpus_bleu(
lowerCamelCase_ , lowerCamelCase_ , smooth_method=lowerCamelCase_ , smooth_value=lowerCamelCase_ , force=lowerCamelCase_ , lowercase=lowerCamelCase_ , use_effective_order=lowerCamelCase_ , )
return output.score
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class UpperCamelCase_ ( datasets.Metric ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> str:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Value("string" , id="sequence" ),
"references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ),
} ) , codebase_urls=[
"https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py",
"https://github.com/cocoxu/simplification/blob/master/SARI.py",
"https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py",
"https://github.com/mjpost/sacreBLEU",
] , reference_urls=[
"https://www.aclweb.org/anthology/Q16-1029.pdf",
"https://github.com/mjpost/sacreBLEU",
"https://en.wikipedia.org/wiki/BLEU",
"https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
] , )
def __A ( self : List[str] , _lowerCamelCase : Dict , _lowerCamelCase : int , _lowerCamelCase : List[str] ) -> List[str]:
__magic_name__ = {}
result.update({"sari": compute_sari(sources=_lowerCamelCase , predictions=_lowerCamelCase , references=_lowerCamelCase )} )
result.update({"sacrebleu": compute_sacrebleu(predictions=_lowerCamelCase , references=_lowerCamelCase )} )
result.update({"exact": compute_em(predictions=_lowerCamelCase , references=_lowerCamelCase )} )
return result
| 664 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__magic_name__ : int =logging.get_logger(__name__)
__magic_name__ : List[Any] ={}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : int = '''llama'''
UpperCAmelCase__ : Any = ['''past_key_values''']
def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any:
__magic_name__ = vocab_size
__magic_name__ = max_position_embeddings
__magic_name__ = hidden_size
__magic_name__ = intermediate_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
__magic_name__ = num_attention_heads
__magic_name__ = num_key_value_heads
__magic_name__ = hidden_act
__magic_name__ = initializer_range
__magic_name__ = rms_norm_eps
__magic_name__ = pretraining_tp
__magic_name__ = use_cache
__magic_name__ = rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , )
def __A ( self : Union[str, Any] ) -> List[Any]:
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2:
raise ValueError(
"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
f'got {self.rope_scaling}' )
__magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase )
__magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' )
if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0:
raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
| 664 | 1 |
'''simple docstring'''
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCamelCase : int , _lowerCamelCase : Dict=None , _lowerCamelCase : Optional[Any]=None ) -> List[str]:
__magic_name__ = data
__magic_name__ = previous
__magic_name__ = next_node
def __str__( self : Tuple ) -> str:
return f'{self.data}'
def __A ( self : Any ) -> int:
return self.data
def __A ( self : List[Any] ) -> Any:
return self.next
def __A ( self : int ) -> int:
return self.previous
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Dict , _lowerCamelCase : str ) -> Optional[Any]:
__magic_name__ = head
def __iter__( self : Optional[Any] ) -> Optional[int]:
return self
def __A ( self : Any ) -> List[Any]:
if not self.current:
raise StopIteration
else:
__magic_name__ = self.current.get_data()
__magic_name__ = self.current.get_next()
return value
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Dict ) -> Tuple:
__magic_name__ = None # First node in list
__magic_name__ = None # Last node in list
def __str__( self : int ) -> Any:
__magic_name__ = self.head
__magic_name__ = []
while current is not None:
nodes.append(current.get_data() )
__magic_name__ = current.get_next()
return " ".join(str(_lowerCamelCase ) for node in nodes )
def __contains__( self : str , _lowerCamelCase : int ) -> List[Any]:
__magic_name__ = self.head
while current:
if current.get_data() == value:
return True
__magic_name__ = current.get_next()
return False
def __iter__( self : Union[str, Any] ) -> str:
return LinkedListIterator(self.head )
def __A ( self : Dict ) -> Optional[Any]:
if self.head:
return self.head.get_data()
return None
def __A ( self : Union[str, Any] ) -> List[Any]:
if self.tail:
return self.tail.get_data()
return None
def __A ( self : Dict , _lowerCamelCase : Node ) -> None:
if self.head is None:
__magic_name__ = node
__magic_name__ = node
else:
self.insert_before_node(self.head , _lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : Node ) -> None:
if self.head is None:
self.set_head(_lowerCamelCase )
else:
self.insert_after_node(self.tail , _lowerCamelCase )
def __A ( self : Dict , _lowerCamelCase : int ) -> None:
__magic_name__ = Node(_lowerCamelCase )
if self.head is None:
self.set_head(_lowerCamelCase )
else:
self.set_tail(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : Node , _lowerCamelCase : Node ) -> None:
__magic_name__ = node
__magic_name__ = node.previous
if node.get_previous() is None:
__magic_name__ = node_to_insert
else:
__magic_name__ = node_to_insert
__magic_name__ = node_to_insert
def __A ( self : int , _lowerCamelCase : Node , _lowerCamelCase : Node ) -> None:
__magic_name__ = node
__magic_name__ = node.next
if node.get_next() is None:
__magic_name__ = node_to_insert
else:
__magic_name__ = node_to_insert
__magic_name__ = node_to_insert
def __A ( self : int , _lowerCamelCase : int , _lowerCamelCase : int ) -> None:
__magic_name__ = 1
__magic_name__ = Node(_lowerCamelCase )
__magic_name__ = self.head
while node:
if current_position == position:
self.insert_before_node(_lowerCamelCase , _lowerCamelCase )
return
current_position += 1
__magic_name__ = node.next
self.insert_after_node(self.tail , _lowerCamelCase )
def __A ( self : Optional[int] , _lowerCamelCase : int ) -> Node:
__magic_name__ = self.head
while node:
if node.get_data() == item:
return node
__magic_name__ = node.get_next()
raise Exception("Node not found" )
def __A ( self : Optional[Any] , _lowerCamelCase : Optional[Any] ) -> List[Any]:
if (node := self.get_node(_lowerCamelCase )) is not None:
if node == self.head:
__magic_name__ = self.head.get_next()
if node == self.tail:
__magic_name__ = self.tail.get_previous()
self.remove_node_pointers(_lowerCamelCase )
@staticmethod
def __A ( _lowerCamelCase : Node ) -> None:
if node.get_next():
__magic_name__ = node.previous
if node.get_previous():
__magic_name__ = node.next
__magic_name__ = None
__magic_name__ = None
def __A ( self : Dict ) -> Optional[Any]:
return self.head is None
def __snake_case ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 |
'''simple docstring'''
__magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1
def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or volume < 0:
raise ValueError("Invalid inputs. Enter positive value." )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume
def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or pressure < 0:
raise ValueError("Invalid inputs. Enter positive value." )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure
if __name__ == "__main__":
from doctest import testmod
testmod()
| 664 | 1 |
'''simple docstring'''
import unittest
import torch
from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class UpperCamelCase_ ( A , A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : List[str] = VQModel
UpperCAmelCase__ : str = '''sample'''
@property
def __A ( self : List[str] , _lowerCamelCase : List[Any]=(32, 32) ) -> str:
__magic_name__ = 4
__magic_name__ = 3
__magic_name__ = floats_tensor((batch_size, num_channels) + sizes ).to(_lowerCamelCase )
return {"sample": image}
@property
def __A ( self : str ) -> int:
return (3, 32, 32)
@property
def __A ( self : List[Any] ) -> Tuple:
return (3, 32, 32)
def __A ( self : Optional[int] ) -> Union[str, Any]:
__magic_name__ = {
"block_out_channels": [32, 64],
"in_channels": 3,
"out_channels": 3,
"down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"],
"up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"],
"latent_channels": 3,
}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def __A ( self : Dict ) -> Tuple:
pass
def __A ( self : str ) -> List[str]:
pass
def __A ( self : Union[str, Any] ) -> Dict:
__magic_name__ , __magic_name__ = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertEqual(len(loading_info["missing_keys"] ) , 0 )
model.to(_lowerCamelCase )
__magic_name__ = model(**self.dummy_input )
assert image is not None, "Make sure output is not None"
def __A ( self : Any ) -> Optional[Any]:
__magic_name__ = VQModel.from_pretrained("fusing/vqgan-dummy" )
model.to(_lowerCamelCase ).eval()
torch.manual_seed(0 )
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0 )
__magic_name__ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size )
__magic_name__ = image.to(_lowerCamelCase )
with torch.no_grad():
__magic_name__ = model(_lowerCamelCase ).sample
__magic_name__ = output[0, -1, -3:, -3:].flatten().cpu()
# fmt: off
__magic_name__ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] )
# fmt: on
self.assertTrue(torch.allclose(_lowerCamelCase , _lowerCamelCase , atol=1e-3 ) )
| 664 |
'''simple docstring'''
import logging
import os
from typing import List, TextIO, Union
from conllu import parse_incr
from utils_ner import InputExample, Split, TokenClassificationTask
__magic_name__ : List[Any] =logging.getLogger(__name__)
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]:
# in NER datasets, the last column is usually reserved for NER label
__magic_name__ = label_idx
def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = mode.value
__magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' )
__magic_name__ = 1
__magic_name__ = []
with open(_lowerCamelCase , encoding="utf-8" ) as f:
__magic_name__ = []
__magic_name__ = []
for line in f:
if line.startswith("-DOCSTART-" ) or line == "" or line == "\n":
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
guid_index += 1
__magic_name__ = []
__magic_name__ = []
else:
__magic_name__ = line.split(" " )
words.append(splits[0] )
if len(_lowerCamelCase ) > 1:
labels.append(splits[self.label_idx].replace("\n" , "" ) )
else:
# Examples could have no label for mode = "test"
labels.append("O" )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
return examples
def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]:
__magic_name__ = 0
for line in test_input_reader:
if line.startswith("-DOCSTART-" ) or line == "" or line == "\n":
writer.write(_lowerCamelCase )
if not preds_list[example_id]:
example_id += 1
elif preds_list[example_id]:
__magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n"
writer.write(_lowerCamelCase )
else:
logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] )
def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
__magic_name__ = f.read().splitlines()
if "O" not in labels:
__magic_name__ = ["O"] + labels
return labels
else:
return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : int ) -> str:
# in CONLL2003 dataset chunk column is second-to-last
super().__init__(label_idx=-2 )
def __A ( self : int , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
__magic_name__ = f.read().splitlines()
if "O" not in labels:
__magic_name__ = ["O"] + labels
return labels
else:
return [
"O",
"B-ADVP",
"B-INTJ",
"B-LST",
"B-PRT",
"B-NP",
"B-SBAR",
"B-VP",
"B-ADJP",
"B-CONJP",
"B-PP",
"I-ADVP",
"I-INTJ",
"I-LST",
"I-PRT",
"I-NP",
"I-SBAR",
"I-VP",
"I-ADJP",
"I-CONJP",
"I-PP",
]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = mode.value
__magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' )
__magic_name__ = 1
__magic_name__ = []
with open(_lowerCamelCase , encoding="utf-8" ) as f:
for sentence in parse_incr(_lowerCamelCase ):
__magic_name__ = []
__magic_name__ = []
for token in sentence:
words.append(token["form"] )
labels.append(token["upos"] )
assert len(_lowerCamelCase ) == len(_lowerCamelCase )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
guid_index += 1
return examples
def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any:
__magic_name__ = 0
for sentence in parse_incr(_lowerCamelCase ):
__magic_name__ = preds_list[example_id]
__magic_name__ = ""
for token in sentence:
out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) '
out += "\n"
writer.write(_lowerCamelCase )
example_id += 1
def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
return f.read().splitlines()
else:
return [
"ADJ",
"ADP",
"ADV",
"AUX",
"CCONJ",
"DET",
"INTJ",
"NOUN",
"NUM",
"PART",
"PRON",
"PROPN",
"PUNCT",
"SCONJ",
"SYM",
"VERB",
"X",
]
| 664 | 1 |
'''simple docstring'''
import argparse
import logging
from collections import namedtuple
import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer # The authors' implementation
from transformers import BertTokenizer
logging.basicConfig(level=logging.INFO)
__magic_name__ : List[Any] =logging.getLogger(__name__)
__magic_name__ : int ='Hello world! cécé herlolip'
__magic_name__ : List[Any] =namedtuple(
'BertAbsConfig',
[
'temp_dir',
'large',
'use_bert_emb',
'finetune_bert',
'encoder',
'share_emb',
'max_pos',
'enc_layers',
'enc_hidden_size',
'enc_heads',
'enc_ff_size',
'enc_dropout',
'dec_layers',
'dec_hidden_size',
'dec_heads',
'dec_ff_size',
'dec_dropout',
],
)
def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ):
'''simple docstring'''
__magic_name__ = BertAbsConfig(
temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , )
__magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage )
__magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ )
original.eval()
__magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) )
new_model.eval()
# -------------------
# Convert the weights
# -------------------
logging.info("convert the model" )
new_model.bert.load_state_dict(original.bert.state_dict() )
new_model.decoder.load_state_dict(original.decoder.state_dict() )
new_model.generator.load_state_dict(original.generator.state_dict() )
# ----------------------------------
# Make sure the outpus are identical
# ----------------------------------
logging.info("Make sure that the models' outputs are identical" )
__magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" )
# prepare the model inputs
__magic_name__ = tokenizer.encode("This is sample éàalj'-." )
encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
__magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." )
decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
# failsafe to make sure the weights reset does not affect the
# loaded weights.
assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0
# forward pass
__magic_name__ = encoder_input_ids
__magic_name__ = decoder_input_ids
__magic_name__ = __magic_name__ = None
__magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = None
# The original model does not apply the geneator layer immediatly but rather in
# the beam search (where it combines softmax + linear layer). Since we already
# apply the softmax in our generation process we only apply the linear layer here.
# We make sure that the outputs of the full stack are identical
__magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = original.generator(lowerCamelCase_ )
__magic_name__ = new_model(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = new_model.generator(lowerCamelCase_ )
__magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if are_identical:
logging.info("all weights are equal up to 1e-3" )
else:
raise ValueError("the weights are different. The new model is likely different from the original one." )
# The model has been saved with torch.save(model) and this is bound to the exact
# directory structure. We save the state_dict instead.
logging.info("saving the model's state dictionary" )
torch.save(
new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" )
if __name__ == "__main__":
__magic_name__ : Dict =argparse.ArgumentParser()
parser.add_argument(
'--bertabs_checkpoint_path',
default=None,
type=str,
required=True,
help='Path the official PyTorch dump.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
required=True,
help='Path to the output PyTorch model.',
)
__magic_name__ : Any =parser.parse_args()
convert_bertabs_checkpoints(
args.bertabs_checkpoint_path,
args.pytorch_dump_folder_path,
)
| 664 |
'''simple docstring'''
from __future__ import annotations
from typing import Any
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None:
__magic_name__ , __magic_name__ = row, column
__magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )]
def __str__( self : Optional[Any] ) -> str:
__magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n'
# Make string identifier
__magic_name__ = 0
for row_vector in self.array:
for obj in row_vector:
__magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) )
__magic_name__ = f'%{max_element_length}s'
# Make string and return
def single_line(_lowerCamelCase : list[float] ) -> str:
nonlocal string_format_identifier
__magic_name__ = "["
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector )
line += "]"
return line
s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array )
return s
def __repr__( self : Optional[int] ) -> str:
return str(self )
def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool:
if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2):
return False
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
return False
else:
return True
def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any:
assert self.validate_indicies(_lowerCamelCase )
return self.array[loc[0]][loc[1]]
def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None:
assert self.validate_indicies(_lowerCamelCase )
__magic_name__ = value
def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix:
assert isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == another.row and self.column == another.column
# Add
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] + another[r, c]
return result
def __neg__( self : int ) -> Matrix:
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = -self[r, c]
return result
def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix:
return self + (-another)
def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix:
if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] * another
return result
elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication
assert self.column == another.row
__magic_name__ = Matrix(self.row , another.column )
for r in range(self.row ):
for c in range(another.column ):
for i in range(self.column ):
result[r, c] += self[r, i] * another[i, c]
return result
else:
__magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})'
raise TypeError(_lowerCamelCase )
def __A ( self : Optional[int] ) -> Matrix:
__magic_name__ = Matrix(self.column , self.row )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c]
return result
def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any:
assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == self.column == u.row == v.row # u, v should be column vector
assert u.column == v.column == 1 # u, v should be column vector
# Calculate
__magic_name__ = v.transpose()
__magic_name__ = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
# Testing
if __name__ == "__main__":
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Matrix(3 , 3 , 0 )
for i in range(3 ):
__magic_name__ = 1
print(F'a^(-1) is {ainv}' )
# u, v
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5
print(F'u is {u}' )
print(F'v is {v}' )
print(F'uv^T is {u * v.transpose()}' )
# Sherman Morrison
print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' )
def __snake_case ( ):
'''simple docstring'''
import doctest
doctest.testmod()
testa()
| 664 | 1 |
'''simple docstring'''
__magic_name__ : Tuple ={'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
__magic_name__ : Union[str, Any] =['a', 'b', 'c', 'd', 'e']
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = start
# add current to visited
visited.append(lowerCamelCase_ )
__magic_name__ = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
__magic_name__ = topological_sort(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
# if all neighbors visited add current to sort
sort.append(lowerCamelCase_ )
# if all vertices haven't been visited select a new one to visit
if len(lowerCamelCase_ ) != len(lowerCamelCase_ ):
for vertice in vertices:
if vertice not in visited:
__magic_name__ = topological_sort(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
# return sort
return sort
if __name__ == "__main__":
__magic_name__ : List[Any] =topological_sort('a', [], [])
print(sort)
| 664 |
'''simple docstring'''
import argparse
import logging
from collections import namedtuple
import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer # The authors' implementation
from transformers import BertTokenizer
logging.basicConfig(level=logging.INFO)
__magic_name__ : List[Any] =logging.getLogger(__name__)
__magic_name__ : int ='Hello world! cécé herlolip'
__magic_name__ : List[Any] =namedtuple(
'BertAbsConfig',
[
'temp_dir',
'large',
'use_bert_emb',
'finetune_bert',
'encoder',
'share_emb',
'max_pos',
'enc_layers',
'enc_hidden_size',
'enc_heads',
'enc_ff_size',
'enc_dropout',
'dec_layers',
'dec_hidden_size',
'dec_heads',
'dec_ff_size',
'dec_dropout',
],
)
def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ):
'''simple docstring'''
__magic_name__ = BertAbsConfig(
temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , )
__magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage )
__magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ )
original.eval()
__magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) )
new_model.eval()
# -------------------
# Convert the weights
# -------------------
logging.info("convert the model" )
new_model.bert.load_state_dict(original.bert.state_dict() )
new_model.decoder.load_state_dict(original.decoder.state_dict() )
new_model.generator.load_state_dict(original.generator.state_dict() )
# ----------------------------------
# Make sure the outpus are identical
# ----------------------------------
logging.info("Make sure that the models' outputs are identical" )
__magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" )
# prepare the model inputs
__magic_name__ = tokenizer.encode("This is sample éàalj'-." )
encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
__magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." )
decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
# failsafe to make sure the weights reset does not affect the
# loaded weights.
assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0
# forward pass
__magic_name__ = encoder_input_ids
__magic_name__ = decoder_input_ids
__magic_name__ = __magic_name__ = None
__magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = None
# The original model does not apply the geneator layer immediatly but rather in
# the beam search (where it combines softmax + linear layer). Since we already
# apply the softmax in our generation process we only apply the linear layer here.
# We make sure that the outputs of the full stack are identical
__magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = original.generator(lowerCamelCase_ )
__magic_name__ = new_model(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = new_model.generator(lowerCamelCase_ )
__magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if are_identical:
logging.info("all weights are equal up to 1e-3" )
else:
raise ValueError("the weights are different. The new model is likely different from the original one." )
# The model has been saved with torch.save(model) and this is bound to the exact
# directory structure. We save the state_dict instead.
logging.info("saving the model's state dictionary" )
torch.save(
new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" )
if __name__ == "__main__":
__magic_name__ : Dict =argparse.ArgumentParser()
parser.add_argument(
'--bertabs_checkpoint_path',
default=None,
type=str,
required=True,
help='Path the official PyTorch dump.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
required=True,
help='Path to the output PyTorch model.',
)
__magic_name__ : Any =parser.parse_args()
convert_bertabs_checkpoints(
args.bertabs_checkpoint_path,
args.pytorch_dump_folder_path,
)
| 664 | 1 |
'''simple docstring'''
import argparse
import json
import os
import numpy as np
import PIL
import requests
import tensorflow.keras.applications.efficientnet as efficientnet
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from tensorflow.keras.preprocessing import image
from transformers import (
EfficientNetConfig,
EfficientNetForImageClassification,
EfficientNetImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
__magic_name__ : Tuple =logging.get_logger(__name__)
__magic_name__ : Optional[int] ={
'b0': efficientnet.EfficientNetBa,
'b1': efficientnet.EfficientNetBa,
'b2': efficientnet.EfficientNetBa,
'b3': efficientnet.EfficientNetBa,
'b4': efficientnet.EfficientNetBa,
'b5': efficientnet.EfficientNetBa,
'b6': efficientnet.EfficientNetBa,
'b7': efficientnet.EfficientNetBa,
}
__magic_name__ : Union[str, Any] ={
'b0': {
'hidden_dim': 12_80,
'width_coef': 1.0,
'depth_coef': 1.0,
'image_size': 2_24,
'dropout_rate': 0.2,
'dw_padding': [],
},
'b1': {
'hidden_dim': 12_80,
'width_coef': 1.0,
'depth_coef': 1.1,
'image_size': 2_40,
'dropout_rate': 0.2,
'dw_padding': [16],
},
'b2': {
'hidden_dim': 14_08,
'width_coef': 1.1,
'depth_coef': 1.2,
'image_size': 2_60,
'dropout_rate': 0.3,
'dw_padding': [5, 8, 16],
},
'b3': {
'hidden_dim': 15_36,
'width_coef': 1.2,
'depth_coef': 1.4,
'image_size': 3_00,
'dropout_rate': 0.3,
'dw_padding': [5, 18],
},
'b4': {
'hidden_dim': 17_92,
'width_coef': 1.4,
'depth_coef': 1.8,
'image_size': 3_80,
'dropout_rate': 0.4,
'dw_padding': [6],
},
'b5': {
'hidden_dim': 20_48,
'width_coef': 1.6,
'depth_coef': 2.2,
'image_size': 4_56,
'dropout_rate': 0.4,
'dw_padding': [13, 27],
},
'b6': {
'hidden_dim': 23_04,
'width_coef': 1.8,
'depth_coef': 2.6,
'image_size': 5_28,
'dropout_rate': 0.5,
'dw_padding': [31],
},
'b7': {
'hidden_dim': 25_60,
'width_coef': 2.0,
'depth_coef': 3.1,
'image_size': 6_00,
'dropout_rate': 0.5,
'dw_padding': [18],
},
}
def __snake_case ( lowerCamelCase_ : List[str] ):
'''simple docstring'''
__magic_name__ = EfficientNetConfig()
__magic_name__ = CONFIG_MAP[model_name]["hidden_dim"]
__magic_name__ = CONFIG_MAP[model_name]["width_coef"]
__magic_name__ = CONFIG_MAP[model_name]["depth_coef"]
__magic_name__ = CONFIG_MAP[model_name]["image_size"]
__magic_name__ = CONFIG_MAP[model_name]["dropout_rate"]
__magic_name__ = CONFIG_MAP[model_name]["dw_padding"]
__magic_name__ = "huggingface/label-files"
__magic_name__ = "imagenet-1k-id2label.json"
__magic_name__ = 1000
__magic_name__ = json.load(open(hf_hub_download(lowerCamelCase_ , lowerCamelCase_ , repo_type="dataset" ) , "r" ) )
__magic_name__ = {int(lowerCamelCase_ ): v for k, v in idalabel.items()}
__magic_name__ = idalabel
__magic_name__ = {v: k for k, v in idalabel.items()}
return config
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = "http://images.cocodataset.org/val2017/000000039769.jpg"
__magic_name__ = Image.open(requests.get(lowerCamelCase_ , stream=lowerCamelCase_ ).raw )
return im
def __snake_case ( lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = CONFIG_MAP[model_name]["image_size"]
__magic_name__ = EfficientNetImageProcessor(
size={"height": size, "width": size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.4785_3944, 0.473_2864, 0.4743_4163] , do_center_crop=lowerCamelCase_ , )
return preprocessor
def __snake_case ( lowerCamelCase_ : Tuple ):
'''simple docstring'''
__magic_name__ = [v.split("_" )[0].split("block" )[1] for v in original_param_names if v.startswith("block" )]
__magic_name__ = sorted(set(lowerCamelCase_ ) )
__magic_name__ = len(lowerCamelCase_ )
__magic_name__ = {b: str(lowerCamelCase_ ) for b, i in zip(lowerCamelCase_ , range(lowerCamelCase_ ) )}
__magic_name__ = []
rename_keys.append(("stem_conv/kernel:0", "embeddings.convolution.weight") )
rename_keys.append(("stem_bn/gamma:0", "embeddings.batchnorm.weight") )
rename_keys.append(("stem_bn/beta:0", "embeddings.batchnorm.bias") )
rename_keys.append(("stem_bn/moving_mean:0", "embeddings.batchnorm.running_mean") )
rename_keys.append(("stem_bn/moving_variance:0", "embeddings.batchnorm.running_var") )
for b in block_names:
__magic_name__ = block_name_mapping[b]
rename_keys.append((F'block{b}_expand_conv/kernel:0', F'encoder.blocks.{hf_b}.expansion.expand_conv.weight') )
rename_keys.append((F'block{b}_expand_bn/gamma:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.weight') )
rename_keys.append((F'block{b}_expand_bn/beta:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.bias') )
rename_keys.append(
(F'block{b}_expand_bn/moving_mean:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_mean') )
rename_keys.append(
(F'block{b}_expand_bn/moving_variance:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_var') )
rename_keys.append(
(F'block{b}_dwconv/depthwise_kernel:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight') )
rename_keys.append((F'block{b}_bn/gamma:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight') )
rename_keys.append((F'block{b}_bn/beta:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias') )
rename_keys.append(
(F'block{b}_bn/moving_mean:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean') )
rename_keys.append(
(F'block{b}_bn/moving_variance:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var') )
rename_keys.append((F'block{b}_se_reduce/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.weight') )
rename_keys.append((F'block{b}_se_reduce/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.bias') )
rename_keys.append((F'block{b}_se_expand/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.weight') )
rename_keys.append((F'block{b}_se_expand/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.bias') )
rename_keys.append(
(F'block{b}_project_conv/kernel:0', F'encoder.blocks.{hf_b}.projection.project_conv.weight') )
rename_keys.append((F'block{b}_project_bn/gamma:0', F'encoder.blocks.{hf_b}.projection.project_bn.weight') )
rename_keys.append((F'block{b}_project_bn/beta:0', F'encoder.blocks.{hf_b}.projection.project_bn.bias') )
rename_keys.append(
(F'block{b}_project_bn/moving_mean:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_mean') )
rename_keys.append(
(F'block{b}_project_bn/moving_variance:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_var') )
rename_keys.append(("top_conv/kernel:0", "encoder.top_conv.weight") )
rename_keys.append(("top_bn/gamma:0", "encoder.top_bn.weight") )
rename_keys.append(("top_bn/beta:0", "encoder.top_bn.bias") )
rename_keys.append(("top_bn/moving_mean:0", "encoder.top_bn.running_mean") )
rename_keys.append(("top_bn/moving_variance:0", "encoder.top_bn.running_var") )
__magic_name__ = {}
for item in rename_keys:
if item[0] in original_param_names:
__magic_name__ = "efficientnet." + item[1]
__magic_name__ = "classifier.weight"
__magic_name__ = "classifier.bias"
return key_mapping
def __snake_case ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int ):
'''simple docstring'''
for key, value in tf_params.items():
if "normalization" in key:
continue
__magic_name__ = key_mapping[key]
if "_conv" in key and "kernel" in key:
__magic_name__ = torch.from_numpy(lowerCamelCase_ ).permute(3 , 2 , 0 , 1 )
elif "depthwise_kernel" in key:
__magic_name__ = torch.from_numpy(lowerCamelCase_ ).permute(2 , 3 , 0 , 1 )
elif "kernel" in key:
__magic_name__ = torch.from_numpy(np.transpose(lowerCamelCase_ ) )
else:
__magic_name__ = torch.from_numpy(lowerCamelCase_ )
# Replace HF parameters with original TF model parameters
assert hf_params[hf_key].shape == new_hf_value.shape
hf_params[hf_key].copy_(lowerCamelCase_ )
@torch.no_grad()
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = model_classes[model_name](
include_top=lowerCamelCase_ , weights="imagenet" , input_tensor=lowerCamelCase_ , input_shape=lowerCamelCase_ , pooling=lowerCamelCase_ , classes=1000 , classifier_activation="softmax" , )
__magic_name__ = original_model.trainable_variables
__magic_name__ = original_model.non_trainable_variables
__magic_name__ = {param.name: param.numpy() for param in tf_params}
for param in tf_non_train_params:
__magic_name__ = param.numpy()
__magic_name__ = list(tf_params.keys() )
# Load HuggingFace model
__magic_name__ = get_efficientnet_config(lowerCamelCase_ )
__magic_name__ = EfficientNetForImageClassification(lowerCamelCase_ ).eval()
__magic_name__ = hf_model.state_dict()
# Create src-to-dst parameter name mapping dictionary
print("Converting parameters..." )
__magic_name__ = rename_keys(lowerCamelCase_ )
replace_params(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
# Initialize preprocessor and preprocess input image
__magic_name__ = convert_image_processor(lowerCamelCase_ )
__magic_name__ = preprocessor(images=prepare_img() , return_tensors="pt" )
# HF model inference
hf_model.eval()
with torch.no_grad():
__magic_name__ = hf_model(**lowerCamelCase_ )
__magic_name__ = outputs.logits.detach().numpy()
# Original model inference
__magic_name__ = False
__magic_name__ = CONFIG_MAP[model_name]["image_size"]
__magic_name__ = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST )
__magic_name__ = image.img_to_array(lowerCamelCase_ )
__magic_name__ = np.expand_dims(lowerCamelCase_ , axis=0 )
__magic_name__ = original_model.predict(lowerCamelCase_ )
# Check whether original and HF model outputs match -> np.allclose
assert np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ), "The predicted logits are not the same."
print("Model outputs match!" )
if save_model:
# Create folder to save model
if not os.path.isdir(lowerCamelCase_ ):
os.mkdir(lowerCamelCase_ )
# Save converted model and image processor
hf_model.save_pretrained(lowerCamelCase_ )
preprocessor.save_pretrained(lowerCamelCase_ )
if push_to_hub:
# Push model and image processor to hub
print(F'Pushing converted {model_name} to the hub...' )
__magic_name__ = F'efficientnet-{model_name}'
preprocessor.push_to_hub(lowerCamelCase_ )
hf_model.push_to_hub(lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : Any =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='b0',
type=str,
help='Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default='hf_model',
type=str,
help='Path to the output PyTorch model directory.',
)
parser.add_argument('--save_model', action='store_true', help='Save model to local')
parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub')
__magic_name__ : Any =parser.parse_args()
convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
| 664 |
'''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.generation import DisjunctiveConstraint
@require_torch
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : List[str] ) -> str:
# For consistency across different places the DisjunctiveConstraint is called,
# dc.token_ids is a list of integers. It is also initialized only by integers.
__magic_name__ = [[1, 2, 4], [1, 2, 3, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] )
def __A ( self : List[Any] ) -> str:
# We can't have constraints that are complete subsets of another. This leads to a preverse
# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
__magic_name__ = [[1, 2], [1, 2, 3, 4]]
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(_lowerCamelCase ) # fails here
def __A ( self : List[Any] ) -> int:
__magic_name__ = [[1, 2, 3], [1, 2, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 )
__magic_name__ = stepped is True and completed is True and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 3] )
def __A ( self : Any ) -> Union[str, Any]:
__magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2, 4] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 4, 5] )
dc.reset()
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 3 )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 2 )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.remaining() == 0 )
self.assertTrue(dc.current_seq == [1, 2, 5] )
| 664 | 1 |
'''simple docstring'''
import os
import pytest
from datasets import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
)
__magic_name__ : List[Any] =pytest.mark.integration
@pytest.mark.parametrize("path" , ["paws", "csv"] )
def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : int ):
'''simple docstring'''
inspect_dataset(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = path + ".py"
assert script_name in os.listdir(lowerCamelCase_ )
assert "__pycache__" not in os.listdir(lowerCamelCase_ )
@pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning" )
@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" )
@pytest.mark.parametrize("path" , ["accuracy"] )
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : str ):
'''simple docstring'''
inspect_metric(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = path + ".py"
assert script_name in os.listdir(lowerCamelCase_ )
assert "__pycache__" not in os.listdir(lowerCamelCase_ )
@pytest.mark.parametrize(
"path, config_name, expected_splits" , [
("squad", "plain_text", ["train", "validation"]),
("dalle-mini/wit", "dalle-mini--wit", ["train"]),
("paws", "labeled_final", ["train", "test", "validation"]),
] , )
def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = get_dataset_config_info(lowerCamelCase_ , config_name=lowerCamelCase_ )
assert info.config_name == config_name
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
"path, config_name, expected_exception" , [
("paws", None, ValueError),
] , )
def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
with pytest.raises(lowerCamelCase_ ):
get_dataset_config_info(lowerCamelCase_ , config_name=lowerCamelCase_ )
@pytest.mark.parametrize(
"path, expected" , [
("squad", "plain_text"),
("acronym_identification", "default"),
("lhoestq/squad", "plain_text"),
("lhoestq/test", "default"),
("lhoestq/demo1", "lhoestq--demo1"),
("dalle-mini/wit", "dalle-mini--wit"),
] , )
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[int] ):
'''simple docstring'''
__magic_name__ = get_dataset_config_names(lowerCamelCase_ )
assert expected in config_names
@pytest.mark.parametrize(
"path, expected_configs, expected_splits_in_first_config" , [
("squad", ["plain_text"], ["train", "validation"]),
("dalle-mini/wit", ["dalle-mini--wit"], ["train"]),
("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]),
] , )
def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : str , lowerCamelCase_ : int ):
'''simple docstring'''
__magic_name__ = get_dataset_infos(lowerCamelCase_ )
assert list(infos.keys() ) == expected_configs
__magic_name__ = expected_configs[0]
assert expected_config in infos
__magic_name__ = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits_in_first_config
@pytest.mark.parametrize(
"path, expected_config, expected_splits" , [
("squad", "plain_text", ["train", "validation"]),
("dalle-mini/wit", "dalle-mini--wit", ["train"]),
("paws", "labeled_final", ["train", "test", "validation"]),
] , )
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] ):
'''simple docstring'''
__magic_name__ = get_dataset_infos(lowerCamelCase_ )
assert expected_config in infos
__magic_name__ = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
"path, config_name, expected_exception" , [
("paws", None, ValueError),
] , )
def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[int] ):
'''simple docstring'''
with pytest.raises(lowerCamelCase_ ):
get_dataset_split_names(lowerCamelCase_ , config_name=lowerCamelCase_ )
| 664 |
'''simple docstring'''
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
__magic_name__ : Dict ={
'return_dict': False,
'output_hidden_states': True,
'output_attentions': True,
'torchscript': True,
'torch_dtype': 'float16',
'use_bfloat16': True,
'tf_legacy_loss': True,
'pruned_heads': {'a': 1},
'tie_word_embeddings': False,
'is_decoder': True,
'cross_attention_hidden_size': 1_28,
'add_cross_attention': True,
'tie_encoder_decoder': True,
'max_length': 50,
'min_length': 3,
'do_sample': True,
'early_stopping': True,
'num_beams': 3,
'num_beam_groups': 3,
'diversity_penalty': 0.5,
'temperature': 2.0,
'top_k': 10,
'top_p': 0.7,
'typical_p': 0.2,
'repetition_penalty': 0.8,
'length_penalty': 0.8,
'no_repeat_ngram_size': 5,
'encoder_no_repeat_ngram_size': 5,
'bad_words_ids': [1, 2, 3],
'num_return_sequences': 3,
'chunk_size_feed_forward': 5,
'output_scores': True,
'return_dict_in_generate': True,
'forced_bos_token_id': 2,
'forced_eos_token_id': 3,
'remove_invalid_values': True,
'architectures': ['BertModel'],
'finetuning_task': 'translation',
'id2label': {0: 'label'},
'label2id': {'label': '0'},
'tokenizer_class': 'BertTokenizerFast',
'prefix': 'prefix',
'bos_token_id': 6,
'pad_token_id': 7,
'eos_token_id': 8,
'sep_token_id': 9,
'decoder_start_token_id': 10,
'exponential_decay_length_penalty': (5, 1.0_1),
'suppress_tokens': [0, 1],
'begin_suppress_tokens': 2,
'task_specific_params': {'translation': 'some_params'},
'problem_type': 'regression',
}
@is_staging_test
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def __A ( cls : Any ) -> Union[str, Any]:
__magic_name__ = TOKEN
HfFolder.save_token(_lowerCamelCase )
@classmethod
def __A ( cls : Any ) -> Tuple:
try:
delete_repo(token=cls._token , repo_id="test-config" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-config-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-config" )
except HTTPError:
pass
def __A ( self : Optional[Any] ) -> Dict:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("test-config" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="test-config" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : str ) -> Optional[int]:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-config-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
_lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : Optional[int] ) -> Union[str, Any]:
CustomConfig.register_for_auto_class()
__magic_name__ = CustomConfig(attribute=42 )
config.push_to_hub("test-dynamic-config" , use_auth_token=self._token )
# This has added the proper auto_map field to the config
self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} )
__magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase )
# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
self.assertEqual(new_config.__class__.__name__ , "CustomConfig" )
self.assertEqual(new_config.attribute , 42 )
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Optional[Any]:
__magic_name__ = GPTaConfig()
# attempt to modify each of int/float/bool/str config records and verify they were updated
__magic_name__ = c.n_embd + 1 # int
__magic_name__ = c.resid_pdrop + 1.0 # float
__magic_name__ = not c.scale_attn_weights # bool
__magic_name__ = c.summary_type + "foo" # str
c.update_from_string(
f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' )
self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" )
self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" )
self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" )
self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" )
def __A ( self : List[Any] ) -> Union[str, Any]:
__magic_name__ = PretrainedConfig()
__magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to addin config_common_kwargs above.
self.assertListEqual(
_lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] )
__magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )]
if len(_lowerCamelCase ) > 0:
raise ValueError(
"The following keys are set with the default values in"
" `test_configuration_common.config_common_kwargs` pick another value for them:"
f' {", ".join(_lowerCamelCase )}.' )
def __A ( self : List[Any] ) -> List[Any]:
with self.assertRaises(_lowerCamelCase ):
# config is in subfolder, the following should not work without specifying the subfolder
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" )
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" )
self.assertIsNotNone(_lowerCamelCase )
def __A ( self : Tuple ) -> int:
# A mock response for an HTTP head request to emulate server down
__magic_name__ = mock.Mock()
__magic_name__ = 5_00
__magic_name__ = {}
__magic_name__ = HTTPError
__magic_name__ = {}
# Download this model to make sure it's in the cache.
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head:
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
def __A ( self : Union[str, Any] ) -> Dict:
# This test is for deprecated behavior and can be removed in v5
__magic_name__ = BertConfig.from_pretrained(
"https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" )
def __A ( self : Dict ) -> Optional[int]:
__magic_name__ = AutoConfig.from_pretrained("bert-base-cased" )
__magic_name__ = ["config.4.0.0.json"]
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(_lowerCamelCase )
__magic_name__ = 2
json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) )
# This should pick the new configuration file as the version of Transformers is > 4.0.0
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
__magic_name__ = ["config.42.0.0.json"]
__magic_name__ = 7_68
configuration.save_pretrained(_lowerCamelCase )
shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) )
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 7_68 )
def __A ( self : Optional[int] ) -> str:
# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
__magic_name__ = "hf-internal-testing/test-two-configs"
import transformers as new_transformers
__magic_name__ = "v4.0.0"
__magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained(
_lowerCamelCase , return_unused_kwargs=_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(_lowerCamelCase , {} )
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
__magic_name__ = "v3.0.0"
__magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(old_configuration.hidden_size , 7_68 )
| 664 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
__magic_name__ : Optional[Any] ={'processing_layoutxlm': ['LayoutXLMProcessor']}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Dict =['LayoutXLMTokenizer']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Dict =['LayoutXLMTokenizerFast']
if TYPE_CHECKING:
from .processing_layoutxlm import LayoutXLMProcessor
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_layoutxlm import LayoutXLMTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast
else:
import sys
__magic_name__ : Optional[int] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision
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 DPTImageProcessor
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict:
__magic_name__ = size if size is not None else {"height": 18, "width": 18}
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = num_channels
__magic_name__ = image_size
__magic_name__ = min_resolution
__magic_name__ = max_resolution
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = do_normalize
__magic_name__ = image_mean
__magic_name__ = image_std
def __A ( self : int ) -> List[str]:
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
@require_torch
@require_vision
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None
def __A ( self : Dict ) -> Any:
__magic_name__ = DPTImageProcessingTester(self )
@property
def __A ( self : str ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : Tuple ) -> List[str]:
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) )
self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "size" ) )
def __A ( self : List[str] ) -> List[Any]:
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"height": 18, "width": 18} )
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {"height": 42, "width": 42} )
def __A ( self : Union[str, Any] ) -> List[str]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Dict ) -> Optional[Any]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Optional[int] ) -> Dict:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
| 664 | 1 |
'''simple docstring'''
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Optional[Any] = ['''image_processor''', '''tokenizer''']
UpperCAmelCase__ : List[str] = '''BlipImageProcessor'''
UpperCAmelCase__ : Tuple = ('''BertTokenizer''', '''BertTokenizerFast''')
def __init__( self : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : str ) -> Union[str, Any]:
__magic_name__ = False
super().__init__(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = self.image_processor
def __call__( self : Union[str, Any] , _lowerCamelCase : ImageInput = None , _lowerCamelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _lowerCamelCase : bool = True , _lowerCamelCase : Union[bool, str, PaddingStrategy] = False , _lowerCamelCase : Union[bool, str, TruncationStrategy] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : int = 0 , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[bool] = None , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = True , _lowerCamelCase : Optional[Union[str, TensorType]] = None , **_lowerCamelCase : str , ) -> BatchEncoding:
if images is None and text is None:
raise ValueError("You have to specify either images or text." )
# Get only text
if images is None:
__magic_name__ = self.tokenizer
__magic_name__ = self.tokenizer(
text=_lowerCamelCase , add_special_tokens=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , stride=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_overflowing_tokens=_lowerCamelCase , return_special_tokens_mask=_lowerCamelCase , return_offsets_mapping=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_length=_lowerCamelCase , verbose=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase , )
return text_encoding
# add pixel_values
__magic_name__ = self.image_processor(_lowerCamelCase , return_tensors=_lowerCamelCase )
if text is not None:
__magic_name__ = self.tokenizer(
text=_lowerCamelCase , add_special_tokens=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , stride=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_overflowing_tokens=_lowerCamelCase , return_special_tokens_mask=_lowerCamelCase , return_offsets_mapping=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_length=_lowerCamelCase , verbose=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase , )
else:
__magic_name__ = None
if text_encoding is not None:
encoding_image_processor.update(_lowerCamelCase )
return encoding_image_processor
def __A ( self : Any , *_lowerCamelCase : List[Any] , **_lowerCamelCase : int ) -> Any:
return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Union[str, Any] , *_lowerCamelCase : int , **_lowerCamelCase : Tuple ) -> Dict:
return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase )
@property
def __A ( self : List[Any] ) -> Optional[int]:
__magic_name__ = self.tokenizer.model_input_names
__magic_name__ = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 664 |
'''simple docstring'''
import numpy
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None:
__magic_name__ = input_array
# Random initial weights are assigned where first argument is the
# number of nodes in previous layer and second argument is the
# number of nodes in the next layer.
# Random initial weights are assigned.
# self.input_array.shape[1] is used to represent number of nodes in input layer.
# First hidden layer consists of 4 nodes.
__magic_name__ = numpy.random.rand(
self.input_array.shape[1] , 4 )
# Random initial values for the first hidden layer.
# First hidden layer has 4 nodes.
# Second hidden layer has 3 nodes.
__magic_name__ = numpy.random.rand(
4 , 3 )
# Random initial values for the second hidden layer.
# Second hidden layer has 3 nodes.
# Output layer has 1 node.
__magic_name__ = numpy.random.rand(3 , 1 )
# Real output values provided.
__magic_name__ = output_array
# Predicted output values by the neural network.
# Predicted_output array initially consists of zeroes.
__magic_name__ = numpy.zeros(output_array.shape )
def __A ( self : int ) -> numpy.ndarray:
__magic_name__ = sigmoid(
numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) )
# layer_between_first_hidden_layer_and_second_hidden_layer is the layer
# connecting the first hidden set of nodes with the second hidden set of nodes.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
# layer_between_second_hidden_layer_and_output is the layer connecting
# second hidden layer with the output node.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return self.layer_between_second_hidden_layer_and_output
def __A ( self : Dict ) -> None:
__magic_name__ = numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , )
__magic_name__ = numpy.dot(
self.layer_between_input_and_first_hidden_layer.T , numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , )
__magic_name__ = numpy.dot(
self.input_array.T , numpy.dot(
numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , )
* sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , )
self.input_layer_and_first_hidden_layer_weights += (
updated_input_layer_and_first_hidden_layer_weights
)
self.first_hidden_layer_and_second_hidden_layer_weights += (
updated_first_hidden_layer_and_second_hidden_layer_weights
)
self.second_hidden_layer_and_output_layer_weights += (
updated_second_hidden_layer_and_output_layer_weights
)
def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None:
for iteration in range(1 , iterations + 1 ):
__magic_name__ = self.feedforward()
self.back_propagation()
if give_loss:
__magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) )
print(f'Iteration {iteration} Loss: {loss}' )
def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int:
__magic_name__ = input_arr
__magic_name__ = sigmoid(
numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return int(self.layer_between_second_hidden_layer_and_output > 0.6 )
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return 1 / (1 + numpy.exp(-value ))
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return (value) * (1 - (value))
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = numpy.array(
(
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
) , dtype=numpy.floataa , )
# True output values for the given input values.
__magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa )
# Calling neural network class.
__magic_name__ = TwoHiddenLayerNeuralNetwork(
input_array=lowerCamelCase_ , output_array=lowerCamelCase_ )
# Calling training function.
# Set give_loss to True if you want to see loss in every iteration.
neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ )
return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) )
if __name__ == "__main__":
example()
| 664 | 1 |
'''simple docstring'''
import math
import random
from typing import Any
from .hill_climbing import SearchProblem
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : bool = True , lowerCamelCase_ : float = math.inf , lowerCamelCase_ : float = -math.inf , lowerCamelCase_ : float = math.inf , lowerCamelCase_ : float = -math.inf , lowerCamelCase_ : bool = False , lowerCamelCase_ : float = 100 , lowerCamelCase_ : float = 0.01 , lowerCamelCase_ : float = 1 , ):
'''simple docstring'''
__magic_name__ = False
__magic_name__ = search_prob
__magic_name__ = start_temperate
__magic_name__ = []
__magic_name__ = 0
__magic_name__ = None
while not search_end:
__magic_name__ = current_state.score()
if best_state is None or current_score > best_state.score():
__magic_name__ = current_state
scores.append(lowerCamelCase_ )
iterations += 1
__magic_name__ = None
__magic_name__ = current_state.get_neighbors()
while (
next_state is None and neighbors
): # till we do not find a neighbor that we can move to
__magic_name__ = random.randint(0 , len(lowerCamelCase_ ) - 1 ) # picking a random neighbor
__magic_name__ = neighbors.pop(lowerCamelCase_ )
__magic_name__ = picked_neighbor.score() - current_score
if (
picked_neighbor.x > max_x
or picked_neighbor.x < min_x
or picked_neighbor.y > max_y
or picked_neighbor.y < min_y
):
continue # neighbor outside our bounds
if not find_max:
__magic_name__ = change * -1 # in case we are finding minimum
if change > 0: # improves the solution
__magic_name__ = picked_neighbor
else:
__magic_name__ = (math.e) ** (
change / current_temp
) # probability generation function
if random.random() < probability: # random number within probability
__magic_name__ = picked_neighbor
__magic_name__ = current_temp - (current_temp * rate_of_decrease)
if current_temp < threshold_temp or next_state is None:
# temperature below threshold, or could not find a suitable neighbor
__magic_name__ = True
else:
__magic_name__ = next_state
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(lowerCamelCase_ ) , lowerCamelCase_ )
plt.xlabel("Iterations" )
plt.ylabel("Function values" )
plt.show()
return best_state
if __name__ == "__main__":
def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
return (x**2) + (y**2)
# starting the problem with initial coordinates (12, 47)
__magic_name__ : Union[str, Any] =SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa)
__magic_name__ : int =simulated_annealing(
prob, find_max=False, max_x=1_00, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 '
F'''and 50 > y > - 5 found via hill climbing: {local_min.score()}'''
)
# starting the problem with initial coordinates (12, 47)
__magic_name__ : List[Any] =SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa)
__magic_name__ : int =simulated_annealing(
prob, find_max=True, max_x=1_00, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 '
F'''and 50 > y > - 5 found via hill climbing: {local_min.score()}'''
)
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : List[str] ):
'''simple docstring'''
return (3 * x**2) - (6 * y)
__magic_name__ : int =SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa)
__magic_name__ : List[Any] =simulated_annealing(prob, find_max=False, visualization=True)
print(
'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: '
F'''{local_min.score()}'''
)
__magic_name__ : int =SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa)
__magic_name__ : int =simulated_annealing(prob, find_max=True, visualization=True)
print(
'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: '
F'''{local_min.score()}'''
)
| 664 |
'''simple docstring'''
import torch
from transformers import AutoModel
class UpperCamelCase_ ( torch.nn.Module ):
"""simple docstring"""
def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]:
super(_lowerCamelCase , self ).__init__()
__magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase )
__magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 )
__magic_name__ = torch.nn.Softmax(dim=1 )
def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]:
return self.bert(**_lowerCamelCase ).last_hidden_state
def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict:
return token_embeddings.sum(2 , keepdim=_lowerCamelCase )
def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]:
return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]:
__magic_name__ = W_supports["sizes"].tolist()
__magic_name__ = W_supports["start_token_id"].item()
__magic_name__ = W_supports["end_token_id"].item()
del W_supports["sizes"]
del W_supports["start_token_id"]
del W_supports["end_token_id"]
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = None
__magic_name__ = None
__magic_name__ = W_supports["input_ids"] == start_token_id
__magic_name__ = W_supports["input_ids"] == end_token_id
for i, size in enumerate(_lowerCamelCase ):
if i == 0:
__magic_name__ = 0
else:
__magic_name__ = support_sizes[i - 1]
__magic_name__ = S[s : s + size][start_token_masks[s : s + size]]
__magic_name__ = S[s : s + size][end_token_masks[s : s + size]]
__magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 )
__magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 )
if p_starts is not None:
__magic_name__ = torch.vstack((p_starts, p_start) )
__magic_name__ = torch.vstack((p_ends, p_end) )
else:
__magic_name__ = p_start
__magic_name__ = p_end
return p_starts, p_ends
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
from typing import Any
def __snake_case ( lowerCamelCase_ : list ):
'''simple docstring'''
if not postfix_notation:
return 0
__magic_name__ = {"+", "-", "*", "/"}
__magic_name__ = []
for token in postfix_notation:
if token in operations:
__magic_name__ , __magic_name__ = stack.pop(), stack.pop()
if token == "+":
stack.append(a + b )
elif token == "-":
stack.append(a - b )
elif token == "*":
stack.append(a * b )
else:
if a * b < 0 and a % b != 0:
stack.append(a // b + 1 )
else:
stack.append(a // b )
else:
stack.append(int(lowerCamelCase_ ) )
return stack.pop()
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 |
'''simple docstring'''
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401
deprecate(
'stable diffusion controlnet',
'0.22.0',
'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.',
standard_warn=False,
stacklevel=3,
)
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Any ):
'''simple docstring'''
if height >= 1:
move_tower(height - 1 , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
move_disk(lowerCamelCase_ , lowerCamelCase_ )
move_tower(height - 1 , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : Tuple , lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
print("moving disk from" , lowerCamelCase_ , "to" , lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = int(input("Height of hanoi: " ).strip() )
move_tower(lowerCamelCase_ , "A" , "B" , "C" )
if __name__ == "__main__":
main()
| 664 |
'''simple docstring'''
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ )
__magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ )
__magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ )
__magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"]
if config.model_type == "t5":
__magic_name__ = "SelfAttention"
if config.model_type == "longt5" and config.encoder_attention_type == "local":
__magic_name__ = "LocalSelfAttention"
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = "TransientGlobalSelfAttention"
else:
raise ValueError(
"Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"
" attribute with a value from ['local', 'transient-global]." )
# Encoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
if split_mlp_wi:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_global_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = tax_mlp_layer_norm
__magic_name__ = flax_model_encoder_layer_block
# Only for layer 0:
__magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_global_rel_embedding
# Assigning
__magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"]
__magic_name__ = tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
"scale"
]
# Encoder-Decoder-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]
__magic_name__ = tax_enc_dec_attention_module["key"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["out"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["query"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
# MLP
if split_mlp_wi:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_pre_attention_layer_norm
__magic_name__ = tax_enc_dec_attention_key
__magic_name__ = tax_enc_dec_attention_out
__magic_name__ = tax_enc_dec_attention_query
__magic_name__ = tax_enc_dec_attention_value
__magic_name__ = tax_cross_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = txa_mlp_layer_norm
__magic_name__ = flax_model_decoder_layer_block
# Decoder Normalization
__magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"]
__magic_name__ = txa_decoder_norm
# Only for layer 0:
__magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_decoder_rel_embedding
# Token Embeddings
__magic_name__ = tax_model["target"]["token_embedder"]["embedding"]
__magic_name__ = txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
__magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"]
flax_model.save_pretrained(lowerCamelCase_ )
print("T5X Model was sucessfully converted!" )
if __name__ == "__main__":
__magic_name__ : Optional[Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.'
)
parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.')
parser.add_argument(
'--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.'
)
__magic_name__ : Optional[int] =parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
import csv
import tweepy
# Twitter API credentials
__magic_name__ : Dict =''
__magic_name__ : int =''
__magic_name__ : str =''
__magic_name__ : List[str] =''
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = tweepy.OAuthHandler(lowerCamelCase_ , lowerCamelCase_ )
auth.set_access_token(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = tweepy.API(lowerCamelCase_ )
# initialize a list to hold all the tweepy Tweets
__magic_name__ = []
# make initial request for most recent tweets (200 is the maximum allowed count)
__magic_name__ = api.user_timeline(screen_name=lowerCamelCase_ , count=200 )
# save most recent tweets
alltweets.extend(lowerCamelCase_ )
# save the id of the oldest tweet less one
__magic_name__ = alltweets[-1].id - 1
# keep grabbing tweets until there are no tweets left to grab
while len(lowerCamelCase_ ) > 0:
print(F'getting tweets before {oldest}' )
# all subsequent requests use the max_id param to prevent duplicates
__magic_name__ = api.user_timeline(
screen_name=lowerCamelCase_ , count=200 , max_id=lowerCamelCase_ )
# save most recent tweets
alltweets.extend(lowerCamelCase_ )
# update the id of the oldest tweet less one
__magic_name__ = alltweets[-1].id - 1
print(F'...{len(lowerCamelCase_ )} tweets downloaded so far' )
# transform the tweepy tweets into a 2D array that will populate the csv
__magic_name__ = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets]
# write the csv
with open(F'new_{screen_name}_tweets.csv' , "w" ) as f:
__magic_name__ = csv.writer(lowerCamelCase_ )
writer.writerow(["id", "created_at", "text"] )
writer.writerows(lowerCamelCase_ )
if __name__ == "__main__":
# pass in the username of the account you want to download
get_all_tweets('FirePing32')
| 664 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class UpperCamelCase_ ( unittest.TestCase , A ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Any:
__magic_name__ = load_tool("text-to-speech" )
self.tool.setup()
def __A ( self : Union[str, Any] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
def __A ( self : List[str] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
| 664 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__magic_name__ : str ={'configuration_van': ['VAN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VanConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : List[str] =[
'VAN_PRETRAINED_MODEL_ARCHIVE_LIST',
'VanForImageClassification',
'VanModel',
'VanPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_van import (
VAN_PRETRAINED_MODEL_ARCHIVE_LIST,
VanForImageClassification,
VanModel,
VanPreTrainedModel,
)
else:
import sys
__magic_name__ : Dict =_LazyModule(__name__, globals()['__file__'], _import_structure)
| 664 |
'''simple docstring'''
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
__magic_name__ : Dict =re.compile('[^A-Za-z_0-9]')
# parameters used in DuplicationIndex
__magic_name__ : int =10
__magic_name__ : Union[str, Any] =2_56
def __snake_case ( lowerCamelCase_ : List[str] ):
'''simple docstring'''
if len(lowerCamelCase_ ) < MIN_NUM_TOKENS:
return None
__magic_name__ = MinHash(num_perm=lowerCamelCase_ )
for token in set(lowerCamelCase_ ):
min_hash.update(token.encode() )
return min_hash
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0}
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *,
_lowerCamelCase : float = 0.85 , ) -> Optional[Any]:
__magic_name__ = duplication_jaccard_threshold
__magic_name__ = NUM_PERM
__magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm )
__magic_name__ = defaultdict(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None:
__magic_name__ = self._index.query(_lowerCamelCase )
if code_key in self._index.keys:
print(f'Duplicate key {code_key}' )
return
self._index.insert(_lowerCamelCase , _lowerCamelCase )
if len(_lowerCamelCase ) > 0:
for base_duplicate in close_duplicates:
if base_duplicate in self._duplicate_clusters:
self._duplicate_clusters[base_duplicate].add(_lowerCamelCase )
break
else:
self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase )
def __A ( self : Union[str, Any] ) -> List[List[Dict]]:
__magic_name__ = []
for base, duplicates in self._duplicate_clusters.items():
__magic_name__ = [base] + list(_lowerCamelCase )
# reformat the cluster to be a list of dict
__magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster]
duplicate_clusters.append(_lowerCamelCase )
return duplicate_clusters
def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None:
__magic_name__ = self.get_duplicate_clusters()
with open(_lowerCamelCase , "w" ) as f:
json.dump(_lowerCamelCase , _lowerCamelCase )
def __snake_case ( lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ , __magic_name__ = element
__magic_name__ = 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 __snake_case ( lowerCamelCase_ : Type[Dataset] ):
'''simple docstring'''
with mp.Pool() as pool:
for data in pool.imap_unordered(
_compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ):
if data is not None:
yield data
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ):
'''simple docstring'''
__magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ )
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ):
di.add(lowerCamelCase_ , lowerCamelCase_ )
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
return di.get_duplicate_clusters()
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = get_tokens(lowerCamelCase_ )
__magic_name__ = get_tokens(lowerCamelCase_ )
return len(tokensa & tokensa ) / len(tokensa | tokensa )
__magic_name__ : List[str] =None
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = []
for elementa in cluster:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
for elementa in extremes:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold:
elementa["copies"] += 1
break
else:
__magic_name__ = 1
extremes.append(lowerCamelCase_ )
return extremes
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
global _shared_dataset
__magic_name__ = dataset
__magic_name__ = []
__magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ )
with mp.Pool() as pool:
for extremes in tqdm(
pool.imap_unordered(
lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ):
extremes_list.append(lowerCamelCase_ )
return extremes_list
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ):
'''simple docstring'''
__magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster}
__magic_name__ = {}
__magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
for extremes in extremes_clusters:
for element in extremes:
__magic_name__ = element
__magic_name__ = duplicate_indices - set(extreme_dict.keys() )
__magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ )
# update duplicate_clusters
for cluster in duplicate_clusters:
for element in cluster:
__magic_name__ = element["base_index"] in extreme_dict
if element["is_extreme"]:
__magic_name__ = extreme_dict[element["base_index"]]["copies"]
print(F'Original dataset size: {len(lowerCamelCase_ )}' )
print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' )
print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Filtered dataset size: {len(lowerCamelCase_ )}' )
return ds_filter, duplicate_clusters
| 664 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
if TYPE_CHECKING:
from ... import FeatureExtractionMixin, TensorType
__magic_name__ : List[Any] =logging.get_logger(__name__)
__magic_name__ : int ={
'openai/imagegpt-small': '',
'openai/imagegpt-medium': '',
'openai/imagegpt-large': '',
}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : List[str] = '''imagegpt'''
UpperCAmelCase__ : Optional[int] = ['''past_key_values''']
UpperCAmelCase__ : str = {
'''hidden_size''': '''n_embd''',
'''max_position_embeddings''': '''n_positions''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self : Union[str, Any] , _lowerCamelCase : List[Any]=5_12 + 1 , _lowerCamelCase : List[str]=32 * 32 , _lowerCamelCase : Optional[int]=5_12 , _lowerCamelCase : List[str]=24 , _lowerCamelCase : Optional[int]=8 , _lowerCamelCase : str=None , _lowerCamelCase : str="quick_gelu" , _lowerCamelCase : Union[str, Any]=0.1 , _lowerCamelCase : Union[str, Any]=0.1 , _lowerCamelCase : Any=0.1 , _lowerCamelCase : Tuple=1e-5 , _lowerCamelCase : List[Any]=0.02 , _lowerCamelCase : Tuple=True , _lowerCamelCase : List[str]=True , _lowerCamelCase : List[str]=False , _lowerCamelCase : List[str]=False , _lowerCamelCase : Any=False , **_lowerCamelCase : List[Any] , ) -> Optional[Any]:
__magic_name__ = vocab_size
__magic_name__ = n_positions
__magic_name__ = n_embd
__magic_name__ = n_layer
__magic_name__ = n_head
__magic_name__ = n_inner
__magic_name__ = activation_function
__magic_name__ = resid_pdrop
__magic_name__ = embd_pdrop
__magic_name__ = attn_pdrop
__magic_name__ = layer_norm_epsilon
__magic_name__ = initializer_range
__magic_name__ = scale_attn_weights
__magic_name__ = use_cache
__magic_name__ = scale_attn_by_inverse_layer_idx
__magic_name__ = reorder_and_upcast_attn
__magic_name__ = tie_word_embeddings
super().__init__(tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase )
class UpperCamelCase_ ( A ):
"""simple docstring"""
@property
def __A ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
("input_ids", {0: "batch", 1: "sequence"}),
] )
def __A ( self : Dict , _lowerCamelCase : "FeatureExtractionMixin" , _lowerCamelCase : int = 1 , _lowerCamelCase : int = -1 , _lowerCamelCase : bool = False , _lowerCamelCase : Optional["TensorType"] = None , _lowerCamelCase : int = 3 , _lowerCamelCase : int = 32 , _lowerCamelCase : int = 32 , ) -> Mapping[str, Any]:
__magic_name__ = self._generate_dummy_images(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
__magic_name__ = dict(preprocessor(images=_lowerCamelCase , return_tensors=_lowerCamelCase ) )
return inputs
| 664 |
'''simple docstring'''
import argparse
import os
import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn
from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
if version.parse(nlp.__version__) != version.parse('0.8.3'):
raise Exception('requires gluonnlp == 0.8.3')
if version.parse(mx.__version__) != version.parse('1.5.0'):
raise Exception('requires mxnet == 1.5.0')
logging.set_verbosity_info()
__magic_name__ : Optional[int] =logging.get_logger(__name__)
__magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!'
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = {
"attention_cell": "multi_head",
"num_layers": 4,
"units": 1024,
"hidden_size": 768,
"max_length": 512,
"num_heads": 8,
"scaled": True,
"dropout": 0.1,
"use_residual": True,
"embed_size": 1024,
"embed_dropout": 0.1,
"word_embed": None,
"layer_norm_eps": 1e-5,
"token_type_vocab_size": 2,
}
__magic_name__ = bort_4_8_768_1024_hparams
# Let's construct the original Bort model here
# Taken from official BERT implementation, see:
# https://github.com/alexa/bort/blob/master/bort/bort.py
__magic_name__ = BERTEncoder(
attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , )
# Vocab information needs to be fetched first
# It's the same as RoBERTa, so RobertaTokenizer can be used later
__magic_name__ = "openwebtext_ccnews_stories_books_cased"
# Specify download folder to Gluonnlp's vocab
__magic_name__ = os.path.join(get_home_dir() , "models" )
__magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ )
__magic_name__ = nlp.model.BERTModel(
lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , )
original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ )
__magic_name__ = original_bort._collect_params_with_prefix()
# Build our config 🤗
__magic_name__ = {
"architectures": ["BertForMaskedLM"],
"attention_probs_dropout_prob": predefined_args["dropout"],
"hidden_act": "gelu",
"hidden_dropout_prob": predefined_args["dropout"],
"hidden_size": predefined_args["embed_size"],
"initializer_range": 0.02,
"intermediate_size": predefined_args["hidden_size"],
"layer_norm_eps": predefined_args["layer_norm_eps"],
"max_position_embeddings": predefined_args["max_length"],
"model_type": "bort",
"num_attention_heads": predefined_args["num_heads"],
"num_hidden_layers": predefined_args["num_layers"],
"pad_token_id": 1, # 2 = BERT, 1 = RoBERTa
"type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa
"vocab_size": len(lowerCamelCase_ ),
}
__magic_name__ = BertConfig.from_dict(lowerCamelCase_ )
__magic_name__ = BertForMaskedLM(lowerCamelCase_ )
hf_bort_model.eval()
# Parameter mapping table (Gluonnlp to Transformers)
# * denotes layer index
#
# | Gluon Parameter | Transformers Parameter
# | -------------------------------------------------------------- | ----------------------
# | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias`
# | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight`
# | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight`
# | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
# | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight`
# | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight`
# | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias`
# | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight`
# Helper function to convert MXNET Arrays to PyTorch
def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter:
return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) )
# Check param shapes and map new HF param back
def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ):
__magic_name__ = hf_param.shape
__magic_name__ = to_torch(params[gluon_param] )
__magic_name__ = gluon_param.shape
assert (
shape_hf == shape_gluon
), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers'
return gluon_param
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" )
# Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
__magic_name__ = torch.zeros_like(
hf_bort_model.bert.embeddings.token_type_embeddings.weight.data )
for i in range(hf_bort_config.num_hidden_layers ):
__magic_name__ = hf_bort_model.bert.encoder.layer[i]
# self attention
__magic_name__ = layer.attention.self
__magic_name__ = check_and_map_params(
self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' )
__magic_name__ = check_and_map_params(
self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' )
__magic_name__ = check_and_map_params(
self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' )
__magic_name__ = check_and_map_params(
self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' )
__magic_name__ = check_and_map_params(
self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' )
__magic_name__ = check_and_map_params(
self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' )
# self attention output
__magic_name__ = layer.attention.output
__magic_name__ = check_and_map_params(
self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' )
__magic_name__ = check_and_map_params(
self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' )
# intermediate
__magic_name__ = layer.intermediate
__magic_name__ = check_and_map_params(
intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' )
__magic_name__ = check_and_map_params(
intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' )
# output
__magic_name__ = layer.output
__magic_name__ = check_and_map_params(
bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' )
__magic_name__ = check_and_map_params(
bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' )
# Save space and energy 🎄
hf_bort_model.half()
# Compare output of both models
__magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" )
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"]
# Get gluon output
__magic_name__ = mx.nd.array([input_ids] )
__magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] )
# Get Transformer output (save and reload model again)
hf_bort_model.save_pretrained(lowerCamelCase_ )
__magic_name__ = BertModel.from_pretrained(lowerCamelCase_ )
hf_bort_model.eval()
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" )
__magic_name__ = hf_bort_model(**lowerCamelCase_ )[0]
__magic_name__ = output_gluon[0].asnumpy()
__magic_name__ = output_hf[0].detach().numpy()
__magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item()
__magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if success:
print("✔️ Both model do output the same tensors" )
else:
print("❌ Both model do **NOT** output the same tensors" )
print("Absolute difference is:" , lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : int =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
__magic_name__ : Optional[Any] =parser.parse_args()
convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch
import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin, SchedulerOutput
@dataclass
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : torch.FloatTensor
UpperCAmelCase__ : torch.FloatTensor
class UpperCamelCase_ ( A , A ):
"""simple docstring"""
UpperCAmelCase__ : Any = 1
@register_to_config
def __init__( self : str , _lowerCamelCase : int = 20_00 , _lowerCamelCase : float = 0.15 , _lowerCamelCase : float = 0.01 , _lowerCamelCase : float = 1_348.0 , _lowerCamelCase : float = 1e-5 , _lowerCamelCase : int = 1 , ) -> List[Any]:
# standard deviation of the initial noise distribution
__magic_name__ = sigma_max
# setable values
__magic_name__ = None
self.set_sigmas(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
def __A ( self : Union[str, Any] , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : Optional[int] = None ) -> torch.FloatTensor:
return sample
def __A ( self : Optional[Any] , _lowerCamelCase : int , _lowerCamelCase : float = None , _lowerCamelCase : Union[str, torch.device] = None ) -> Tuple:
__magic_name__ = sampling_eps if sampling_eps is not None else self.config.sampling_eps
__magic_name__ = torch.linspace(1 , _lowerCamelCase , _lowerCamelCase , device=_lowerCamelCase )
def __A ( self : Optional[int] , _lowerCamelCase : int , _lowerCamelCase : float = None , _lowerCamelCase : float = None , _lowerCamelCase : float = None ) -> List[str]:
__magic_name__ = sigma_min if sigma_min is not None else self.config.sigma_min
__magic_name__ = sigma_max if sigma_max is not None else self.config.sigma_max
__magic_name__ = sampling_eps if sampling_eps is not None else self.config.sampling_eps
if self.timesteps is None:
self.set_timesteps(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps)
__magic_name__ = torch.exp(torch.linspace(math.log(_lowerCamelCase ) , math.log(_lowerCamelCase ) , _lowerCamelCase ) )
__magic_name__ = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] )
def __A ( self : List[str] , _lowerCamelCase : str , _lowerCamelCase : str ) -> List[str]:
return torch.where(
timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , )
def __A ( self : Tuple , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : int , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : Optional[torch.Generator] = None , _lowerCamelCase : bool = True , ) -> Union[SdeVeOutput, Tuple]:
if self.timesteps is None:
raise ValueError(
"`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" )
__magic_name__ = timestep * torch.ones(
sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0])
__magic_name__ = (timestep * (len(self.timesteps ) - 1)).long()
# mps requires indices to be in the same device, so we use cpu as is the default with cuda
__magic_name__ = timesteps.to(self.discrete_sigmas.device )
__magic_name__ = self.discrete_sigmas[timesteps].to(sample.device )
__magic_name__ = self.get_adjacent_sigma(_lowerCamelCase , _lowerCamelCase ).to(sample.device )
__magic_name__ = torch.zeros_like(_lowerCamelCase )
__magic_name__ = (sigma**2 - adjacent_sigma**2) ** 0.5
# equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
# also equation 47 shows the analog from SDE models to ancestral sampling methods
__magic_name__ = diffusion.flatten()
while len(diffusion.shape ) < len(sample.shape ):
__magic_name__ = diffusion.unsqueeze(-1 )
__magic_name__ = drift - diffusion**2 * model_output
# equation 6: sample noise for the diffusion term of
__magic_name__ = randn_tensor(
sample.shape , layout=sample.layout , generator=_lowerCamelCase , device=sample.device , dtype=sample.dtype )
__magic_name__ = sample - drift # subtract because `dt` is a small negative timestep
# TODO is the variable diffusion the correct scaling term for the noise?
__magic_name__ = prev_sample_mean + diffusion * noise # add impact of diffusion field g
if not return_dict:
return (prev_sample, prev_sample_mean)
return SdeVeOutput(prev_sample=_lowerCamelCase , prev_sample_mean=_lowerCamelCase )
def __A ( self : str , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : Optional[torch.Generator] = None , _lowerCamelCase : bool = True , ) -> Union[SchedulerOutput, Tuple]:
if self.timesteps is None:
raise ValueError(
"`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" )
# For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z"
# sample noise for correction
__magic_name__ = randn_tensor(sample.shape , layout=sample.layout , generator=_lowerCamelCase ).to(sample.device )
# compute step size from the model_output, the noise, and the snr
__magic_name__ = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean()
__magic_name__ = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean()
__magic_name__ = (self.config.snr * noise_norm / grad_norm) ** 2 * 2
__magic_name__ = step_size * torch.ones(sample.shape[0] ).to(sample.device )
# self.repeat_scalar(step_size, sample.shape[0])
# compute corrected sample: model_output term and noise term
__magic_name__ = step_size.flatten()
while len(step_size.shape ) < len(sample.shape ):
__magic_name__ = step_size.unsqueeze(-1 )
__magic_name__ = sample + step_size * model_output
__magic_name__ = prev_sample_mean + ((step_size * 2) ** 0.5) * noise
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=_lowerCamelCase )
def __A ( self : Dict , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : torch.FloatTensor , ) -> torch.FloatTensor:
# Make sure sigmas and timesteps have the same device and dtype as original_samples
__magic_name__ = timesteps.to(original_samples.device )
__magic_name__ = self.discrete_sigmas.to(original_samples.device )[timesteps]
__magic_name__ = (
noise * sigmas[:, None, None, None]
if noise is not None
else torch.randn_like(_lowerCamelCase ) * sigmas[:, None, None, None]
)
__magic_name__ = noise + original_samples
return noisy_samples
def __len__( self : Optional[Any] ) -> Dict:
return self.config.num_train_timesteps
| 664 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ):
'''simple docstring'''
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive" )
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) )
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1" ) )
for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
from collections import namedtuple
from dataclasses import dataclass
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : int
UpperCAmelCase__ : TreeNode | None = None
UpperCAmelCase__ : TreeNode | None = None
__magic_name__ : Optional[int] =namedtuple('CoinsDistribResult', 'moves excess')
def __snake_case ( lowerCamelCase_ : TreeNode | None ):
'''simple docstring'''
if root is None:
return 0
# Validation
def count_nodes(lowerCamelCase_ : TreeNode | None ) -> int:
if node is None:
return 0
return count_nodes(node.left ) + count_nodes(node.right ) + 1
def count_coins(lowerCamelCase_ : TreeNode | None ) -> int:
if node is None:
return 0
return count_coins(node.left ) + count_coins(node.right ) + node.data
if count_nodes(lowerCamelCase_ ) != count_coins(lowerCamelCase_ ):
raise ValueError("The nodes number should be same as the number of coins" )
# Main calculation
def get_distrib(lowerCamelCase_ : TreeNode | None ) -> CoinsDistribResult:
if node is None:
return CoinsDistribResult(0 , 1 )
__magic_name__ , __magic_name__ = get_distrib(node.left )
__magic_name__ , __magic_name__ = get_distrib(node.right )
__magic_name__ = 1 - left_distrib_excess
__magic_name__ = 1 - right_distrib_excess
__magic_name__ = (
left_distrib_moves
+ right_distrib_moves
+ abs(lowerCamelCase_ )
+ abs(lowerCamelCase_ )
)
__magic_name__ = node.data - coins_to_left - coins_to_right
return CoinsDistribResult(lowerCamelCase_ , lowerCamelCase_ )
return get_distrib(lowerCamelCase_ )[0]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 |
'''simple docstring'''
import functools
import logging
import os
import sys
import threading
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
__magic_name__ : Tuple =threading.Lock()
__magic_name__ : Optional[logging.Handler] =None
__magic_name__ : List[str] ={
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
}
__magic_name__ : str =logging.WARNING
__magic_name__ : Any =True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '
F'has to be one of: { ", ".join(log_levels.keys() ) }' )
return _default_log_level
def __snake_case ( ):
'''simple docstring'''
return __name__.split("." )[0]
def __snake_case ( ):
'''simple docstring'''
return logging.getLogger(_get_library_name() )
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
__magic_name__ = logging.StreamHandler() # Set sys.stderr as stream.
__magic_name__ = sys.stderr.flush
# Apply our default configuration to the library root logger.
__magic_name__ = _get_library_root_logger()
library_root_logger.addHandler(_default_handler )
library_root_logger.setLevel(_get_default_logging_level() )
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if not _default_handler:
return
__magic_name__ = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler )
library_root_logger.setLevel(logging.NOTSET )
__magic_name__ = None
def __snake_case ( ):
'''simple docstring'''
return log_levels
def __snake_case ( lowerCamelCase_ : Optional[str] = None ):
'''simple docstring'''
if name is None:
__magic_name__ = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def __snake_case ( lowerCamelCase_ : int ):
'''simple docstring'''
_configure_library_root_logger()
_get_library_root_logger().setLevel(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
__magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" )
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ )
if no_advisory_warnings:
return
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : int =warning_advice
@functools.lru_cache(lowerCamelCase_ )
def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ):
'''simple docstring'''
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : Optional[int] =warning_once
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument
__magic_name__ = args[0] if args else None
def __iter__( self : int ) -> Tuple:
return iter(self._iterator )
def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]:
def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument
return
return empty_fn
def __enter__( self : Optional[Any] ) -> Any:
return self
def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict:
return
class UpperCamelCase_ :
"""simple docstring"""
def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]:
if _tqdm_active:
return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase )
else:
return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]:
__magic_name__ = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : str ) -> Any:
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
__magic_name__ : List[Any] =_tqdm_cls()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
return bool(_tqdm_active )
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = True
hf_hub_utils.enable_progress_bars()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = False
hf_hub_utils.disable_progress_bars()
| 664 | 1 |
'''simple docstring'''
__magic_name__ : List[str] ={
'Pillow': 'Pillow',
'accelerate': 'accelerate>=0.11.0',
'compel': 'compel==0.1.8',
'black': 'black~=23.1',
'datasets': 'datasets',
'filelock': 'filelock',
'flax': 'flax>=0.4.1',
'hf-doc-builder': 'hf-doc-builder>=0.3.0',
'huggingface-hub': 'huggingface-hub>=0.13.2',
'requests-mock': 'requests-mock==1.10.0',
'importlib_metadata': 'importlib_metadata',
'invisible-watermark': 'invisible-watermark',
'isort': 'isort>=5.5.4',
'jax': 'jax>=0.2.8,!=0.3.2',
'jaxlib': 'jaxlib>=0.1.65',
'Jinja2': 'Jinja2',
'k-diffusion': 'k-diffusion>=0.0.12',
'torchsde': 'torchsde',
'note_seq': 'note_seq',
'librosa': 'librosa',
'numpy': 'numpy',
'omegaconf': 'omegaconf',
'parameterized': 'parameterized',
'protobuf': 'protobuf>=3.20.3,<4',
'pytest': 'pytest',
'pytest-timeout': 'pytest-timeout',
'pytest-xdist': 'pytest-xdist',
'ruff': 'ruff>=0.0.241',
'safetensors': 'safetensors',
'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92',
'scipy': 'scipy',
'onnx': 'onnx',
'regex': 'regex!=2019.12.17',
'requests': 'requests',
'tensorboard': 'tensorboard',
'torch': 'torch>=1.4',
'torchvision': 'torchvision',
'transformers': 'transformers>=4.25.1',
'urllib3': 'urllib3<=2.0.0',
}
| 664 |
'''simple docstring'''
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : str =[
'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST',
'FocalNetForImageClassification',
'FocalNetForMaskedImageModeling',
'FocalNetBackbone',
'FocalNetModel',
'FocalNetPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_focalnet import (
FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST,
FocalNetBackbone,
FocalNetForImageClassification,
FocalNetForMaskedImageModeling,
FocalNetModel,
FocalNetPreTrainedModel,
)
else:
import sys
__magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 | 1 |
'''simple docstring'''
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
__magic_name__ : Optional[Any] =logging.get_logger(__name__)
__magic_name__ : int ={'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}
__magic_name__ : Tuple ={
'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'
),
},
}
__magic_name__ : List[Any] ={
'distilbert-base-uncased': 5_12,
'distilbert-base-uncased-distilled-squad': 5_12,
'distilbert-base-cased': 5_12,
'distilbert-base-cased-distilled-squad': 5_12,
'distilbert-base-german-cased': 5_12,
'distilbert-base-multilingual-cased': 5_12,
}
__magic_name__ : List[str] ={
'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 UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Any = VOCAB_FILES_NAMES
UpperCAmelCase__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
UpperCAmelCase__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCAmelCase__ : Tuple = PRETRAINED_INIT_CONFIGURATION
UpperCAmelCase__ : str = ['''input_ids''', '''attention_mask''']
UpperCAmelCase__ : Any = DistilBertTokenizer
def __init__( self : Union[str, Any] , _lowerCamelCase : Any=None , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : int="[UNK]" , _lowerCamelCase : Tuple="[SEP]" , _lowerCamelCase : Dict="[PAD]" , _lowerCamelCase : int="[CLS]" , _lowerCamelCase : Optional[Any]="[MASK]" , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> List[Any]:
super().__init__(
_lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , )
__magic_name__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get("lowercase" , _lowerCamelCase ) != do_lower_case
or normalizer_state.get("strip_accents" , _lowerCamelCase ) != strip_accents
or normalizer_state.get("handle_chinese_chars" , _lowerCamelCase ) != tokenize_chinese_chars
):
__magic_name__ = getattr(_lowerCamelCase , normalizer_state.pop("type" ) )
__magic_name__ = do_lower_case
__magic_name__ = strip_accents
__magic_name__ = tokenize_chinese_chars
__magic_name__ = normalizer_class(**_lowerCamelCase )
__magic_name__ = do_lower_case
def __A ( self : Optional[int] , _lowerCamelCase : List[Any] , _lowerCamelCase : Union[str, Any]=None ) -> int:
__magic_name__ = [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 __A ( self : Tuple , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None ) -> List[int]:
__magic_name__ = [self.sep_token_id]
__magic_name__ = [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 : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ) -> Tuple[str]:
__magic_name__ = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase )
return tuple(_lowerCamelCase )
| 664 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__magic_name__ : Optional[Any] ={
'configuration_longformer': [
'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'LongformerConfig',
'LongformerOnnxConfig',
],
'tokenization_longformer': ['LongformerTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : int =['LongformerTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Dict =[
'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'LongformerForMaskedLM',
'LongformerForMultipleChoice',
'LongformerForQuestionAnswering',
'LongformerForSequenceClassification',
'LongformerForTokenClassification',
'LongformerModel',
'LongformerPreTrainedModel',
'LongformerSelfAttention',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Tuple =[
'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFLongformerForMaskedLM',
'TFLongformerForMultipleChoice',
'TFLongformerForQuestionAnswering',
'TFLongformerForSequenceClassification',
'TFLongformerForTokenClassification',
'TFLongformerModel',
'TFLongformerPreTrainedModel',
'TFLongformerSelfAttention',
]
if TYPE_CHECKING:
from .configuration_longformer import (
LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
LongformerConfig,
LongformerOnnxConfig,
)
from .tokenization_longformer import LongformerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_longformer_fast import LongformerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_longformer import (
LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
LongformerForMaskedLM,
LongformerForMultipleChoice,
LongformerForQuestionAnswering,
LongformerForSequenceClassification,
LongformerForTokenClassification,
LongformerModel,
LongformerPreTrainedModel,
LongformerSelfAttention,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_longformer import (
TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLongformerForMaskedLM,
TFLongformerForMultipleChoice,
TFLongformerForQuestionAnswering,
TFLongformerForSequenceClassification,
TFLongformerForTokenClassification,
TFLongformerModel,
TFLongformerPreTrainedModel,
TFLongformerSelfAttention,
)
else:
import sys
__magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
from collections.abc import Callable
from typing import Generic, TypeVar
__magic_name__ : Union[str, Any] =TypeVar('T')
__magic_name__ : str =TypeVar('U')
class UpperCamelCase_ ( Generic[T, U] ):
"""simple docstring"""
def __init__( self : Tuple , _lowerCamelCase : T | None , _lowerCamelCase : U | None ) -> int:
__magic_name__ = key
__magic_name__ = val
__magic_name__ = None
__magic_name__ = None
def __repr__( self : Union[str, Any] ) -> str:
return (
f'Node: key: {self.key}, val: {self.val}, '
f'has next: {bool(self.next )}, has prev: {bool(self.prev )}'
)
class UpperCamelCase_ ( Generic[T, U] ):
"""simple docstring"""
def __init__( self : int ) -> None:
__magic_name__ = DoubleLinkedListNode(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = DoubleLinkedListNode(_lowerCamelCase , _lowerCamelCase )
__magic_name__ , __magic_name__ = self.rear, self.head
def __repr__( self : int ) -> str:
__magic_name__ = ["DoubleLinkedList"]
__magic_name__ = self.head
while node.next is not None:
rep.append(str(_lowerCamelCase ) )
__magic_name__ = node.next
rep.append(str(self.rear ) )
return ",\n ".join(_lowerCamelCase )
def __A ( self : List[str] , _lowerCamelCase : DoubleLinkedListNode[T, U] ) -> None:
__magic_name__ = self.rear.prev
# All nodes other than self.head are guaranteed to have non-None previous
assert previous is not None
__magic_name__ = node
__magic_name__ = previous
__magic_name__ = node
__magic_name__ = self.rear
def __A ( self : Dict , _lowerCamelCase : DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None:
if node.prev is None or node.next is None:
return None
__magic_name__ = node.next
__magic_name__ = node.prev
__magic_name__ = None
__magic_name__ = None
return node
class UpperCamelCase_ ( Generic[T, U] ):
"""simple docstring"""
UpperCAmelCase__ : dict[Callable[[T], U], LRUCache[T, U]] = {}
def __init__( self : Optional[Any] , _lowerCamelCase : int ) -> Any:
__magic_name__ = DoubleLinkedList()
__magic_name__ = capacity
__magic_name__ = 0
__magic_name__ = 0
__magic_name__ = 0
__magic_name__ = {}
def __repr__( self : str ) -> str:
return (
f'CacheInfo(hits={self.hits}, misses={self.miss}, '
f'capacity={self.capacity}, current size={self.num_keys})'
)
def __contains__( self : List[Any] , _lowerCamelCase : T ) -> bool:
return key in self.cache
def __A ( self : Optional[int] , _lowerCamelCase : T ) -> U | None:
# Note: pythonic interface would throw KeyError rather than return None
if key in self.cache:
self.hits += 1
__magic_name__ = self.cache[key]
__magic_name__ = self.list.remove(self.cache[key] )
assert node == value_node
# node is guaranteed not None because it is in self.cache
assert node is not None
self.list.add(_lowerCamelCase )
return node.val
self.miss += 1
return None
def __A ( self : Optional[int] , _lowerCamelCase : T , _lowerCamelCase : U ) -> None:
if key not in self.cache:
if self.num_keys >= self.capacity:
# delete first node (oldest) when over capacity
__magic_name__ = self.list.head.next
# guaranteed to have a non-None first node when num_keys > 0
# explain to type checker via assertions
assert first_node is not None
assert first_node.key is not None
assert (
self.list.remove(_lowerCamelCase ) is not None
) # node guaranteed to be in list assert node.key is not None
del self.cache[first_node.key]
self.num_keys -= 1
__magic_name__ = DoubleLinkedListNode(_lowerCamelCase , _lowerCamelCase )
self.list.add(self.cache[key] )
self.num_keys += 1
else:
# bump node to the end of the list, update value
__magic_name__ = self.list.remove(self.cache[key] )
assert node is not None # node guaranteed to be in list
__magic_name__ = value
self.list.add(_lowerCamelCase )
@classmethod
def __A ( cls : Dict , _lowerCamelCase : int = 1_28 ) -> Callable[[Callable[[T], U]], Callable[..., U]]:
def cache_decorator_inner(_lowerCamelCase : Callable[[T], U] ) -> Callable[..., U]:
def cache_decorator_wrapper(*_lowerCamelCase : T ) -> U:
if func not in cls.decorator_function_to_instance_map:
__magic_name__ = LRUCache(_lowerCamelCase )
__magic_name__ = cls.decorator_function_to_instance_map[func].get(args[0] )
if result is None:
__magic_name__ = func(*_lowerCamelCase )
cls.decorator_function_to_instance_map[func].put(args[0] , _lowerCamelCase )
return result
def cache_info() -> LRUCache[T, U]:
return cls.decorator_function_to_instance_map[func]
setattr(_lowerCamelCase , "cache_info" , _lowerCamelCase ) # noqa: B010
return cache_decorator_wrapper
return cache_decorator_inner
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 |
'''simple docstring'''
import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'):
__magic_name__ : str ={
'linear': PIL.Image.Resampling.BILINEAR,
'bilinear': PIL.Image.Resampling.BILINEAR,
'bicubic': PIL.Image.Resampling.BICUBIC,
'lanczos': PIL.Image.Resampling.LANCZOS,
'nearest': PIL.Image.Resampling.NEAREST,
}
else:
__magic_name__ : Tuple ={
'linear': PIL.Image.LINEAR,
'bilinear': PIL.Image.BILINEAR,
'bicubic': PIL.Image.BICUBIC,
'lanczos': PIL.Image.LANCZOS,
'nearest': PIL.Image.NEAREST,
}
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = (images / 2 + 0.5).clamp(0 , 1 )
__magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
__magic_name__ = numpy_to_pil(lowerCamelCase_ )
return images
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
if images.ndim == 3:
__magic_name__ = images[None, ...]
__magic_name__ = (images * 255).round().astype("uint8" )
if images.shape[-1] == 1:
# special case for grayscale (single channel) images
__magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images]
else:
__magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images]
return pil_images
| 664 | 1 |
'''simple docstring'''
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Optional[int] , _lowerCamelCase : Any , _lowerCamelCase : int=2 , _lowerCamelCase : int=True , _lowerCamelCase : Union[str, Any]=False , _lowerCamelCase : Tuple=10 , _lowerCamelCase : Any=3 , _lowerCamelCase : Optional[int]=32 * 4 , _lowerCamelCase : List[Any]=32 * 6 , _lowerCamelCase : Union[str, Any]=4 , _lowerCamelCase : Optional[int]=32 , ) -> Any:
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = is_training
__magic_name__ = use_auxiliary_loss
__magic_name__ = num_queries
__magic_name__ = num_channels
__magic_name__ = min_size
__magic_name__ = max_size
__magic_name__ = num_labels
__magic_name__ = mask_feature_size
def __A ( self : str ) -> Tuple:
__magic_name__ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
_lowerCamelCase )
__magic_name__ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase )
__magic_name__ = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5
).float()
__magic_name__ = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long()
__magic_name__ = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def __A ( self : Tuple ) -> Union[str, Any]:
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_28 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def __A ( self : str ) -> List[str]:
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = self.prepare_config_and_inputs()
__magic_name__ = {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
return config, inputs_dict
def __A ( self : str , _lowerCamelCase : Optional[int] , _lowerCamelCase : Dict ) -> Tuple:
__magic_name__ = output.encoder_hidden_states
__magic_name__ = output.pixel_decoder_hidden_states
__magic_name__ = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers )
def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : List[Any]=False ) -> int:
with torch.no_grad():
__magic_name__ = MaskFormerModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__magic_name__ = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase )
def __A ( self : str , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[str] , _lowerCamelCase : Any ) -> Dict:
__magic_name__ = MaskFormerForInstanceSegmentation(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
def comm_check_on_output(_lowerCamelCase : Tuple ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
__magic_name__ = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__magic_name__ = model(_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
__magic_name__ = model(
pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class UpperCamelCase_ ( A , A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : int = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
UpperCAmelCase__ : Tuple = (
{'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
UpperCAmelCase__ : List[str] = False
UpperCAmelCase__ : Optional[Any] = False
UpperCAmelCase__ : Union[str, Any] = False
UpperCAmelCase__ : List[str] = False
def __A ( self : Union[str, Any] ) -> Optional[int]:
__magic_name__ = MaskFormerModelTester(self )
__magic_name__ = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase )
def __A ( self : Tuple ) -> Optional[int]:
self.config_tester.run_common_tests()
def __A ( self : int ) -> int:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def __A ( self : List[Any] ) -> Dict:
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase )
@unittest.skip(reason="MaskFormer does not use inputs_embeds" )
def __A ( self : Optional[Any] ) -> Optional[int]:
pass
@unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" )
def __A ( self : List[Any] ) -> Any:
pass
@unittest.skip(reason="MaskFormer is not a generative model" )
def __A ( self : Optional[int] ) -> Dict:
pass
@unittest.skip(reason="MaskFormer does not use token embeddings" )
def __A ( self : int ) -> int:
pass
@require_torch_multi_gpu
@unittest.skip(
reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" )
def __A ( self : Tuple ) -> Union[str, Any]:
pass
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
def __A ( self : Tuple ) -> Tuple:
pass
def __A ( self : Optional[int] ) -> Tuple:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__magic_name__ = model_class(_lowerCamelCase )
__magic_name__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__magic_name__ = [*signature.parameters.keys()]
__magic_name__ = ["pixel_values"]
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
@slow
def __A ( self : Optional[int] ) -> Optional[int]:
for model_name in ["facebook/maskformer-swin-small-coco"]:
__magic_name__ = MaskFormerModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def __A ( self : List[Any] ) -> List[str]:
__magic_name__ = (self.model_tester.min_size,) * 2
__magic_name__ = {
"pixel_values": torch.randn((2, 3, *size) , device=_lowerCamelCase ),
"mask_labels": torch.randn((2, 10, *size) , device=_lowerCamelCase ),
"class_labels": torch.zeros(2 , 10 , device=_lowerCamelCase ).long(),
}
__magic_name__ = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase )
__magic_name__ = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
def __A ( self : List[str] ) -> List[str]:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def __A ( self : List[Any] ) -> Optional[int]:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__magic_name__ = model_class(_lowerCamelCase ).to(_lowerCamelCase )
__magic_name__ = model(**_lowerCamelCase , output_attentions=_lowerCamelCase )
self.assertTrue(outputs.attentions is not None )
def __A ( self : List[str] ) -> Optional[int]:
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
__magic_name__ = self.all_model_classes[1]
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs()
__magic_name__ = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__magic_name__ = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss
loss.backward()
def __A ( self : Any ) -> Any:
# only MaskFormerForInstanceSegmentation has the loss
__magic_name__ = self.all_model_classes[1]
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs()
__magic_name__ = True
__magic_name__ = True
__magic_name__ = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__magic_name__ = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
__magic_name__ = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
__magic_name__ = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
__magic_name__ = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
__magic_name__ = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=_lowerCamelCase )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
__magic_name__ : Any =1E-4
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_vision
@slow
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self : Tuple ) -> Any:
return (
MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" )
if is_vision_available()
else None
)
def __A ( self : str ) -> int:
__magic_name__ = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(_lowerCamelCase )
__magic_name__ = self.default_image_processor
__magic_name__ = prepare_img()
__magic_name__ = image_processor(_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase )
__magic_name__ = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_00, 10_88) )
with torch.no_grad():
__magic_name__ = model(**_lowerCamelCase )
__magic_name__ = torch.tensor(
[[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__magic_name__ = torch.tensor(
[[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__magic_name__ = torch.tensor(
[[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def __A ( self : Dict ) -> str:
__magic_name__ = (
MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" )
.to(_lowerCamelCase )
.eval()
)
__magic_name__ = self.default_image_processor
__magic_name__ = prepare_img()
__magic_name__ = image_processor(_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase )
__magic_name__ = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_00, 10_88) )
with torch.no_grad():
__magic_name__ = model(**_lowerCamelCase )
# masks_queries_logits
__magic_name__ = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__magic_name__ = [
[-1.3_737_124, -1.7_724_937, -1.9_364_233],
[-1.5_977_281, -1.9_867_939, -2.1_523_695],
[-1.5_795_398, -1.9_269_832, -2.093_942],
]
__magic_name__ = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__magic_name__ = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__magic_name__ = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def __A ( self : List[Any] ) -> Optional[Any]:
__magic_name__ = (
MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" )
.to(_lowerCamelCase )
.eval()
)
__magic_name__ = self.default_image_processor
__magic_name__ = prepare_img()
__magic_name__ = image_processor(_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase )
__magic_name__ = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_00, 10_88) )
with torch.no_grad():
__magic_name__ = model(**_lowerCamelCase )
# masks_queries_logits
__magic_name__ = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__magic_name__ = [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
__magic_name__ = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__magic_name__ = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__magic_name__ = torch.tensor(
[[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def __A ( self : Optional[int] ) -> Any:
__magic_name__ = (
MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" )
.to(_lowerCamelCase )
.eval()
)
__magic_name__ = self.default_image_processor
__magic_name__ = image_processor(
[np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )] , segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )] , return_tensors="pt" , )
__magic_name__ = inputs["pixel_values"].to(_lowerCamelCase )
__magic_name__ = [el.to(_lowerCamelCase ) for el in inputs["mask_labels"]]
__magic_name__ = [el.to(_lowerCamelCase ) for el in inputs["class_labels"]]
with torch.no_grad():
__magic_name__ = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
| 664 |
'''simple docstring'''
from typing import Dict
import numpy as np
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException
if is_tf_available():
import tensorflow as tf
from ..tf_utils import stable_softmax
if is_torch_available():
import torch
__magic_name__ : Optional[Any] =logging.get_logger(__name__)
@add_end_docstrings(
A , r'''
top_k (`int`, defaults to 5):
The number of predictions to return.
targets (`str` or `List[str]`, *optional*):
When passed, the model will limit the scores to the passed targets instead of looking up in the whole
vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
token will be used (with a warning, and that might be slower).
''' , )
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray:
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
elif self.framework == "pt":
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase )
else:
raise ValueError("Unsupported framework" )
return masked_index
def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray:
__magic_name__ = self.get_masked_index(_lowerCamelCase )
__magic_name__ = np.prod(masked_index.shape )
if numel < 1:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , )
def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
for model_input in model_inputs:
self._ensure_exactly_one_mask_token(model_input["input_ids"][0] )
else:
for input_ids in model_inputs["input_ids"]:
self._ensure_exactly_one_mask_token(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]:
if return_tensors is None:
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase )
self.ensure_exactly_one_mask_token(_lowerCamelCase )
return model_inputs
def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]:
__magic_name__ = self.model(**_lowerCamelCase )
__magic_name__ = model_inputs["input_ids"]
return model_outputs
def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict:
# Cap top_k if there are targets
if target_ids is not None and target_ids.shape[0] < top_k:
__magic_name__ = target_ids.shape[0]
__magic_name__ = model_outputs["input_ids"][0]
__magic_name__ = model_outputs["logits"]
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]
__magic_name__ = outputs.numpy()
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 )
if target_ids is not None:
__magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) )
__magic_name__ = tf.expand_dims(_lowerCamelCase , 0 )
__magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase )
__magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy()
else:
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 )
# Fill mask pipeline supports only one ${mask_token} per sample
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = logits.softmax(dim=-1 )
if target_ids is not None:
__magic_name__ = probs[..., target_ids]
__magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase )
__magic_name__ = []
__magic_name__ = values.shape[0] == 1
for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ):
__magic_name__ = []
for v, p in zip(_values , _predictions ):
# Copy is important since we're going to modify this array in place
__magic_name__ = input_ids.numpy().copy()
if target_ids is not None:
__magic_name__ = target_ids[p].tolist()
__magic_name__ = p
# Filter padding out:
__magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )]
# Originally we skip special tokens to give readable output.
# For multi masks though, the other [MASK] would be removed otherwise
# making the output look odd, so we add them back
__magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase )
__magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence}
row.append(_lowerCamelCase )
result.append(_lowerCamelCase )
if single_mask:
return result[0]
return result
def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = [targets]
try:
__magic_name__ = self.tokenizer.get_vocab()
except Exception:
__magic_name__ = {}
__magic_name__ = []
for target in targets:
__magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase )
if id_ is None:
__magic_name__ = self.tokenizer(
_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"]
if len(_lowerCamelCase ) == 0:
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
"We cannot replace it with anything meaningful, ignoring it" )
continue
__magic_name__ = input_ids[0]
# XXX: If users encounter this pass
# it becomes pretty slow, so let's make sure
# The warning enables them to fix the input to
# get faster performance.
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' )
target_ids.append(id_ )
__magic_name__ = list(set(_lowerCamelCase ) )
if len(_lowerCamelCase ) == 0:
raise ValueError("At least one target must be provided when passed." )
__magic_name__ = np.array(_lowerCamelCase )
return target_ids
def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple:
__magic_name__ = {}
if targets is not None:
__magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = target_ids
if top_k is not None:
__magic_name__ = top_k
if self.tokenizer.mask_token_id is None:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." )
return {}, {}, postprocess_params
def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]:
__magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase )
if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1:
return outputs[0]
return outputs
| 664 | 1 |
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from transformers import (
CLIPImageProcessor,
CLIPTextConfig,
CLIPTextModel,
CLIPTokenizer,
CLIPVisionConfig,
CLIPVisionModelWithProjection,
)
from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import (
enable_full_determinism,
floats_tensor,
load_image,
load_numpy,
require_torch_gpu,
skip_mps,
slow,
torch_device,
)
from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import (
PipelineKarrasSchedulerTesterMixin,
PipelineLatentTesterMixin,
PipelineTesterMixin,
assert_mean_pixel_difference,
)
enable_full_determinism()
class UpperCamelCase_ ( A , A , A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : List[str] = StableUnCLIPImgaImgPipeline
UpperCAmelCase__ : int = TEXT_GUIDED_IMAGE_VARIATION_PARAMS
UpperCAmelCase__ : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
UpperCAmelCase__ : Tuple = frozenset(
[] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
UpperCAmelCase__ : Any = frozenset([] )
def __A ( self : Any ) -> Optional[Any]:
__magic_name__ = 32
__magic_name__ = embedder_hidden_size
# image encoding components
__magic_name__ = CLIPImageProcessor(crop_size=32 , size=32 )
torch.manual_seed(0 )
__magic_name__ = CLIPVisionModelWithProjection(
CLIPVisionConfig(
hidden_size=_lowerCamelCase , projection_dim=_lowerCamelCase , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) )
# regular denoising components
torch.manual_seed(0 )
__magic_name__ = StableUnCLIPImageNormalizer(embedding_dim=_lowerCamelCase )
__magic_name__ = DDPMScheduler(beta_schedule="squaredcos_cap_v2" )
torch.manual_seed(0 )
__magic_name__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
torch.manual_seed(0 )
__magic_name__ = CLIPTextModel(
CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=_lowerCamelCase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) )
torch.manual_seed(0 )
__magic_name__ = UNetaDConditionModel(
sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_lowerCamelCase , layers_per_block=1 , upcast_attention=_lowerCamelCase , use_linear_projection=_lowerCamelCase , )
torch.manual_seed(0 )
__magic_name__ = DDIMScheduler(
beta_schedule="scaled_linear" , beta_start=0.00_085 , beta_end=0.012 , prediction_type="v_prediction" , set_alpha_to_one=_lowerCamelCase , steps_offset=1 , )
torch.manual_seed(0 )
__magic_name__ = AutoencoderKL()
__magic_name__ = {
# image encoding components
"feature_extractor": feature_extractor,
"image_encoder": image_encoder.eval(),
# image noising components
"image_normalizer": image_normalizer.eval(),
"image_noising_scheduler": image_noising_scheduler,
# regular denoising components
"tokenizer": tokenizer,
"text_encoder": text_encoder.eval(),
"unet": unet.eval(),
"scheduler": scheduler,
"vae": vae.eval(),
}
return components
def __A ( self : Dict , _lowerCamelCase : List[str] , _lowerCamelCase : Dict=0 , _lowerCamelCase : Optional[Any]=True ) -> str:
if str(_lowerCamelCase ).startswith("mps" ):
__magic_name__ = torch.manual_seed(_lowerCamelCase )
else:
__magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase )
__magic_name__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase )
if pil_image:
__magic_name__ = input_image * 0.5 + 0.5
__magic_name__ = input_image.clamp(0 , 1 )
__magic_name__ = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
__magic_name__ = DiffusionPipeline.numpy_to_pil(_lowerCamelCase )[0]
return {
"prompt": "An anime racoon running a marathon",
"image": input_image,
"generator": generator,
"num_inference_steps": 2,
"output_type": "np",
}
@skip_mps
def __A ( self : List[Any] ) -> Dict:
__magic_name__ = "cpu" # ensure determinism for the device-dependent torch.Generator
__magic_name__ = self.get_dummy_components()
__magic_name__ = StableUnCLIPImgaImgPipeline(**_lowerCamelCase )
__magic_name__ = sd_pipe.to(_lowerCamelCase )
sd_pipe.set_progress_bar_config(disable=_lowerCamelCase )
__magic_name__ = self.get_dummy_inputs(_lowerCamelCase )
inputs.update({"image_embeds": None} )
__magic_name__ = sd_pipe(**_lowerCamelCase ).images
__magic_name__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
__magic_name__ = np.array([0.3_872, 0.7_224, 0.5_601, 0.4_741, 0.6_872, 0.5_814, 0.4_636, 0.3_867, 0.5_078] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def __A ( self : str ) -> str:
__magic_name__ = torch_device in ["cpu", "mps"]
self._test_attention_slicing_forward_pass(test_max_difference=_lowerCamelCase )
def __A ( self : List[str] ) -> str:
__magic_name__ = torch_device in ["cpu", "mps"]
self._test_inference_batch_single_identical(test_max_difference=_lowerCamelCase )
@unittest.skipIf(
torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , )
def __A ( self : List[Any] ) -> Union[str, Any]:
self._test_xformers_attention_forwardGenerator_pass(test_max_difference=_lowerCamelCase )
@slow
@require_torch_gpu
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Tuple ) -> str:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __A ( self : Optional[int] ) -> Dict:
__magic_name__ = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" )
__magic_name__ = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy" )
__magic_name__ = StableUnCLIPImgaImgPipeline.from_pretrained(
"fusing/stable-unclip-2-1-l-img2img" , torch_dtype=torch.floataa )
pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
# stable unclip will oom when integration tests are run on a V100,
# so turn on memory savings
pipe.enable_attention_slicing()
pipe.enable_sequential_cpu_offload()
__magic_name__ = torch.Generator(device="cpu" ).manual_seed(0 )
__magic_name__ = pipe(_lowerCamelCase , "anime turle" , generator=_lowerCamelCase , output_type="np" )
__magic_name__ = output.images[0]
assert image.shape == (7_68, 7_68, 3)
assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase )
def __A ( self : Any ) -> Tuple:
__magic_name__ = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" )
__magic_name__ = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy" )
__magic_name__ = StableUnCLIPImgaImgPipeline.from_pretrained(
"fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa )
pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
# stable unclip will oom when integration tests are run on a V100,
# so turn on memory savings
pipe.enable_attention_slicing()
pipe.enable_sequential_cpu_offload()
__magic_name__ = torch.Generator(device="cpu" ).manual_seed(0 )
__magic_name__ = pipe(_lowerCamelCase , "anime turle" , generator=_lowerCamelCase , output_type="np" )
__magic_name__ = output.images[0]
assert image.shape == (7_68, 7_68, 3)
assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase )
def __A ( self : Any ) -> Optional[int]:
__magic_name__ = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" )
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
__magic_name__ = StableUnCLIPImgaImgPipeline.from_pretrained(
"fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa )
__magic_name__ = pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
pipe.enable_attention_slicing()
pipe.enable_sequential_cpu_offload()
__magic_name__ = pipe(
_lowerCamelCase , "anime turtle" , num_inference_steps=2 , output_type="np" , )
__magic_name__ = torch.cuda.max_memory_allocated()
# make sure that less than 7 GB is allocated
assert mem_bytes < 7 * 10**9
| 664 |
'''simple docstring'''
from __future__ import annotations
def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ):
'''simple docstring'''
if len(lowerCamelCase_ ) < k or k < 0:
raise ValueError("Invalid Input" )
__magic_name__ = __magic_name__ = sum(array[:k] )
for i in range(len(lowerCamelCase_ ) - k ):
__magic_name__ = current_sum - array[i] + array[i + k]
__magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ )
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
__magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)]
__magic_name__ : List[str] =randint(0, 1_10)
print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
| 664 | 1 |
'''simple docstring'''
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
# Importing the dataset
__magic_name__ : Optional[int] =pd.read_csv(
'https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/'
'position_salaries.csv'
)
__magic_name__ : str =dataset.iloc[:, 1:2].values
__magic_name__ : List[Any] =dataset.iloc[:, 2].values
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : List[Any] =train_test_split(X, y, test_size=0.2, random_state=0)
__magic_name__ : int =PolynomialFeatures(degree=4)
__magic_name__ : Tuple =poly_reg.fit_transform(X)
__magic_name__ : Optional[int] =LinearRegression()
pol_reg.fit(X_poly, y)
def __snake_case ( ):
'''simple docstring'''
plt.scatter(lowerCamelCase_ , lowerCamelCase_ , color="red" )
plt.plot(lowerCamelCase_ , pol_reg.predict(poly_reg.fit_transform(lowerCamelCase_ ) ) , color="blue" )
plt.title("Truth or Bluff (Linear Regression)" )
plt.xlabel("Position level" )
plt.ylabel("Salary" )
plt.show()
if __name__ == "__main__":
viz_polymonial()
# Predicting a new result with Polymonial Regression
pol_reg.predict(poly_reg.fit_transform([[5.5]]))
# output should be 132148.43750003
| 664 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__magic_name__ : int =logging.get_logger(__name__)
__magic_name__ : List[Any] ={}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : int = '''llama'''
UpperCAmelCase__ : Any = ['''past_key_values''']
def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any:
__magic_name__ = vocab_size
__magic_name__ = max_position_embeddings
__magic_name__ = hidden_size
__magic_name__ = intermediate_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
__magic_name__ = num_attention_heads
__magic_name__ = num_key_value_heads
__magic_name__ = hidden_act
__magic_name__ = initializer_range
__magic_name__ = rms_norm_eps
__magic_name__ = pretraining_tp
__magic_name__ = use_cache
__magic_name__ = rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , )
def __A ( self : Union[str, Any] ) -> List[Any]:
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2:
raise ValueError(
"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
f'got {self.rope_scaling}' )
__magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase )
__magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' )
if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0:
raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
| 664 | 1 |
'''simple docstring'''
from typing import Dict
import numpy as np
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException
if is_tf_available():
import tensorflow as tf
from ..tf_utils import stable_softmax
if is_torch_available():
import torch
__magic_name__ : Optional[Any] =logging.get_logger(__name__)
@add_end_docstrings(
A , r'''
top_k (`int`, defaults to 5):
The number of predictions to return.
targets (`str` or `List[str]`, *optional*):
When passed, the model will limit the scores to the passed targets instead of looking up in the whole
vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
token will be used (with a warning, and that might be slower).
''' , )
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray:
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
elif self.framework == "pt":
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase )
else:
raise ValueError("Unsupported framework" )
return masked_index
def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray:
__magic_name__ = self.get_masked_index(_lowerCamelCase )
__magic_name__ = np.prod(masked_index.shape )
if numel < 1:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , )
def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
for model_input in model_inputs:
self._ensure_exactly_one_mask_token(model_input["input_ids"][0] )
else:
for input_ids in model_inputs["input_ids"]:
self._ensure_exactly_one_mask_token(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]:
if return_tensors is None:
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase )
self.ensure_exactly_one_mask_token(_lowerCamelCase )
return model_inputs
def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]:
__magic_name__ = self.model(**_lowerCamelCase )
__magic_name__ = model_inputs["input_ids"]
return model_outputs
def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict:
# Cap top_k if there are targets
if target_ids is not None and target_ids.shape[0] < top_k:
__magic_name__ = target_ids.shape[0]
__magic_name__ = model_outputs["input_ids"][0]
__magic_name__ = model_outputs["logits"]
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]
__magic_name__ = outputs.numpy()
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 )
if target_ids is not None:
__magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) )
__magic_name__ = tf.expand_dims(_lowerCamelCase , 0 )
__magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase )
__magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy()
else:
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 )
# Fill mask pipeline supports only one ${mask_token} per sample
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = logits.softmax(dim=-1 )
if target_ids is not None:
__magic_name__ = probs[..., target_ids]
__magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase )
__magic_name__ = []
__magic_name__ = values.shape[0] == 1
for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ):
__magic_name__ = []
for v, p in zip(_values , _predictions ):
# Copy is important since we're going to modify this array in place
__magic_name__ = input_ids.numpy().copy()
if target_ids is not None:
__magic_name__ = target_ids[p].tolist()
__magic_name__ = p
# Filter padding out:
__magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )]
# Originally we skip special tokens to give readable output.
# For multi masks though, the other [MASK] would be removed otherwise
# making the output look odd, so we add them back
__magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase )
__magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence}
row.append(_lowerCamelCase )
result.append(_lowerCamelCase )
if single_mask:
return result[0]
return result
def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = [targets]
try:
__magic_name__ = self.tokenizer.get_vocab()
except Exception:
__magic_name__ = {}
__magic_name__ = []
for target in targets:
__magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase )
if id_ is None:
__magic_name__ = self.tokenizer(
_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"]
if len(_lowerCamelCase ) == 0:
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
"We cannot replace it with anything meaningful, ignoring it" )
continue
__magic_name__ = input_ids[0]
# XXX: If users encounter this pass
# it becomes pretty slow, so let's make sure
# The warning enables them to fix the input to
# get faster performance.
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' )
target_ids.append(id_ )
__magic_name__ = list(set(_lowerCamelCase ) )
if len(_lowerCamelCase ) == 0:
raise ValueError("At least one target must be provided when passed." )
__magic_name__ = np.array(_lowerCamelCase )
return target_ids
def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple:
__magic_name__ = {}
if targets is not None:
__magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = target_ids
if top_k is not None:
__magic_name__ = top_k
if self.tokenizer.mask_token_id is None:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." )
return {}, {}, postprocess_params
def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]:
__magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase )
if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1:
return outputs[0]
return outputs
| 664 |
'''simple docstring'''
__magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1
def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or volume < 0:
raise ValueError("Invalid inputs. Enter positive value." )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume
def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or pressure < 0:
raise ValueError("Invalid inputs. Enter positive value." )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure
if __name__ == "__main__":
from doctest import testmod
testmod()
| 664 | 1 |
'''simple docstring'''
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
__magic_name__ : Union[str, Any] =logging.get_logger(__name__)
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Dict = ['''input_features''']
def __init__( self : Dict , _lowerCamelCase : Tuple=80 , _lowerCamelCase : int=1_60_00 , _lowerCamelCase : Optional[int]=1_60 , _lowerCamelCase : str=30 , _lowerCamelCase : Any=4_00 , _lowerCamelCase : Dict=0.0 , _lowerCamelCase : Optional[Any]=False , **_lowerCamelCase : Dict , ) -> int:
super().__init__(
feature_size=_lowerCamelCase , sampling_rate=_lowerCamelCase , padding_value=_lowerCamelCase , return_attention_mask=_lowerCamelCase , **_lowerCamelCase , )
__magic_name__ = n_fft
__magic_name__ = hop_length
__magic_name__ = chunk_length
__magic_name__ = chunk_length * sampling_rate
__magic_name__ = self.n_samples // hop_length
__magic_name__ = sampling_rate
__magic_name__ = mel_filter_bank(
num_frequency_bins=1 + n_fft // 2 , num_mel_filters=_lowerCamelCase , min_frequency=0.0 , max_frequency=8_000.0 , sampling_rate=_lowerCamelCase , norm="slaney" , mel_scale="slaney" , )
def __A ( self : Tuple , _lowerCamelCase : np.array ) -> np.ndarray:
__magic_name__ = spectrogram(
_lowerCamelCase , window_function(self.n_fft , "hann" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel="log10" , )
__magic_name__ = log_spec[:, :-1]
__magic_name__ = np.maximum(_lowerCamelCase , log_spec.max() - 8.0 )
__magic_name__ = (log_spec + 4.0) / 4.0
return log_spec
@staticmethod
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
def __A ( _lowerCamelCase : List[np.ndarray] , _lowerCamelCase : List[np.ndarray] , _lowerCamelCase : float = 0.0 ) -> List[np.ndarray]:
if attention_mask is not None:
__magic_name__ = np.array(_lowerCamelCase , np.intaa )
__magic_name__ = []
for vector, length in zip(_lowerCamelCase , attention_mask.sum(-1 ) ):
__magic_name__ = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 )
if length < normed_slice.shape[0]:
__magic_name__ = padding_value
normed_input_values.append(_lowerCamelCase )
else:
__magic_name__ = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values]
return normed_input_values
def __call__( self : int , _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , _lowerCamelCase : bool = True , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[Union[str, TensorType]] = None , _lowerCamelCase : Optional[bool] = None , _lowerCamelCase : Optional[str] = "max_length" , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[bool] = None , **_lowerCamelCase : List[str] , ) -> BatchFeature:
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'
f' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'
f' was sampled with {self.sampling_rate} and not {sampling_rate}.' )
else:
logger.warning(
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug." )
__magic_name__ = isinstance(_lowerCamelCase , np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(f'Only mono-channel audio is supported for input to {self}' )
__magic_name__ = is_batched_numpy or (
isinstance(_lowerCamelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
__magic_name__ = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech]
elif not is_batched and not isinstance(_lowerCamelCase , np.ndarray ):
__magic_name__ = np.asarray(_lowerCamelCase , dtype=np.floataa )
elif isinstance(_lowerCamelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
__magic_name__ = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
__magic_name__ = [np.asarray([raw_speech] ).T]
__magic_name__ = BatchFeature({"input_features": raw_speech} )
# convert into correct format for padding
__magic_name__ = self.pad(
_lowerCamelCase , padding=_lowerCamelCase , max_length=max_length if max_length else self.n_samples , truncation=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=return_attention_mask or do_normalize , )
# zero-mean and unit-variance normalization
if do_normalize:
__magic_name__ = self.zero_mean_unit_var_norm(
padded_inputs["input_features"] , attention_mask=padded_inputs["attention_mask"] , padding_value=self.padding_value , )
__magic_name__ = np.stack(padded_inputs["input_features"] , axis=0 )
# make sure list is in array format
__magic_name__ = padded_inputs.get("input_features" ).transpose(2 , 0 , 1 )
__magic_name__ = [self._np_extract_fbank_features(_lowerCamelCase ) for waveform in input_features[0]]
if isinstance(input_features[0] , _lowerCamelCase ):
__magic_name__ = [np.asarray(_lowerCamelCase , dtype=np.floataa ) for feature in input_features]
else:
__magic_name__ = input_features
if return_attention_mask:
# rescale from sample (48000) to feature (3000)
__magic_name__ = padded_inputs["attention_mask"][:, :: self.hop_length]
if return_tensors is not None:
__magic_name__ = padded_inputs.convert_to_tensors(_lowerCamelCase )
return padded_inputs
def __A ( self : List[str] ) -> Dict[str, Any]:
__magic_name__ = copy.deepcopy(self.__dict__ )
__magic_name__ = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
return output
| 664 |
'''simple docstring'''
import logging
import os
from typing import List, TextIO, Union
from conllu import parse_incr
from utils_ner import InputExample, Split, TokenClassificationTask
__magic_name__ : List[Any] =logging.getLogger(__name__)
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]:
# in NER datasets, the last column is usually reserved for NER label
__magic_name__ = label_idx
def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = mode.value
__magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' )
__magic_name__ = 1
__magic_name__ = []
with open(_lowerCamelCase , encoding="utf-8" ) as f:
__magic_name__ = []
__magic_name__ = []
for line in f:
if line.startswith("-DOCSTART-" ) or line == "" or line == "\n":
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
guid_index += 1
__magic_name__ = []
__magic_name__ = []
else:
__magic_name__ = line.split(" " )
words.append(splits[0] )
if len(_lowerCamelCase ) > 1:
labels.append(splits[self.label_idx].replace("\n" , "" ) )
else:
# Examples could have no label for mode = "test"
labels.append("O" )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
return examples
def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]:
__magic_name__ = 0
for line in test_input_reader:
if line.startswith("-DOCSTART-" ) or line == "" or line == "\n":
writer.write(_lowerCamelCase )
if not preds_list[example_id]:
example_id += 1
elif preds_list[example_id]:
__magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n"
writer.write(_lowerCamelCase )
else:
logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] )
def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
__magic_name__ = f.read().splitlines()
if "O" not in labels:
__magic_name__ = ["O"] + labels
return labels
else:
return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : int ) -> str:
# in CONLL2003 dataset chunk column is second-to-last
super().__init__(label_idx=-2 )
def __A ( self : int , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
__magic_name__ = f.read().splitlines()
if "O" not in labels:
__magic_name__ = ["O"] + labels
return labels
else:
return [
"O",
"B-ADVP",
"B-INTJ",
"B-LST",
"B-PRT",
"B-NP",
"B-SBAR",
"B-VP",
"B-ADJP",
"B-CONJP",
"B-PP",
"I-ADVP",
"I-INTJ",
"I-LST",
"I-PRT",
"I-NP",
"I-SBAR",
"I-VP",
"I-ADJP",
"I-CONJP",
"I-PP",
]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = mode.value
__magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' )
__magic_name__ = 1
__magic_name__ = []
with open(_lowerCamelCase , encoding="utf-8" ) as f:
for sentence in parse_incr(_lowerCamelCase ):
__magic_name__ = []
__magic_name__ = []
for token in sentence:
words.append(token["form"] )
labels.append(token["upos"] )
assert len(_lowerCamelCase ) == len(_lowerCamelCase )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
guid_index += 1
return examples
def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any:
__magic_name__ = 0
for sentence in parse_incr(_lowerCamelCase ):
__magic_name__ = preds_list[example_id]
__magic_name__ = ""
for token in sentence:
out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) '
out += "\n"
writer.write(_lowerCamelCase )
example_id += 1
def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
return f.read().splitlines()
else:
return [
"ADJ",
"ADP",
"ADV",
"AUX",
"CCONJ",
"DET",
"INTJ",
"NOUN",
"NUM",
"PART",
"PRON",
"PROPN",
"PUNCT",
"SCONJ",
"SYM",
"VERB",
"X",
]
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : list[list] ):
'''simple docstring'''
__magic_name__ = current_set.copy()
for row_index, row in enumerate(lowerCamelCase_ ):
__magic_name__ = row[0]
for column_index, column in enumerate(lowerCamelCase_ ):
if magnitude == 0:
__magic_name__ = column
continue
__magic_name__ = column / magnitude
# Subtract to cancel term
__magic_name__ = current_set[0]
__magic_name__ = [first_row]
__magic_name__ = current_set[1::]
for row in current_set:
__magic_name__ = []
# If first term is 0, it is already in form we want, so we preserve it
if row[0] == 0:
final_set.append(lowerCamelCase_ )
continue
for column_index in range(len(lowerCamelCase_ ) ):
temp_row.append(first_row[column_index] - row[column_index] )
final_set.append(lowerCamelCase_ )
# Create next recursion iteration set
if len(final_set[0] ) != 3:
__magic_name__ = final_set[0]
__magic_name__ = []
__magic_name__ = []
for row in final_set[1::]:
current_first_column.append(row[0] )
next_iteration.append(row[1::] )
__magic_name__ = simplify(lowerCamelCase_ )
for i in range(len(lowerCamelCase_ ) ):
resultant[i].insert(0 , current_first_column[i] )
resultant.insert(0 , lowerCamelCase_ )
__magic_name__ = resultant
return final_set
def __snake_case ( lowerCamelCase_ : list[list] ):
'''simple docstring'''
if len(lowerCamelCase_ ) == 0:
raise IndexError("solve_simultaneous() requires n lists of length n+1" )
__magic_name__ = len(lowerCamelCase_ ) + 1
if any(len(lowerCamelCase_ ) != _length for item in equations ):
raise IndexError("solve_simultaneous() requires n lists of length n+1" )
for row in equations:
if any(not isinstance(lowerCamelCase_ , (int, float) ) for column in row ):
raise ValueError("solve_simultaneous() requires lists of integers" )
if len(lowerCamelCase_ ) == 1:
return [equations[0][-1] / equations[0][0]]
__magic_name__ = equations.copy()
if any(0 in row for row in data_set ):
__magic_name__ = data_set.copy()
__magic_name__ = []
for row_index, row in enumerate(lowerCamelCase_ ):
if 0 not in row:
__magic_name__ = data_set.pop(lowerCamelCase_ )
break
if not full_row:
raise ValueError("solve_simultaneous() requires at least 1 full equation" )
data_set.insert(0 , lowerCamelCase_ )
__magic_name__ = data_set.copy()
__magic_name__ = simplify(lowerCamelCase_ )
__magic_name__ = simplified[::-1]
__magic_name__ = []
for row in simplified:
__magic_name__ = row[-1]
if not solutions:
if row[-2] == 0:
solutions.append(0 )
continue
solutions.append(current_solution / row[-2] )
continue
__magic_name__ = row.copy()[: len(lowerCamelCase_ ) - 1 :]
while temp_row[0] == 0:
temp_row.pop(0 )
if len(lowerCamelCase_ ) == 0:
solutions.append(0 )
continue
__magic_name__ = temp_row[1::]
__magic_name__ = temp_row[::-1]
for column_index, column in enumerate(lowerCamelCase_ ):
current_solution -= column * solutions[column_index]
solutions.append(lowerCamelCase_ )
__magic_name__ = []
for item in solutions:
final.append(float(round(lowerCamelCase_ , 5 ) ) )
return final[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
__magic_name__ : List[Any] =[
[2, 1, 1, 1, 1, 4],
[1, 2, 1, 1, 1, 5],
[1, 1, 2, 1, 1, 6],
[1, 1, 1, 2, 1, 7],
[1, 1, 1, 1, 2, 8],
]
print(solve_simultaneous(eq))
print(solve_simultaneous([[4, 2]]))
| 664 |
'''simple docstring'''
from __future__ import annotations
from typing import Any
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None:
__magic_name__ , __magic_name__ = row, column
__magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )]
def __str__( self : Optional[Any] ) -> str:
__magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n'
# Make string identifier
__magic_name__ = 0
for row_vector in self.array:
for obj in row_vector:
__magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) )
__magic_name__ = f'%{max_element_length}s'
# Make string and return
def single_line(_lowerCamelCase : list[float] ) -> str:
nonlocal string_format_identifier
__magic_name__ = "["
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector )
line += "]"
return line
s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array )
return s
def __repr__( self : Optional[int] ) -> str:
return str(self )
def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool:
if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2):
return False
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
return False
else:
return True
def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any:
assert self.validate_indicies(_lowerCamelCase )
return self.array[loc[0]][loc[1]]
def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None:
assert self.validate_indicies(_lowerCamelCase )
__magic_name__ = value
def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix:
assert isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == another.row and self.column == another.column
# Add
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] + another[r, c]
return result
def __neg__( self : int ) -> Matrix:
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = -self[r, c]
return result
def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix:
return self + (-another)
def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix:
if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] * another
return result
elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication
assert self.column == another.row
__magic_name__ = Matrix(self.row , another.column )
for r in range(self.row ):
for c in range(another.column ):
for i in range(self.column ):
result[r, c] += self[r, i] * another[i, c]
return result
else:
__magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})'
raise TypeError(_lowerCamelCase )
def __A ( self : Optional[int] ) -> Matrix:
__magic_name__ = Matrix(self.column , self.row )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c]
return result
def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any:
assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == self.column == u.row == v.row # u, v should be column vector
assert u.column == v.column == 1 # u, v should be column vector
# Calculate
__magic_name__ = v.transpose()
__magic_name__ = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
# Testing
if __name__ == "__main__":
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Matrix(3 , 3 , 0 )
for i in range(3 ):
__magic_name__ = 1
print(F'a^(-1) is {ainv}' )
# u, v
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5
print(F'u is {u}' )
print(F'v is {v}' )
print(F'uv^T is {u * v.transpose()}' )
# Sherman Morrison
print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' )
def __snake_case ( ):
'''simple docstring'''
import doctest
doctest.testmod()
testa()
| 664 | 1 |
'''simple docstring'''
import numpy as np
import torch
from torch.utils.data import Dataset, IterableDataset
from ..utils.generic import ModelOutput
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Dict ) -> str:
__magic_name__ = dataset
__magic_name__ = process
__magic_name__ = params
def __len__( self : Optional[int] ) -> Union[str, Any]:
return len(self.dataset )
def __getitem__( self : Union[str, Any] , _lowerCamelCase : List[Any] ) -> List[Any]:
__magic_name__ = self.dataset[i]
__magic_name__ = self.process(_lowerCamelCase , **self.params )
return processed
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : Dict , _lowerCamelCase : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any , _lowerCamelCase : Optional[int]=None ) -> Optional[int]:
__magic_name__ = loader
__magic_name__ = infer
__magic_name__ = params
if loader_batch_size == 1:
# Let's spare some time by deactivating altogether
__magic_name__ = None
__magic_name__ = loader_batch_size
# Internal bookkeeping
__magic_name__ = None
__magic_name__ = None
def __len__( self : Optional[int] ) -> str:
return len(self.loader )
def __iter__( self : List[str] ) -> Any:
__magic_name__ = iter(self.loader )
return self
def __A ( self : Optional[Any] ) -> List[Any]:
if isinstance(self._loader_batch_data , torch.Tensor ):
# Batch data is simple tensor, just fetch the slice
__magic_name__ = self._loader_batch_data[self._loader_batch_index]
else:
# Batch data is assumed to be BaseModelOutput (or dict)
__magic_name__ = {}
for k, element in self._loader_batch_data.items():
if isinstance(_lowerCamelCase , _lowerCamelCase ):
# Convert ModelOutput to tuple first
__magic_name__ = element.to_tuple()
if isinstance(element[0] , torch.Tensor ):
__magic_name__ = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element )
elif isinstance(element[0] , np.ndarray ):
__magic_name__ = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element )
continue
if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_lowerCamelCase , _lowerCamelCase ):
# Those are stored as lists of tensors so need specific unbatching.
if isinstance(element[0] , torch.Tensor ):
__magic_name__ = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element )
elif isinstance(element[0] , np.ndarray ):
__magic_name__ = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element )
continue
if element is None:
# This can happen for optional data that get passed around
__magic_name__ = None
elif isinstance(element[self._loader_batch_index] , torch.Tensor ):
# Take correct batch data, but make it looked like batch_size=1
# For compatibility with other methods within transformers
__magic_name__ = element[self._loader_batch_index].unsqueeze(0 )
elif isinstance(element[self._loader_batch_index] , np.ndarray ):
# Take correct batch data, but make it looked like batch_size=1
# For compatibility with other methods within transformers
__magic_name__ = np.expand_dims(element[self._loader_batch_index] , 0 )
else:
# This is typically a list, so no need to `unsqueeze`.
__magic_name__ = element[self._loader_batch_index]
# Recreate the element by reusing the original class to make it look
# batch_size=1
__magic_name__ = self._loader_batch_data.__class__(_lowerCamelCase )
self._loader_batch_index += 1
return result
def __A ( self : str ) -> Tuple:
if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
# We are currently unrolling a batch so we just need to return
# the current item within a batch
return self.loader_batch_item()
# We're out of items within a batch
__magic_name__ = next(self.iterator )
__magic_name__ = self.infer(_lowerCamelCase , **self.params )
# We now have a batch of "inferred things".
if self.loader_batch_size is not None:
# Try to infer the size of the batch
if isinstance(_lowerCamelCase , torch.Tensor ):
__magic_name__ = processed
else:
__magic_name__ = list(processed.keys() )[0]
__magic_name__ = processed[key]
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = len(_lowerCamelCase )
else:
__magic_name__ = first_tensor.shape[0]
if 0 < observed_batch_size < self.loader_batch_size:
# could be last batch so we can't unroll as many
# elements.
__magic_name__ = observed_batch_size
# Setting internal index to unwrap the batch
__magic_name__ = processed
__magic_name__ = 0
return self.loader_batch_item()
else:
# We're not unrolling batches
return processed
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : List[str] , _lowerCamelCase : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Dict , _lowerCamelCase : List[Any]=None ) -> Tuple:
super().__init__(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
def __iter__( self : Any ) -> Union[str, Any]:
__magic_name__ = iter(self.loader )
__magic_name__ = None
return self
def __A ( self : Any ) -> str:
if self.subiterator is None:
__magic_name__ = self.infer(next(self.iterator ) , **self.params )
try:
# Try to return next item
__magic_name__ = next(self.subiterator )
except StopIteration:
# When a preprocess iterator ends, we can start lookig at the next item
# ChunkIterator will keep feeding until ALL elements of iterator
# all have created their subiterator and have been iterating against.
#
# Another way to look at it, is we're basically flattening lists of lists
# into a single list, but with generators
__magic_name__ = self.infer(next(self.iterator ) , **self.params )
__magic_name__ = next(self.subiterator )
return processed
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __iter__( self : Dict ) -> Union[str, Any]:
__magic_name__ = iter(self.loader )
return self
def __A ( self : Optional[Any] ) -> str:
# Extremely similar to PipelineIterator in its unpacking mechanism
# BUT, we have an extra required item which is the presence of `is_last`
# That is because everything is flattened by `PipelineChunkIterator` we
# need to keep track of how to regroup here in the original `process`
# boundaries so that `process` and `postprocess` see the same data.
# This iterator accumulates items (possibly while unbatching) until it
# its a `is_last` and then just passes it on to the caller.
__magic_name__ = False
__magic_name__ = []
if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
while self._loader_batch_index < self.loader_batch_size:
__magic_name__ = self.loader_batch_item()
__magic_name__ = item.pop("is_last" )
accumulator.append(_lowerCamelCase )
if is_last:
return accumulator
while not is_last:
__magic_name__ = self.infer(next(self.iterator ) , **self.params )
if self.loader_batch_size is not None:
if isinstance(_lowerCamelCase , torch.Tensor ):
__magic_name__ = processed
else:
__magic_name__ = list(processed.keys() )[0]
__magic_name__ = processed[key]
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = len(_lowerCamelCase )
else:
__magic_name__ = first_tensor.shape[0]
if 0 < observed_batch_size < self.loader_batch_size:
# could be last batch so we can't unroll as many
# elements.
__magic_name__ = observed_batch_size
__magic_name__ = processed
__magic_name__ = 0
while self._loader_batch_index < self.loader_batch_size:
__magic_name__ = self.loader_batch_item()
__magic_name__ = item.pop("is_last" )
accumulator.append(_lowerCamelCase )
if is_last:
return accumulator
else:
__magic_name__ = processed
__magic_name__ = item.pop("is_last" )
accumulator.append(_lowerCamelCase )
return accumulator
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : Dict , _lowerCamelCase : Dataset , _lowerCamelCase : str ) -> Any:
__magic_name__ = dataset
__magic_name__ = key
def __len__( self : Union[str, Any] ) -> int:
return len(self.dataset )
def __getitem__( self : List[str] , _lowerCamelCase : Optional[int] ) -> int:
return self.dataset[i][self.key]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCamelCase : Dataset , _lowerCamelCase : str , _lowerCamelCase : str ) -> Optional[Any]:
__magic_name__ = dataset
__magic_name__ = keya
__magic_name__ = keya
def __len__( self : int ) -> Optional[int]:
return len(self.dataset )
def __getitem__( self : Union[str, Any] , _lowerCamelCase : List[Any] ) -> Optional[Any]:
return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
| 664 |
'''simple docstring'''
import argparse
import logging
from collections import namedtuple
import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer # The authors' implementation
from transformers import BertTokenizer
logging.basicConfig(level=logging.INFO)
__magic_name__ : List[Any] =logging.getLogger(__name__)
__magic_name__ : int ='Hello world! cécé herlolip'
__magic_name__ : List[Any] =namedtuple(
'BertAbsConfig',
[
'temp_dir',
'large',
'use_bert_emb',
'finetune_bert',
'encoder',
'share_emb',
'max_pos',
'enc_layers',
'enc_hidden_size',
'enc_heads',
'enc_ff_size',
'enc_dropout',
'dec_layers',
'dec_hidden_size',
'dec_heads',
'dec_ff_size',
'dec_dropout',
],
)
def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ):
'''simple docstring'''
__magic_name__ = BertAbsConfig(
temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , )
__magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage )
__magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ )
original.eval()
__magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) )
new_model.eval()
# -------------------
# Convert the weights
# -------------------
logging.info("convert the model" )
new_model.bert.load_state_dict(original.bert.state_dict() )
new_model.decoder.load_state_dict(original.decoder.state_dict() )
new_model.generator.load_state_dict(original.generator.state_dict() )
# ----------------------------------
# Make sure the outpus are identical
# ----------------------------------
logging.info("Make sure that the models' outputs are identical" )
__magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" )
# prepare the model inputs
__magic_name__ = tokenizer.encode("This is sample éàalj'-." )
encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
__magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." )
decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
# failsafe to make sure the weights reset does not affect the
# loaded weights.
assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0
# forward pass
__magic_name__ = encoder_input_ids
__magic_name__ = decoder_input_ids
__magic_name__ = __magic_name__ = None
__magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = None
# The original model does not apply the geneator layer immediatly but rather in
# the beam search (where it combines softmax + linear layer). Since we already
# apply the softmax in our generation process we only apply the linear layer here.
# We make sure that the outputs of the full stack are identical
__magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = original.generator(lowerCamelCase_ )
__magic_name__ = new_model(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = new_model.generator(lowerCamelCase_ )
__magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if are_identical:
logging.info("all weights are equal up to 1e-3" )
else:
raise ValueError("the weights are different. The new model is likely different from the original one." )
# The model has been saved with torch.save(model) and this is bound to the exact
# directory structure. We save the state_dict instead.
logging.info("saving the model's state dictionary" )
torch.save(
new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" )
if __name__ == "__main__":
__magic_name__ : Dict =argparse.ArgumentParser()
parser.add_argument(
'--bertabs_checkpoint_path',
default=None,
type=str,
required=True,
help='Path the official PyTorch dump.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
required=True,
help='Path to the output PyTorch model.',
)
__magic_name__ : Any =parser.parse_args()
convert_bertabs_checkpoints(
args.bertabs_checkpoint_path,
args.pytorch_dump_folder_path,
)
| 664 | 1 |
'''simple docstring'''
import json
import os
from typing import Optional, Tuple
import regex as re
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__magic_name__ : Any =logging.get_logger(__name__)
__magic_name__ : List[Any] ={
'vocab_file': 'vocab.json',
'merges_file': 'merges.txt',
}
__magic_name__ : int ={
'vocab_file': {'ctrl': 'https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'},
'merges_file': {'ctrl': 'https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'},
}
__magic_name__ : Optional[Any] ={
'ctrl': 2_56,
}
__magic_name__ : List[str] ={
'Pregnancy': 16_86_29,
'Christianity': 76_75,
'Explain': 10_64_23,
'Fitness': 6_34_40,
'Saving': 6_31_63,
'Ask': 2_71_71,
'Ass': 9_59_85,
'Joke': 16_35_09,
'Questions': 4_56_22,
'Thoughts': 4_96_05,
'Retail': 5_23_42,
'Feminism': 16_43_38,
'Writing': 1_19_92,
'Atheism': 19_22_63,
'Netflix': 4_86_16,
'Computing': 3_96_39,
'Opinion': 4_32_13,
'Alone': 4_49_67,
'Funny': 5_89_17,
'Gaming': 4_03_58,
'Human': 40_88,
'India': 13_31,
'Joker': 7_71_38,
'Diet': 3_62_06,
'Legal': 1_18_59,
'Norman': 49_39,
'Tip': 7_26_89,
'Weight': 5_23_43,
'Movies': 4_62_73,
'Running': 2_34_25,
'Science': 20_90,
'Horror': 3_77_93,
'Confession': 6_05_72,
'Finance': 1_22_50,
'Politics': 1_63_60,
'Scary': 19_19_85,
'Support': 1_26_54,
'Technologies': 3_25_16,
'Teenage': 6_61_60,
'Event': 3_27_69,
'Learned': 6_74_60,
'Notion': 18_27_70,
'Wikipedia': 3_75_83,
'Books': 66_65,
'Extract': 7_60_50,
'Confessions': 10_27_01,
'Conspiracy': 7_59_32,
'Links': 6_36_74,
'Narcissus': 15_04_25,
'Relationship': 5_47_66,
'Relationships': 13_47_96,
'Reviews': 4_16_71,
'News': 42_56,
'Translation': 2_68_20,
'multilingual': 12_84_06,
}
def __snake_case ( lowerCamelCase_ : List[str] ):
'''simple docstring'''
__magic_name__ = set()
__magic_name__ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
__magic_name__ = char
__magic_name__ = set(lowerCamelCase_ )
return pairs
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = VOCAB_FILES_NAMES
UpperCAmelCase__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP
UpperCAmelCase__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCAmelCase__ : Optional[Any] = CONTROL_CODES
def __init__( self : Any , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Any="<unk>" , **_lowerCamelCase : Dict ) -> Optional[int]:
super().__init__(unk_token=_lowerCamelCase , **_lowerCamelCase )
with open(_lowerCamelCase , encoding="utf-8" ) as vocab_handle:
__magic_name__ = json.load(_lowerCamelCase )
__magic_name__ = {v: k for k, v in self.encoder.items()}
with open(_lowerCamelCase , encoding="utf-8" ) as merges_handle:
__magic_name__ = merges_handle.read().split("\n" )[1:-1]
__magic_name__ = [tuple(merge.split() ) for merge in merges]
__magic_name__ = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) )
__magic_name__ = {}
@property
def __A ( self : List[str] ) -> List[Any]:
return len(self.encoder )
def __A ( self : Any ) -> Tuple:
return dict(self.encoder , **self.added_tokens_encoder )
def __A ( self : Optional[Any] , _lowerCamelCase : str ) -> str:
if token in self.cache:
return self.cache[token]
__magic_name__ = tuple(_lowerCamelCase )
__magic_name__ = tuple(list(word[:-1] ) + [word[-1] + "</w>"] )
__magic_name__ = get_pairs(_lowerCamelCase )
if not pairs:
return token
while True:
__magic_name__ = min(_lowerCamelCase , key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase , float("inf" ) ) )
if bigram not in self.bpe_ranks:
break
__magic_name__ , __magic_name__ = bigram
__magic_name__ = []
__magic_name__ = 0
while i < len(_lowerCamelCase ):
try:
__magic_name__ = word.index(_lowerCamelCase , _lowerCamelCase )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
__magic_name__ = j
if word[i] == first and i < len(_lowerCamelCase ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
__magic_name__ = tuple(_lowerCamelCase )
__magic_name__ = new_word
if len(_lowerCamelCase ) == 1:
break
else:
__magic_name__ = get_pairs(_lowerCamelCase )
__magic_name__ = "@@ ".join(_lowerCamelCase )
__magic_name__ = word[:-4]
__magic_name__ = word
return word
def __A ( self : Tuple , _lowerCamelCase : int ) -> Optional[Any]:
__magic_name__ = []
__magic_name__ = re.findall(r"\S+\n?" , _lowerCamelCase )
for token in words:
split_tokens.extend(list(self.bpe(_lowerCamelCase ).split(" " ) ) )
return split_tokens
def __A ( self : Union[str, Any] , _lowerCamelCase : List[str] ) -> str:
return self.encoder.get(_lowerCamelCase , self.encoder.get(self.unk_token ) )
def __A ( self : List[Any] , _lowerCamelCase : List[Any] ) -> Dict:
return self.decoder.get(_lowerCamelCase , self.unk_token )
def __A ( self : Dict , _lowerCamelCase : int ) -> Union[str, Any]:
__magic_name__ = " ".join(_lowerCamelCase ).replace("@@ " , "" ).strip()
return out_string
def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ) -> Tuple[str]:
if not os.path.isdir(_lowerCamelCase ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
__magic_name__ = os.path.join(
_lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
__magic_name__ = os.path.join(
_lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] )
with open(_lowerCamelCase , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_lowerCamelCase , ensure_ascii=_lowerCamelCase ) + "\n" )
__magic_name__ = 0
with open(_lowerCamelCase , "w" , encoding="utf-8" ) as writer:
writer.write("#version: 0.2\n" )
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _lowerCamelCase : kv[1] ):
if index != token_index:
logger.warning(
f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
" Please check that the tokenizer is not corrupted!" )
__magic_name__ = token_index
writer.write(" ".join(_lowerCamelCase ) + "\n" )
index += 1
return vocab_file, merge_file
# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
# filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
# tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
# tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
# return ''.join(tokens_generated_so_far)
| 664 |
'''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.generation import DisjunctiveConstraint
@require_torch
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : List[str] ) -> str:
# For consistency across different places the DisjunctiveConstraint is called,
# dc.token_ids is a list of integers. It is also initialized only by integers.
__magic_name__ = [[1, 2, 4], [1, 2, 3, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] )
def __A ( self : List[Any] ) -> str:
# We can't have constraints that are complete subsets of another. This leads to a preverse
# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
__magic_name__ = [[1, 2], [1, 2, 3, 4]]
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(_lowerCamelCase ) # fails here
def __A ( self : List[Any] ) -> int:
__magic_name__ = [[1, 2, 3], [1, 2, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 )
__magic_name__ = stepped is True and completed is True and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 3] )
def __A ( self : Any ) -> Union[str, Any]:
__magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2, 4] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 4, 5] )
dc.reset()
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 3 )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 2 )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.remaining() == 0 )
self.assertTrue(dc.current_seq == [1, 2, 5] )
| 664 | 1 |
'''simple docstring'''
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union
import sentencepiece
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__magic_name__ : Any =logging.get_logger(__name__)
__magic_name__ : List[str] ='▁'
__magic_name__ : int ={
'vocab_file': 'vocab.json',
'spm_file': 'sentencepiece.bpe.model',
}
__magic_name__ : Tuple ={
'vocab_file': {
'facebook/s2t-small-librispeech-asr': (
'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json'
),
},
'spm_file': {
'facebook/s2t-small-librispeech-asr': (
'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model'
)
},
}
__magic_name__ : Optional[Any] ={
'facebook/s2t-small-librispeech-asr': 10_24,
}
__magic_name__ : List[Any] =['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de']
__magic_name__ : Any ={'mustc': MUSTC_LANGS}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Optional[Any] = VOCAB_FILES_NAMES
UpperCAmelCase__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP
UpperCAmelCase__ : List[str] = MAX_MODEL_INPUT_SIZES
UpperCAmelCase__ : Optional[int] = ['''input_ids''', '''attention_mask''']
UpperCAmelCase__ : List[int] = []
def __init__( self : List[str] , _lowerCamelCase : Optional[int] , _lowerCamelCase : str , _lowerCamelCase : Any="<s>" , _lowerCamelCase : List[Any]="</s>" , _lowerCamelCase : Union[str, Any]="<pad>" , _lowerCamelCase : List[str]="<unk>" , _lowerCamelCase : Optional[Any]=False , _lowerCamelCase : Optional[Any]=False , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : List[str]=None , _lowerCamelCase : Optional[Dict[str, Any]] = None , **_lowerCamelCase : Optional[int] , ) -> None:
__magic_name__ = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , do_upper_case=_lowerCamelCase , do_lower_case=_lowerCamelCase , tgt_lang=_lowerCamelCase , lang_codes=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , )
__magic_name__ = do_upper_case
__magic_name__ = do_lower_case
__magic_name__ = load_json(_lowerCamelCase )
__magic_name__ = {v: k for k, v in self.encoder.items()}
__magic_name__ = spm_file
__magic_name__ = load_spm(_lowerCamelCase , self.sp_model_kwargs )
if lang_codes is not None:
__magic_name__ = lang_codes
__magic_name__ = LANGUAGES[lang_codes]
__magic_name__ = [f'<lang:{lang}>' for lang in self.langs]
__magic_name__ = {lang: self.sp_model.PieceToId(f'<lang:{lang}>' ) for lang in self.langs}
__magic_name__ = self.lang_tokens
__magic_name__ = tgt_lang if tgt_lang is not None else self.langs[0]
self.set_tgt_lang_special_tokens(self._tgt_lang )
else:
__magic_name__ = {}
@property
def __A ( self : List[Any] ) -> int:
return len(self.encoder )
@property
def __A ( self : Dict ) -> str:
return self._tgt_lang
@tgt_lang.setter
def __A ( self : Optional[int] , _lowerCamelCase : int ) -> None:
__magic_name__ = new_tgt_lang
self.set_tgt_lang_special_tokens(_lowerCamelCase )
def __A ( self : Optional[Any] , _lowerCamelCase : str ) -> None:
__magic_name__ = self.lang_code_to_id[tgt_lang]
__magic_name__ = [lang_code_id]
def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]:
return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase )
def __A ( self : Tuple , _lowerCamelCase : Optional[int] ) -> Union[str, Any]:
return self.encoder.get(_lowerCamelCase , self.encoder[self.unk_token] )
def __A ( self : Tuple , _lowerCamelCase : int ) -> str:
return self.decoder.get(_lowerCamelCase , self.unk_token )
def __A ( self : List[str] , _lowerCamelCase : List[str] ) -> str:
__magic_name__ = []
__magic_name__ = ""
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
__magic_name__ = self.sp_model.decode(_lowerCamelCase )
out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
__magic_name__ = []
else:
current_sub_tokens.append(_lowerCamelCase )
__magic_name__ = self.sp_model.decode(_lowerCamelCase )
out_string += decoded.upper() if self.do_upper_case else decoded
return out_string.strip()
def __A ( self : List[str] , _lowerCamelCase : Optional[int] , _lowerCamelCase : str=None ) -> List[int]:
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + [self.eos_token_id]
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]
def __A ( self : Dict , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None , _lowerCamelCase : bool = False ) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase )
__magic_name__ = [1] * len(self.prefix_tokens )
__magic_name__ = [1]
if token_ids_a is None:
return prefix_ones + ([0] * len(_lowerCamelCase )) + suffix_ones
return prefix_ones + ([0] * len(_lowerCamelCase )) + ([0] * len(_lowerCamelCase )) + suffix_ones
def __A ( self : Optional[Any] ) -> Dict:
__magic_name__ = self.encoder.copy()
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Optional[Any] ) -> Dict:
__magic_name__ = self.__dict__.copy()
__magic_name__ = None
return state
def __setstate__( self : str , _lowerCamelCase : Dict ) -> None:
__magic_name__ = d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
__magic_name__ = {}
__magic_name__ = load_spm(self.spm_file , self.sp_model_kwargs )
def __A ( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ) -> Tuple[str]:
__magic_name__ = Path(_lowerCamelCase )
assert save_dir.is_dir(), f'{save_directory} should be a directory'
__magic_name__ = save_dir / (
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
)
__magic_name__ = save_dir / (
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
)
save_json(self.encoder , _lowerCamelCase )
if os.path.abspath(self.spm_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.spm_file ):
copyfile(self.spm_file , _lowerCamelCase )
elif not os.path.isfile(self.spm_file ):
with open(_lowerCamelCase , "wb" ) as fi:
__magic_name__ = self.sp_model.serialized_model_proto()
fi.write(_lowerCamelCase )
return (str(_lowerCamelCase ), str(_lowerCamelCase ))
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : Dict[str, Any] ):
'''simple docstring'''
__magic_name__ = sentencepiece.SentencePieceProcessor(**lowerCamelCase_ )
spm.Load(str(lowerCamelCase_ ) )
return spm
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
with open(lowerCamelCase_ , "r" ) as f:
return json.load(lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str ):
'''simple docstring'''
with open(lowerCamelCase_ , "w" ) as f:
json.dump(lowerCamelCase_ , lowerCamelCase_ , indent=2 )
| 664 |
'''simple docstring'''
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
__magic_name__ : Dict ={
'return_dict': False,
'output_hidden_states': True,
'output_attentions': True,
'torchscript': True,
'torch_dtype': 'float16',
'use_bfloat16': True,
'tf_legacy_loss': True,
'pruned_heads': {'a': 1},
'tie_word_embeddings': False,
'is_decoder': True,
'cross_attention_hidden_size': 1_28,
'add_cross_attention': True,
'tie_encoder_decoder': True,
'max_length': 50,
'min_length': 3,
'do_sample': True,
'early_stopping': True,
'num_beams': 3,
'num_beam_groups': 3,
'diversity_penalty': 0.5,
'temperature': 2.0,
'top_k': 10,
'top_p': 0.7,
'typical_p': 0.2,
'repetition_penalty': 0.8,
'length_penalty': 0.8,
'no_repeat_ngram_size': 5,
'encoder_no_repeat_ngram_size': 5,
'bad_words_ids': [1, 2, 3],
'num_return_sequences': 3,
'chunk_size_feed_forward': 5,
'output_scores': True,
'return_dict_in_generate': True,
'forced_bos_token_id': 2,
'forced_eos_token_id': 3,
'remove_invalid_values': True,
'architectures': ['BertModel'],
'finetuning_task': 'translation',
'id2label': {0: 'label'},
'label2id': {'label': '0'},
'tokenizer_class': 'BertTokenizerFast',
'prefix': 'prefix',
'bos_token_id': 6,
'pad_token_id': 7,
'eos_token_id': 8,
'sep_token_id': 9,
'decoder_start_token_id': 10,
'exponential_decay_length_penalty': (5, 1.0_1),
'suppress_tokens': [0, 1],
'begin_suppress_tokens': 2,
'task_specific_params': {'translation': 'some_params'},
'problem_type': 'regression',
}
@is_staging_test
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def __A ( cls : Any ) -> Union[str, Any]:
__magic_name__ = TOKEN
HfFolder.save_token(_lowerCamelCase )
@classmethod
def __A ( cls : Any ) -> Tuple:
try:
delete_repo(token=cls._token , repo_id="test-config" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-config-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-config" )
except HTTPError:
pass
def __A ( self : Optional[Any] ) -> Dict:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("test-config" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="test-config" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : str ) -> Optional[int]:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-config-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
_lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : Optional[int] ) -> Union[str, Any]:
CustomConfig.register_for_auto_class()
__magic_name__ = CustomConfig(attribute=42 )
config.push_to_hub("test-dynamic-config" , use_auth_token=self._token )
# This has added the proper auto_map field to the config
self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} )
__magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase )
# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
self.assertEqual(new_config.__class__.__name__ , "CustomConfig" )
self.assertEqual(new_config.attribute , 42 )
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Optional[Any]:
__magic_name__ = GPTaConfig()
# attempt to modify each of int/float/bool/str config records and verify they were updated
__magic_name__ = c.n_embd + 1 # int
__magic_name__ = c.resid_pdrop + 1.0 # float
__magic_name__ = not c.scale_attn_weights # bool
__magic_name__ = c.summary_type + "foo" # str
c.update_from_string(
f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' )
self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" )
self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" )
self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" )
self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" )
def __A ( self : List[Any] ) -> Union[str, Any]:
__magic_name__ = PretrainedConfig()
__magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to addin config_common_kwargs above.
self.assertListEqual(
_lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] )
__magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )]
if len(_lowerCamelCase ) > 0:
raise ValueError(
"The following keys are set with the default values in"
" `test_configuration_common.config_common_kwargs` pick another value for them:"
f' {", ".join(_lowerCamelCase )}.' )
def __A ( self : List[Any] ) -> List[Any]:
with self.assertRaises(_lowerCamelCase ):
# config is in subfolder, the following should not work without specifying the subfolder
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" )
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" )
self.assertIsNotNone(_lowerCamelCase )
def __A ( self : Tuple ) -> int:
# A mock response for an HTTP head request to emulate server down
__magic_name__ = mock.Mock()
__magic_name__ = 5_00
__magic_name__ = {}
__magic_name__ = HTTPError
__magic_name__ = {}
# Download this model to make sure it's in the cache.
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head:
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
def __A ( self : Union[str, Any] ) -> Dict:
# This test is for deprecated behavior and can be removed in v5
__magic_name__ = BertConfig.from_pretrained(
"https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" )
def __A ( self : Dict ) -> Optional[int]:
__magic_name__ = AutoConfig.from_pretrained("bert-base-cased" )
__magic_name__ = ["config.4.0.0.json"]
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(_lowerCamelCase )
__magic_name__ = 2
json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) )
# This should pick the new configuration file as the version of Transformers is > 4.0.0
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
__magic_name__ = ["config.42.0.0.json"]
__magic_name__ = 7_68
configuration.save_pretrained(_lowerCamelCase )
shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) )
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 7_68 )
def __A ( self : Optional[int] ) -> str:
# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
__magic_name__ = "hf-internal-testing/test-two-configs"
import transformers as new_transformers
__magic_name__ = "v4.0.0"
__magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained(
_lowerCamelCase , return_unused_kwargs=_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(_lowerCamelCase , {} )
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
__magic_name__ = "v3.0.0"
__magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(old_configuration.hidden_size , 7_68 )
| 664 | 1 |
'''simple docstring'''
import argparse
import os
import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn
from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
if version.parse(nlp.__version__) != version.parse('0.8.3'):
raise Exception('requires gluonnlp == 0.8.3')
if version.parse(mx.__version__) != version.parse('1.5.0'):
raise Exception('requires mxnet == 1.5.0')
logging.set_verbosity_info()
__magic_name__ : Optional[int] =logging.get_logger(__name__)
__magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!'
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = {
"attention_cell": "multi_head",
"num_layers": 4,
"units": 1024,
"hidden_size": 768,
"max_length": 512,
"num_heads": 8,
"scaled": True,
"dropout": 0.1,
"use_residual": True,
"embed_size": 1024,
"embed_dropout": 0.1,
"word_embed": None,
"layer_norm_eps": 1e-5,
"token_type_vocab_size": 2,
}
__magic_name__ = bort_4_8_768_1024_hparams
# Let's construct the original Bort model here
# Taken from official BERT implementation, see:
# https://github.com/alexa/bort/blob/master/bort/bort.py
__magic_name__ = BERTEncoder(
attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , )
# Vocab information needs to be fetched first
# It's the same as RoBERTa, so RobertaTokenizer can be used later
__magic_name__ = "openwebtext_ccnews_stories_books_cased"
# Specify download folder to Gluonnlp's vocab
__magic_name__ = os.path.join(get_home_dir() , "models" )
__magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ )
__magic_name__ = nlp.model.BERTModel(
lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , )
original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ )
__magic_name__ = original_bort._collect_params_with_prefix()
# Build our config 🤗
__magic_name__ = {
"architectures": ["BertForMaskedLM"],
"attention_probs_dropout_prob": predefined_args["dropout"],
"hidden_act": "gelu",
"hidden_dropout_prob": predefined_args["dropout"],
"hidden_size": predefined_args["embed_size"],
"initializer_range": 0.02,
"intermediate_size": predefined_args["hidden_size"],
"layer_norm_eps": predefined_args["layer_norm_eps"],
"max_position_embeddings": predefined_args["max_length"],
"model_type": "bort",
"num_attention_heads": predefined_args["num_heads"],
"num_hidden_layers": predefined_args["num_layers"],
"pad_token_id": 1, # 2 = BERT, 1 = RoBERTa
"type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa
"vocab_size": len(lowerCamelCase_ ),
}
__magic_name__ = BertConfig.from_dict(lowerCamelCase_ )
__magic_name__ = BertForMaskedLM(lowerCamelCase_ )
hf_bort_model.eval()
# Parameter mapping table (Gluonnlp to Transformers)
# * denotes layer index
#
# | Gluon Parameter | Transformers Parameter
# | -------------------------------------------------------------- | ----------------------
# | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias`
# | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight`
# | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight`
# | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
# | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight`
# | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight`
# | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias`
# | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight`
# Helper function to convert MXNET Arrays to PyTorch
def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter:
return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) )
# Check param shapes and map new HF param back
def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ):
__magic_name__ = hf_param.shape
__magic_name__ = to_torch(params[gluon_param] )
__magic_name__ = gluon_param.shape
assert (
shape_hf == shape_gluon
), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers'
return gluon_param
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" )
# Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
__magic_name__ = torch.zeros_like(
hf_bort_model.bert.embeddings.token_type_embeddings.weight.data )
for i in range(hf_bort_config.num_hidden_layers ):
__magic_name__ = hf_bort_model.bert.encoder.layer[i]
# self attention
__magic_name__ = layer.attention.self
__magic_name__ = check_and_map_params(
self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' )
__magic_name__ = check_and_map_params(
self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' )
__magic_name__ = check_and_map_params(
self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' )
__magic_name__ = check_and_map_params(
self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' )
__magic_name__ = check_and_map_params(
self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' )
__magic_name__ = check_and_map_params(
self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' )
# self attention output
__magic_name__ = layer.attention.output
__magic_name__ = check_and_map_params(
self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' )
__magic_name__ = check_and_map_params(
self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' )
# intermediate
__magic_name__ = layer.intermediate
__magic_name__ = check_and_map_params(
intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' )
__magic_name__ = check_and_map_params(
intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' )
# output
__magic_name__ = layer.output
__magic_name__ = check_and_map_params(
bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' )
__magic_name__ = check_and_map_params(
bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' )
# Save space and energy 🎄
hf_bort_model.half()
# Compare output of both models
__magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" )
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"]
# Get gluon output
__magic_name__ = mx.nd.array([input_ids] )
__magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] )
# Get Transformer output (save and reload model again)
hf_bort_model.save_pretrained(lowerCamelCase_ )
__magic_name__ = BertModel.from_pretrained(lowerCamelCase_ )
hf_bort_model.eval()
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" )
__magic_name__ = hf_bort_model(**lowerCamelCase_ )[0]
__magic_name__ = output_gluon[0].asnumpy()
__magic_name__ = output_hf[0].detach().numpy()
__magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item()
__magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if success:
print("✔️ Both model do output the same tensors" )
else:
print("❌ Both model do **NOT** output the same tensors" )
print("Absolute difference is:" , lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : int =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
__magic_name__ : Optional[Any] =parser.parse_args()
convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
| 664 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision
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 DPTImageProcessor
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict:
__magic_name__ = size if size is not None else {"height": 18, "width": 18}
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = num_channels
__magic_name__ = image_size
__magic_name__ = min_resolution
__magic_name__ = max_resolution
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = do_normalize
__magic_name__ = image_mean
__magic_name__ = image_std
def __A ( self : int ) -> List[str]:
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
@require_torch
@require_vision
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None
def __A ( self : Dict ) -> Any:
__magic_name__ = DPTImageProcessingTester(self )
@property
def __A ( self : str ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : Tuple ) -> List[str]:
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) )
self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "size" ) )
def __A ( self : List[str] ) -> List[Any]:
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"height": 18, "width": 18} )
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {"height": 42, "width": 42} )
def __A ( self : Union[str, Any] ) -> List[str]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Dict ) -> Optional[Any]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Optional[int] ) -> Dict:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
| 664 | 1 |
'''simple docstring'''
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
__magic_name__ : str =logging.get_logger(__name__)
__magic_name__ : List[Any] ={
'sail/poolformer_s12': 'https://huggingface.co/sail/poolformer_s12/resolve/main/config.json',
# See all PoolFormer models at https://huggingface.co/models?filter=poolformer
}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Optional[Any] = '''poolformer'''
def __init__( self : Tuple , _lowerCamelCase : Any=3 , _lowerCamelCase : str=16 , _lowerCamelCase : int=16 , _lowerCamelCase : Union[str, Any]=3 , _lowerCamelCase : Optional[Any]=4.0 , _lowerCamelCase : Union[str, Any]=[2, 2, 6, 2] , _lowerCamelCase : Tuple=[64, 1_28, 3_20, 5_12] , _lowerCamelCase : Dict=[7, 3, 3, 3] , _lowerCamelCase : Dict=[4, 2, 2, 2] , _lowerCamelCase : str=[2, 1, 1, 1] , _lowerCamelCase : List[Any]=4 , _lowerCamelCase : Optional[int]=0.0 , _lowerCamelCase : int="gelu" , _lowerCamelCase : Any=True , _lowerCamelCase : List[str]=1e-5 , _lowerCamelCase : Union[str, Any]=0.02 , **_lowerCamelCase : List[str] , ) -> Union[str, Any]:
__magic_name__ = num_channels
__magic_name__ = patch_size
__magic_name__ = stride
__magic_name__ = padding
__magic_name__ = pool_size
__magic_name__ = hidden_sizes
__magic_name__ = mlp_ratio
__magic_name__ = depths
__magic_name__ = patch_sizes
__magic_name__ = strides
__magic_name__ = num_encoder_blocks
__magic_name__ = drop_path_rate
__magic_name__ = hidden_act
__magic_name__ = use_layer_scale
__magic_name__ = layer_scale_init_value
__magic_name__ = initializer_range
super().__init__(**_lowerCamelCase )
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Any = version.parse('''1.11''' )
@property
def __A ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
@property
def __A ( self : Optional[int] ) -> float:
return 2e-3
| 664 |
'''simple docstring'''
import numpy
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None:
__magic_name__ = input_array
# Random initial weights are assigned where first argument is the
# number of nodes in previous layer and second argument is the
# number of nodes in the next layer.
# Random initial weights are assigned.
# self.input_array.shape[1] is used to represent number of nodes in input layer.
# First hidden layer consists of 4 nodes.
__magic_name__ = numpy.random.rand(
self.input_array.shape[1] , 4 )
# Random initial values for the first hidden layer.
# First hidden layer has 4 nodes.
# Second hidden layer has 3 nodes.
__magic_name__ = numpy.random.rand(
4 , 3 )
# Random initial values for the second hidden layer.
# Second hidden layer has 3 nodes.
# Output layer has 1 node.
__magic_name__ = numpy.random.rand(3 , 1 )
# Real output values provided.
__magic_name__ = output_array
# Predicted output values by the neural network.
# Predicted_output array initially consists of zeroes.
__magic_name__ = numpy.zeros(output_array.shape )
def __A ( self : int ) -> numpy.ndarray:
__magic_name__ = sigmoid(
numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) )
# layer_between_first_hidden_layer_and_second_hidden_layer is the layer
# connecting the first hidden set of nodes with the second hidden set of nodes.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
# layer_between_second_hidden_layer_and_output is the layer connecting
# second hidden layer with the output node.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return self.layer_between_second_hidden_layer_and_output
def __A ( self : Dict ) -> None:
__magic_name__ = numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , )
__magic_name__ = numpy.dot(
self.layer_between_input_and_first_hidden_layer.T , numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , )
__magic_name__ = numpy.dot(
self.input_array.T , numpy.dot(
numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , )
* sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , )
self.input_layer_and_first_hidden_layer_weights += (
updated_input_layer_and_first_hidden_layer_weights
)
self.first_hidden_layer_and_second_hidden_layer_weights += (
updated_first_hidden_layer_and_second_hidden_layer_weights
)
self.second_hidden_layer_and_output_layer_weights += (
updated_second_hidden_layer_and_output_layer_weights
)
def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None:
for iteration in range(1 , iterations + 1 ):
__magic_name__ = self.feedforward()
self.back_propagation()
if give_loss:
__magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) )
print(f'Iteration {iteration} Loss: {loss}' )
def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int:
__magic_name__ = input_arr
__magic_name__ = sigmoid(
numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return int(self.layer_between_second_hidden_layer_and_output > 0.6 )
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return 1 / (1 + numpy.exp(-value ))
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return (value) * (1 - (value))
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = numpy.array(
(
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
) , dtype=numpy.floataa , )
# True output values for the given input values.
__magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa )
# Calling neural network class.
__magic_name__ = TwoHiddenLayerNeuralNetwork(
input_array=lowerCamelCase_ , output_array=lowerCamelCase_ )
# Calling training function.
# Set give_loss to True if you want to see loss in every iteration.
neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ )
return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) )
if __name__ == "__main__":
example()
| 664 | 1 |
'''simple docstring'''
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
from accelerate.utils import ComputeEnvironment
from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401
from .sagemaker import get_sagemaker_input
__magic_name__ : Any ='Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine'
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _ask_options(
"In which compute environment are you running?" , ["This machine", "AWS (Amazon SageMaker)"] , _convert_compute_environment , )
if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
__magic_name__ = get_sagemaker_input()
else:
__magic_name__ = get_cluster_input()
return config
def __snake_case ( lowerCamelCase_ : Union[str, Any]=None ):
'''simple docstring'''
if subparsers is not None:
__magic_name__ = subparsers.add_parser("config" , description=lowerCamelCase_ )
else:
__magic_name__ = argparse.ArgumentParser("Accelerate config command" , description=lowerCamelCase_ )
parser.add_argument(
"--config_file" , default=lowerCamelCase_ , help=(
"The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
"location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
"such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
"with 'huggingface'."
) , )
if subparsers is not None:
parser.set_defaults(func=lowerCamelCase_ )
return parser
def __snake_case ( lowerCamelCase_ : Dict ):
'''simple docstring'''
__magic_name__ = get_user_input()
if args.config_file is not None:
__magic_name__ = args.config_file
else:
if not os.path.isdir(lowerCamelCase_ ):
os.makedirs(lowerCamelCase_ )
__magic_name__ = default_yaml_config_file
if config_file.endswith(".json" ):
config.to_json_file(lowerCamelCase_ )
else:
config.to_yaml_file(lowerCamelCase_ )
print(F'accelerate configuration saved at {config_file}' )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = config_command_parser()
__magic_name__ = parser.parse_args()
config_command(lowerCamelCase_ )
if __name__ == "__main__":
main()
| 664 |
'''simple docstring'''
import torch
from transformers import AutoModel
class UpperCamelCase_ ( torch.nn.Module ):
"""simple docstring"""
def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]:
super(_lowerCamelCase , self ).__init__()
__magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase )
__magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 )
__magic_name__ = torch.nn.Softmax(dim=1 )
def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]:
return self.bert(**_lowerCamelCase ).last_hidden_state
def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict:
return token_embeddings.sum(2 , keepdim=_lowerCamelCase )
def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]:
return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]:
__magic_name__ = W_supports["sizes"].tolist()
__magic_name__ = W_supports["start_token_id"].item()
__magic_name__ = W_supports["end_token_id"].item()
del W_supports["sizes"]
del W_supports["start_token_id"]
del W_supports["end_token_id"]
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = None
__magic_name__ = None
__magic_name__ = W_supports["input_ids"] == start_token_id
__magic_name__ = W_supports["input_ids"] == end_token_id
for i, size in enumerate(_lowerCamelCase ):
if i == 0:
__magic_name__ = 0
else:
__magic_name__ = support_sizes[i - 1]
__magic_name__ = S[s : s + size][start_token_masks[s : s + size]]
__magic_name__ = S[s : s + size][end_token_masks[s : s + size]]
__magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 )
__magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 )
if p_starts is not None:
__magic_name__ = torch.vstack((p_starts, p_start) )
__magic_name__ = torch.vstack((p_ends, p_end) )
else:
__magic_name__ = p_start
__magic_name__ = p_end
return p_starts, p_ends
| 664 | 1 |
'''simple docstring'''
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path
import torch_xla.distributed.xla_multiprocessing as xmp
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = ArgumentParser(
description=(
"PyTorch TPU distributed training launch "
"helper utility that will spawn up "
"multiple distributed processes"
) )
# Optional arguments for the launch helper
parser.add_argument("--num_cores" , type=lowerCamelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." )
# positional
parser.add_argument(
"training_script" , type=lowerCamelCase_ , help=(
"The full path to the single TPU training "
"program/script to be launched in parallel, "
"followed by all the arguments for the "
"training script"
) , )
# rest from the training program
parser.add_argument("training_script_args" , nargs=lowerCamelCase_ )
return parser.parse_args()
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = parse_args()
# Import training_script as a module.
__magic_name__ = Path(args.training_script )
sys.path.append(str(script_fpath.parent.resolve() ) )
__magic_name__ = script_fpath.stem
__magic_name__ = importlib.import_module(lowerCamelCase_ )
# Patch sys.argv
__magic_name__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )]
xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores )
if __name__ == "__main__":
main()
| 664 |
'''simple docstring'''
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401
deprecate(
'stable diffusion controlnet',
'0.22.0',
'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.',
standard_warn=False,
stacklevel=3,
)
| 664 | 1 |
'''simple docstring'''
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int ) -> Any:
__magic_name__ = 0
__magic_name__ = 0
__magic_name__ = {}
def __A ( self : Optional[Any] , _lowerCamelCase : List[Any] ) -> List[str]:
if vertex not in self.adjacency:
__magic_name__ = {}
self.num_vertices += 1
def __A ( self : Union[str, Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : int ) -> Any:
self.add_vertex(_lowerCamelCase )
self.add_vertex(_lowerCamelCase )
if head == tail:
return
__magic_name__ = weight
__magic_name__ = weight
def __A ( self : Tuple ) -> Optional[int]:
__magic_name__ = self.get_edges()
for edge in edges:
__magic_name__ , __magic_name__ , __magic_name__ = edge
edges.remove((tail, head, weight) )
for i in range(len(_lowerCamelCase ) ):
__magic_name__ = list(edges[i] )
edges.sort(key=lambda _lowerCamelCase : e[2] )
for i in range(len(_lowerCamelCase ) - 1 ):
if edges[i][2] >= edges[i + 1][2]:
__magic_name__ = edges[i][2] + 1
for edge in edges:
__magic_name__ , __magic_name__ , __magic_name__ = edge
__magic_name__ = weight
__magic_name__ = weight
def __str__( self : Any ) -> Dict:
__magic_name__ = ""
for tail in self.adjacency:
for head in self.adjacency[tail]:
__magic_name__ = self.adjacency[head][tail]
string += f'{head} -> {tail} == {weight}\n'
return string.rstrip("\n" )
def __A ( self : Optional[Any] ) -> Union[str, Any]:
__magic_name__ = []
for tail in self.adjacency:
for head in self.adjacency[tail]:
output.append((tail, head, self.adjacency[head][tail]) )
return output
def __A ( self : Tuple ) -> Dict:
return self.adjacency.keys()
@staticmethod
def __A ( _lowerCamelCase : Optional[int]=None , _lowerCamelCase : List[str]=None ) -> Optional[int]:
__magic_name__ = Graph()
if vertices is None:
__magic_name__ = []
if edges is None:
__magic_name__ = []
for vertex in vertices:
g.add_vertex(_lowerCamelCase )
for edge in edges:
g.add_edge(*_lowerCamelCase )
return g
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Any ) -> Optional[Any]:
__magic_name__ = {}
__magic_name__ = {}
def __len__( self : Tuple ) -> Union[str, Any]:
return len(self.parent )
def __A ( self : Any , _lowerCamelCase : Any ) -> str:
if item in self.parent:
return self.find(_lowerCamelCase )
__magic_name__ = item
__magic_name__ = 0
return item
def __A ( self : Dict , _lowerCamelCase : Dict ) -> Union[str, Any]:
if item not in self.parent:
return self.make_set(_lowerCamelCase )
if item != self.parent[item]:
__magic_name__ = self.find(self.parent[item] )
return self.parent[item]
def __A ( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any] ) -> int:
__magic_name__ = self.find(_lowerCamelCase )
__magic_name__ = self.find(_lowerCamelCase )
if roota == roota:
return roota
if self.rank[roota] > self.rank[roota]:
__magic_name__ = roota
return roota
if self.rank[roota] < self.rank[roota]:
__magic_name__ = roota
return roota
if self.rank[roota] == self.rank[roota]:
self.rank[roota] += 1
__magic_name__ = roota
return roota
return None
@staticmethod
def __A ( _lowerCamelCase : Union[str, Any] ) -> Optional[Any]:
__magic_name__ = graph.num_vertices
__magic_name__ = Graph.UnionFind()
__magic_name__ = []
while num_components > 1:
__magic_name__ = {}
for vertex in graph.get_vertices():
__magic_name__ = -1
__magic_name__ = graph.get_edges()
for edge in edges:
__magic_name__ , __magic_name__ , __magic_name__ = edge
edges.remove((tail, head, weight) )
for edge in edges:
__magic_name__ , __magic_name__ , __magic_name__ = edge
__magic_name__ = union_find.find(_lowerCamelCase )
__magic_name__ = union_find.find(_lowerCamelCase )
if seta != seta:
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
__magic_name__ = [head, tail, weight]
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
__magic_name__ = [head, tail, weight]
for vertex in cheap_edge:
if cheap_edge[vertex] != -1:
__magic_name__ , __magic_name__ , __magic_name__ = cheap_edge[vertex]
if union_find.find(_lowerCamelCase ) != union_find.find(_lowerCamelCase ):
union_find.union(_lowerCamelCase , _lowerCamelCase )
mst_edges.append(cheap_edge[vertex] )
__magic_name__ = num_components - 1
__magic_name__ = Graph.build(edges=_lowerCamelCase )
return mst
| 664 |
'''simple docstring'''
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ )
__magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ )
__magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ )
__magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"]
if config.model_type == "t5":
__magic_name__ = "SelfAttention"
if config.model_type == "longt5" and config.encoder_attention_type == "local":
__magic_name__ = "LocalSelfAttention"
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = "TransientGlobalSelfAttention"
else:
raise ValueError(
"Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"
" attribute with a value from ['local', 'transient-global]." )
# Encoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
if split_mlp_wi:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_global_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = tax_mlp_layer_norm
__magic_name__ = flax_model_encoder_layer_block
# Only for layer 0:
__magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_global_rel_embedding
# Assigning
__magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"]
__magic_name__ = tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
"scale"
]
# Encoder-Decoder-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]
__magic_name__ = tax_enc_dec_attention_module["key"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["out"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["query"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
# MLP
if split_mlp_wi:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_pre_attention_layer_norm
__magic_name__ = tax_enc_dec_attention_key
__magic_name__ = tax_enc_dec_attention_out
__magic_name__ = tax_enc_dec_attention_query
__magic_name__ = tax_enc_dec_attention_value
__magic_name__ = tax_cross_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = txa_mlp_layer_norm
__magic_name__ = flax_model_decoder_layer_block
# Decoder Normalization
__magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"]
__magic_name__ = txa_decoder_norm
# Only for layer 0:
__magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_decoder_rel_embedding
# Token Embeddings
__magic_name__ = tax_model["target"]["token_embedder"]["embedding"]
__magic_name__ = txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
__magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"]
flax_model.save_pretrained(lowerCamelCase_ )
print("T5X Model was sucessfully converted!" )
if __name__ == "__main__":
__magic_name__ : Optional[Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.'
)
parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.')
parser.add_argument(
'--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.'
)
__magic_name__ : Optional[int] =parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
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 DetaImageProcessor
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : int , _lowerCamelCase : List[str] , _lowerCamelCase : List[str]=7 , _lowerCamelCase : Optional[Any]=3 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : List[Any]=4_00 , _lowerCamelCase : List[Any]=True , _lowerCamelCase : Tuple=None , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Tuple=[0.5, 0.5, 0.5] , _lowerCamelCase : Optional[Any]=[0.5, 0.5, 0.5] , _lowerCamelCase : int=True , _lowerCamelCase : str=1 / 2_55 , _lowerCamelCase : Optional[Any]=True , ) -> Any:
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
__magic_name__ = size if size is not None else {"shortest_edge": 18, "longest_edge": 13_33}
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = num_channels
__magic_name__ = min_resolution
__magic_name__ = max_resolution
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = do_normalize
__magic_name__ = image_mean
__magic_name__ = image_std
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_pad
def __A ( self : Optional[Any] ) -> Any:
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def __A ( self : Optional[int] , _lowerCamelCase : int , _lowerCamelCase : Tuple=False ) -> Tuple:
if not batched:
__magic_name__ = image_inputs[0]
if isinstance(_lowerCamelCase , Image.Image ):
__magic_name__ , __magic_name__ = image.size
else:
__magic_name__ , __magic_name__ = image.shape[1], image.shape[2]
if w < h:
__magic_name__ = int(self.size["shortest_edge"] * h / w )
__magic_name__ = self.size["shortest_edge"]
elif w > h:
__magic_name__ = self.size["shortest_edge"]
__magic_name__ = int(self.size["shortest_edge"] * w / h )
else:
__magic_name__ = self.size["shortest_edge"]
__magic_name__ = self.size["shortest_edge"]
else:
__magic_name__ = []
for image in image_inputs:
__magic_name__ , __magic_name__ = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
__magic_name__ = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0]
__magic_name__ = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Optional[int] = DetaImageProcessor if is_vision_available() else None
def __A ( self : str ) -> Union[str, Any]:
__magic_name__ = DetaImageProcessingTester(self )
@property
def __A ( self : Tuple ) -> int:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : Optional[Any] ) -> int:
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) )
self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_rescale" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_pad" ) )
self.assertTrue(hasattr(_lowerCamelCase , "size" ) )
def __A ( self : Union[str, Any] ) -> Tuple:
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 13_33} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
def __A ( self : Optional[Any] ) -> List[Any]:
pass
def __A ( self : Any ) -> Tuple:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def __A ( self : int ) -> List[Any]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def __A ( self : Dict ) -> Optional[int]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def __A ( self : List[str] ) -> Dict:
# prepare image and target
__magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f:
__magic_name__ = json.loads(f.read() )
__magic_name__ = {"image_id": 3_97_69, "annotations": target}
# encode them
__magic_name__ = DetaImageProcessor()
__magic_name__ = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors="pt" )
# verify pixel values
__magic_name__ = torch.Size([1, 3, 8_00, 10_66] )
self.assertEqual(encoding["pixel_values"].shape , _lowerCamelCase )
__magic_name__ = torch.tensor([0.2_796, 0.3_138, 0.3_481] )
self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__magic_name__ = torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438] )
self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _lowerCamelCase ) )
# verify boxes
__magic_name__ = torch.Size([6, 4] )
self.assertEqual(encoding["labels"][0]["boxes"].shape , _lowerCamelCase )
__magic_name__ = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] )
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__magic_name__ = torch.tensor([3_97_69] )
self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _lowerCamelCase ) )
# verify is_crowd
__magic_name__ = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _lowerCamelCase ) )
# verify class_labels
__magic_name__ = torch.tensor([75, 75, 63, 65, 17, 17] )
self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _lowerCamelCase ) )
# verify orig_size
__magic_name__ = torch.tensor([4_80, 6_40] )
self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _lowerCamelCase ) )
# verify size
__magic_name__ = torch.tensor([8_00, 10_66] )
self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _lowerCamelCase ) )
@slow
def __A ( self : List[str] ) -> Dict:
# prepare image, target and masks_path
__magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f:
__magic_name__ = json.loads(f.read() )
__magic_name__ = {"file_name": "000000039769.png", "image_id": 3_97_69, "segments_info": target}
__magic_name__ = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" )
# encode them
__magic_name__ = DetaImageProcessor(format="coco_panoptic" )
__magic_name__ = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors="pt" )
# verify pixel values
__magic_name__ = torch.Size([1, 3, 8_00, 10_66] )
self.assertEqual(encoding["pixel_values"].shape , _lowerCamelCase )
__magic_name__ = torch.tensor([0.2_796, 0.3_138, 0.3_481] )
self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__magic_name__ = torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147] )
self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _lowerCamelCase ) )
# verify boxes
__magic_name__ = torch.Size([6, 4] )
self.assertEqual(encoding["labels"][0]["boxes"].shape , _lowerCamelCase )
__magic_name__ = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] )
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__magic_name__ = torch.tensor([3_97_69] )
self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _lowerCamelCase ) )
# verify is_crowd
__magic_name__ = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _lowerCamelCase ) )
# verify class_labels
__magic_name__ = torch.tensor([17, 17, 63, 75, 75, 93] )
self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _lowerCamelCase ) )
# verify masks
__magic_name__ = 82_28_73
self.assertEqual(encoding["labels"][0]["masks"].sum().item() , _lowerCamelCase )
# verify orig_size
__magic_name__ = torch.tensor([4_80, 6_40] )
self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _lowerCamelCase ) )
# verify size
__magic_name__ = torch.tensor([8_00, 10_66] )
self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _lowerCamelCase ) )
| 664 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class UpperCamelCase_ ( unittest.TestCase , A ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Any:
__magic_name__ = load_tool("text-to-speech" )
self.tool.setup()
def __A ( self : Union[str, Any] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
def __A ( self : List[str] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
| 664 | 1 |
'''simple docstring'''
import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Callable, Dict, List, Tuple
import timm
import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs
from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.utils import logging
logging.set_verbosity_info()
__magic_name__ : Any =logging.get_logger()
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : nn.Module
UpperCAmelCase__ : List[nn.Module] = field(default_factory=A )
UpperCAmelCase__ : list = field(default_factory=A )
def __A ( self : int , _lowerCamelCase : Any , _lowerCamelCase : Tensor , _lowerCamelCase : Tensor ) -> str:
__magic_name__ = len(list(m.modules() ) ) == 1 or isinstance(_lowerCamelCase , nn.Convad ) or isinstance(_lowerCamelCase , nn.BatchNormad )
if has_not_submodules:
self.traced.append(_lowerCamelCase )
def __call__( self : Any , _lowerCamelCase : Tensor ) -> List[str]:
for m in self.module.modules():
self.handles.append(m.register_forward_hook(self._forward_hook ) )
self.module(_lowerCamelCase )
[x.remove() for x in self.handles]
return self
@property
def __A ( self : Dict ) -> int:
# check the len of the state_dict keys to see if we have learnable params
return list(filter(lambda _lowerCamelCase : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) )
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : nn.Module
UpperCAmelCase__ : nn.Module
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : List = field(default_factory=A )
UpperCAmelCase__ : List = field(default_factory=A )
UpperCAmelCase__ : bool = True
def __call__( self : List[Any] , _lowerCamelCase : Tensor ) -> List[str]:
__magic_name__ = Tracker(self.dest )(_lowerCamelCase ).parametrized
__magic_name__ = Tracker(self.src )(_lowerCamelCase ).parametrized
__magic_name__ = list(filter(lambda _lowerCamelCase : type(_lowerCamelCase ) not in self.src_skip , _lowerCamelCase ) )
__magic_name__ = list(filter(lambda _lowerCamelCase : type(_lowerCamelCase ) not in self.dest_skip , _lowerCamelCase ) )
if len(_lowerCamelCase ) != len(_lowerCamelCase ) and self.raise_if_mismatch:
raise Exception(
f'Numbers of operations are different. Source module has {len(_lowerCamelCase )} operations while'
f' destination module has {len(_lowerCamelCase )}.' )
for dest_m, src_m in zip(_lowerCamelCase , _lowerCamelCase ):
dest_m.load_state_dict(src_m.state_dict() )
if self.verbose == 1:
print(f'Transfered from={src_m} to={dest_m}' )
class UpperCamelCase_ ( nn.Module ):
"""simple docstring"""
def __init__( self : int , _lowerCamelCase : nn.Module ) -> Optional[Any]:
super().__init__()
__magic_name__ = []
# - get the stem
feature_blocks.append(("conv1", model.stem) )
# - get all the feature blocks
for k, v in model.trunk_output.named_children():
assert k.startswith("block" ), f'Unexpected layer name {k}'
__magic_name__ = len(_lowerCamelCase ) + 1
feature_blocks.append((f'res{block_index}', v) )
__magic_name__ = nn.ModuleDict(_lowerCamelCase )
def __A ( self : Optional[Any] , _lowerCamelCase : Tensor ) -> List[Any]:
return get_trunk_forward_outputs(
_lowerCamelCase , out_feat_keys=_lowerCamelCase , feature_blocks=self._feature_blocks , )
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : Union[str, Any] , _lowerCamelCase : str ) -> str:
__magic_name__ = x.split("-" )
return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] )
def __getitem__( self : Optional[int] , _lowerCamelCase : str ) -> Callable[[], Tuple[nn.Module, Dict]]:
# default to timm!
if x not in self:
__magic_name__ = self.convert_name_to_timm(_lowerCamelCase )
__magic_name__ = partial(lambda: (timm.create_model(_lowerCamelCase , pretrained=_lowerCamelCase ).eval(), None) )
else:
__magic_name__ = super().__getitem__(_lowerCamelCase )
return val
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __getitem__( self : Dict , _lowerCamelCase : str ) -> Callable[[], nn.Module]:
if "seer" in x and "in1k" not in x:
__magic_name__ = RegNetModel
else:
__magic_name__ = RegNetForImageClassification
return val
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[Tuple[str, str]] ):
'''simple docstring'''
for from_key, to_key in keys:
__magic_name__ = from_state_dict[from_key].clone()
print(F'Copied key={from_key} to={to_key}' )
return to_state_dict
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : Callable[[], nn.Module] , lowerCamelCase_ : Callable[[], nn.Module] , lowerCamelCase_ : RegNetConfig , lowerCamelCase_ : Path , lowerCamelCase_ : bool = True , ):
'''simple docstring'''
print(F'Converting {name}...' )
with torch.no_grad():
__magic_name__ , __magic_name__ = from_model_func()
__magic_name__ = our_model_func(lowerCamelCase_ ).eval()
__magic_name__ = ModuleTransfer(src=lowerCamelCase_ , dest=lowerCamelCase_ , raise_if_mismatch=lowerCamelCase_ )
__magic_name__ = torch.randn((1, 3, 224, 224) )
module_transfer(lowerCamelCase_ )
if from_state_dict is not None:
__magic_name__ = []
# for seer - in1k finetuned we have to manually copy the head
if "seer" in name and "in1k" in name:
__magic_name__ = [("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")]
__magic_name__ = manually_copy_vissl_head(lowerCamelCase_ , our_model.state_dict() , lowerCamelCase_ )
our_model.load_state_dict(lowerCamelCase_ )
__magic_name__ = our_model(lowerCamelCase_ , output_hidden_states=lowerCamelCase_ )
__magic_name__ = (
our_outputs.logits if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else our_outputs.last_hidden_state
)
__magic_name__ = from_model(lowerCamelCase_ )
__magic_name__ = from_output[-1] if type(lowerCamelCase_ ) is list else from_output
# now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state
if "seer" in name and "in1k" in name:
__magic_name__ = our_outputs.hidden_states[-1]
assert torch.allclose(lowerCamelCase_ , lowerCamelCase_ ), "The model logits don't match the original one."
if push_to_hub:
our_model.push_to_hub(
repo_path_or_name=save_directory / name , commit_message="Add model" , use_temp_dir=lowerCamelCase_ , )
__magic_name__ = 224 if "seer" not in name else 384
# we can use the convnext one
__magic_name__ = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" , size=lowerCamelCase_ )
image_processor.push_to_hub(
repo_path_or_name=save_directory / name , commit_message="Add image processor" , use_temp_dir=lowerCamelCase_ , )
print(F'Pushed {name}' )
def __snake_case ( lowerCamelCase_ : Path , lowerCamelCase_ : str = None , lowerCamelCase_ : bool = True ):
'''simple docstring'''
__magic_name__ = "imagenet-1k-id2label.json"
__magic_name__ = 1000
__magic_name__ = (1, num_labels)
__magic_name__ = "huggingface/label-files"
__magic_name__ = num_labels
__magic_name__ = json.load(open(cached_download(hf_hub_url(lowerCamelCase_ , lowerCamelCase_ , repo_type="dataset" ) ) , "r" ) )
__magic_name__ = {int(lowerCamelCase_ ): v for k, v in idalabel.items()}
__magic_name__ = idalabel
__magic_name__ = {v: k for k, v in idalabel.items()}
__magic_name__ = partial(lowerCamelCase_ , num_labels=lowerCamelCase_ , idalabel=lowerCamelCase_ , labelaid=lowerCamelCase_ )
__magic_name__ = {
"regnet-x-002": ImageNetPreTrainedConfig(
depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type="x" ),
"regnet-x-004": ImageNetPreTrainedConfig(
depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type="x" ),
"regnet-x-006": ImageNetPreTrainedConfig(
depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type="x" ),
"regnet-x-008": ImageNetPreTrainedConfig(
depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type="x" ),
"regnet-x-016": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type="x" ),
"regnet-x-032": ImageNetPreTrainedConfig(
depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type="x" ),
"regnet-x-040": ImageNetPreTrainedConfig(
depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type="x" ),
"regnet-x-064": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type="x" ),
"regnet-x-080": ImageNetPreTrainedConfig(
depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type="x" ),
"regnet-x-120": ImageNetPreTrainedConfig(
depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type="x" ),
"regnet-x-160": ImageNetPreTrainedConfig(
depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type="x" ),
"regnet-x-320": ImageNetPreTrainedConfig(
depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type="x" ),
# y variant
"regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ),
"regnet-y-004": ImageNetPreTrainedConfig(
depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ),
"regnet-y-006": ImageNetPreTrainedConfig(
depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ),
"regnet-y-008": ImageNetPreTrainedConfig(
depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ),
"regnet-y-016": ImageNetPreTrainedConfig(
depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ),
"regnet-y-032": ImageNetPreTrainedConfig(
depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24 ),
"regnet-y-040": ImageNetPreTrainedConfig(
depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64 ),
"regnet-y-064": ImageNetPreTrainedConfig(
depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72 ),
"regnet-y-080": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56 ),
"regnet-y-120": ImageNetPreTrainedConfig(
depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 ),
"regnet-y-160": ImageNetPreTrainedConfig(
depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112 ),
"regnet-y-320": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ),
# models created by SEER -> https://arxiv.org/abs/2202.08360
"regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ),
"regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ),
"regnet-y-1280-seer": RegNetConfig(
depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ),
"regnet-y-2560-seer": RegNetConfig(
depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ),
"regnet-y-10b-seer": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ),
# finetuned on imagenet
"regnet-y-320-seer-in1k": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ),
"regnet-y-640-seer-in1k": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ),
"regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ),
"regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig(
depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ),
"regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ),
}
__magic_name__ = NameToOurModelFuncMap()
__magic_name__ = NameToFromModelFuncMap()
# add seer weights logic
def load_using_classy_vision(lowerCamelCase_ : str , lowerCamelCase_ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]:
__magic_name__ = torch.hub.load_state_dict_from_url(lowerCamelCase_ , model_dir=str(lowerCamelCase_ ) , map_location="cpu" )
__magic_name__ = model_func()
# check if we have a head, if yes add it
__magic_name__ = files["classy_state_dict"]["base_model"]["model"]
__magic_name__ = model_state_dict["trunk"]
model.load_state_dict(lowerCamelCase_ )
return model.eval(), model_state_dict["heads"]
# pretrained
__magic_name__ = partial(
lowerCamelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , )
__magic_name__ = partial(
lowerCamelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , )
__magic_name__ = partial(
lowerCamelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , )
__magic_name__ = partial(
lowerCamelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch" , lambda: FakeRegNetVisslWrapper(
RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , )
# IN1K finetuned
__magic_name__ = partial(
lowerCamelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , )
__magic_name__ = partial(
lowerCamelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , )
__magic_name__ = partial(
lowerCamelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , )
__magic_name__ = partial(
lowerCamelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch" , lambda: FakeRegNetVisslWrapper(
RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , )
if model_name:
convert_weight_and_push(
lowerCamelCase_ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowerCamelCase_ , lowerCamelCase_ , )
else:
for model_name, config in names_to_config.items():
convert_weight_and_push(
lowerCamelCase_ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , )
return config, expected_shape
if __name__ == "__main__":
__magic_name__ : List[Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default=None,
type=str,
help=(
'The name of the model you wish to convert, it must be one of the supported regnet* architecture,'
' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.'
),
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=Path,
required=True,
help='Path to the output PyTorch model directory.',
)
parser.add_argument(
'--push_to_hub',
default=True,
type=bool,
required=False,
help='If True, push model and image processor to the hub.',
)
__magic_name__ : str =parser.parse_args()
__magic_name__ : Path =args.pytorch_dump_folder_path
pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| 664 |
'''simple docstring'''
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
__magic_name__ : Dict =re.compile('[^A-Za-z_0-9]')
# parameters used in DuplicationIndex
__magic_name__ : int =10
__magic_name__ : Union[str, Any] =2_56
def __snake_case ( lowerCamelCase_ : List[str] ):
'''simple docstring'''
if len(lowerCamelCase_ ) < MIN_NUM_TOKENS:
return None
__magic_name__ = MinHash(num_perm=lowerCamelCase_ )
for token in set(lowerCamelCase_ ):
min_hash.update(token.encode() )
return min_hash
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0}
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *,
_lowerCamelCase : float = 0.85 , ) -> Optional[Any]:
__magic_name__ = duplication_jaccard_threshold
__magic_name__ = NUM_PERM
__magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm )
__magic_name__ = defaultdict(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None:
__magic_name__ = self._index.query(_lowerCamelCase )
if code_key in self._index.keys:
print(f'Duplicate key {code_key}' )
return
self._index.insert(_lowerCamelCase , _lowerCamelCase )
if len(_lowerCamelCase ) > 0:
for base_duplicate in close_duplicates:
if base_duplicate in self._duplicate_clusters:
self._duplicate_clusters[base_duplicate].add(_lowerCamelCase )
break
else:
self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase )
def __A ( self : Union[str, Any] ) -> List[List[Dict]]:
__magic_name__ = []
for base, duplicates in self._duplicate_clusters.items():
__magic_name__ = [base] + list(_lowerCamelCase )
# reformat the cluster to be a list of dict
__magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster]
duplicate_clusters.append(_lowerCamelCase )
return duplicate_clusters
def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None:
__magic_name__ = self.get_duplicate_clusters()
with open(_lowerCamelCase , "w" ) as f:
json.dump(_lowerCamelCase , _lowerCamelCase )
def __snake_case ( lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ , __magic_name__ = element
__magic_name__ = 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 __snake_case ( lowerCamelCase_ : Type[Dataset] ):
'''simple docstring'''
with mp.Pool() as pool:
for data in pool.imap_unordered(
_compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ):
if data is not None:
yield data
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ):
'''simple docstring'''
__magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ )
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ):
di.add(lowerCamelCase_ , lowerCamelCase_ )
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
return di.get_duplicate_clusters()
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = get_tokens(lowerCamelCase_ )
__magic_name__ = get_tokens(lowerCamelCase_ )
return len(tokensa & tokensa ) / len(tokensa | tokensa )
__magic_name__ : List[str] =None
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = []
for elementa in cluster:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
for elementa in extremes:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold:
elementa["copies"] += 1
break
else:
__magic_name__ = 1
extremes.append(lowerCamelCase_ )
return extremes
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
global _shared_dataset
__magic_name__ = dataset
__magic_name__ = []
__magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ )
with mp.Pool() as pool:
for extremes in tqdm(
pool.imap_unordered(
lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ):
extremes_list.append(lowerCamelCase_ )
return extremes_list
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ):
'''simple docstring'''
__magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster}
__magic_name__ = {}
__magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
for extremes in extremes_clusters:
for element in extremes:
__magic_name__ = element
__magic_name__ = duplicate_indices - set(extreme_dict.keys() )
__magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ )
# update duplicate_clusters
for cluster in duplicate_clusters:
for element in cluster:
__magic_name__ = element["base_index"] in extreme_dict
if element["is_extreme"]:
__magic_name__ = extreme_dict[element["base_index"]]["copies"]
print(F'Original dataset size: {len(lowerCamelCase_ )}' )
print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' )
print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Filtered dataset size: {len(lowerCamelCase_ )}' )
return ds_filter, duplicate_clusters
| 664 | 1 |
'''simple docstring'''
__magic_name__ : Tuple ='\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
__magic_name__ : int =[{'type': 'code', 'content': INSTALL_CONTENT}]
__magic_name__ : int ={
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 664 |
'''simple docstring'''
import argparse
import os
import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn
from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
if version.parse(nlp.__version__) != version.parse('0.8.3'):
raise Exception('requires gluonnlp == 0.8.3')
if version.parse(mx.__version__) != version.parse('1.5.0'):
raise Exception('requires mxnet == 1.5.0')
logging.set_verbosity_info()
__magic_name__ : Optional[int] =logging.get_logger(__name__)
__magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!'
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = {
"attention_cell": "multi_head",
"num_layers": 4,
"units": 1024,
"hidden_size": 768,
"max_length": 512,
"num_heads": 8,
"scaled": True,
"dropout": 0.1,
"use_residual": True,
"embed_size": 1024,
"embed_dropout": 0.1,
"word_embed": None,
"layer_norm_eps": 1e-5,
"token_type_vocab_size": 2,
}
__magic_name__ = bort_4_8_768_1024_hparams
# Let's construct the original Bort model here
# Taken from official BERT implementation, see:
# https://github.com/alexa/bort/blob/master/bort/bort.py
__magic_name__ = BERTEncoder(
attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , )
# Vocab information needs to be fetched first
# It's the same as RoBERTa, so RobertaTokenizer can be used later
__magic_name__ = "openwebtext_ccnews_stories_books_cased"
# Specify download folder to Gluonnlp's vocab
__magic_name__ = os.path.join(get_home_dir() , "models" )
__magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ )
__magic_name__ = nlp.model.BERTModel(
lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , )
original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ )
__magic_name__ = original_bort._collect_params_with_prefix()
# Build our config 🤗
__magic_name__ = {
"architectures": ["BertForMaskedLM"],
"attention_probs_dropout_prob": predefined_args["dropout"],
"hidden_act": "gelu",
"hidden_dropout_prob": predefined_args["dropout"],
"hidden_size": predefined_args["embed_size"],
"initializer_range": 0.02,
"intermediate_size": predefined_args["hidden_size"],
"layer_norm_eps": predefined_args["layer_norm_eps"],
"max_position_embeddings": predefined_args["max_length"],
"model_type": "bort",
"num_attention_heads": predefined_args["num_heads"],
"num_hidden_layers": predefined_args["num_layers"],
"pad_token_id": 1, # 2 = BERT, 1 = RoBERTa
"type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa
"vocab_size": len(lowerCamelCase_ ),
}
__magic_name__ = BertConfig.from_dict(lowerCamelCase_ )
__magic_name__ = BertForMaskedLM(lowerCamelCase_ )
hf_bort_model.eval()
# Parameter mapping table (Gluonnlp to Transformers)
# * denotes layer index
#
# | Gluon Parameter | Transformers Parameter
# | -------------------------------------------------------------- | ----------------------
# | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias`
# | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight`
# | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight`
# | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
# | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight`
# | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight`
# | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias`
# | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight`
# Helper function to convert MXNET Arrays to PyTorch
def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter:
return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) )
# Check param shapes and map new HF param back
def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ):
__magic_name__ = hf_param.shape
__magic_name__ = to_torch(params[gluon_param] )
__magic_name__ = gluon_param.shape
assert (
shape_hf == shape_gluon
), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers'
return gluon_param
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" )
# Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
__magic_name__ = torch.zeros_like(
hf_bort_model.bert.embeddings.token_type_embeddings.weight.data )
for i in range(hf_bort_config.num_hidden_layers ):
__magic_name__ = hf_bort_model.bert.encoder.layer[i]
# self attention
__magic_name__ = layer.attention.self
__magic_name__ = check_and_map_params(
self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' )
__magic_name__ = check_and_map_params(
self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' )
__magic_name__ = check_and_map_params(
self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' )
__magic_name__ = check_and_map_params(
self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' )
__magic_name__ = check_and_map_params(
self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' )
__magic_name__ = check_and_map_params(
self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' )
# self attention output
__magic_name__ = layer.attention.output
__magic_name__ = check_and_map_params(
self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' )
__magic_name__ = check_and_map_params(
self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' )
# intermediate
__magic_name__ = layer.intermediate
__magic_name__ = check_and_map_params(
intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' )
__magic_name__ = check_and_map_params(
intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' )
# output
__magic_name__ = layer.output
__magic_name__ = check_and_map_params(
bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' )
__magic_name__ = check_and_map_params(
bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' )
# Save space and energy 🎄
hf_bort_model.half()
# Compare output of both models
__magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" )
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"]
# Get gluon output
__magic_name__ = mx.nd.array([input_ids] )
__magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] )
# Get Transformer output (save and reload model again)
hf_bort_model.save_pretrained(lowerCamelCase_ )
__magic_name__ = BertModel.from_pretrained(lowerCamelCase_ )
hf_bort_model.eval()
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" )
__magic_name__ = hf_bort_model(**lowerCamelCase_ )[0]
__magic_name__ = output_gluon[0].asnumpy()
__magic_name__ = output_hf[0].detach().numpy()
__magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item()
__magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if success:
print("✔️ Both model do output the same tensors" )
else:
print("❌ Both model do **NOT** output the same tensors" )
print("Absolute difference is:" , lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : int =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
__magic_name__ : Optional[Any] =parser.parse_args()
convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401
deprecate(
'stable diffusion controlnet',
'0.22.0',
'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.',
standard_warn=False,
stacklevel=3,
)
| 664 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ):
'''simple docstring'''
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive" )
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) )
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1" ) )
for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = 1
__magic_name__ = 2
while i * i <= n:
__magic_name__ = 0
while n % i == 0:
n //= i
multiplicity += 1
n_divisors *= multiplicity + 1
i += 1
if n > 1:
n_divisors *= 2
return n_divisors
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = 1
__magic_name__ = 1
while True:
i += 1
t_num += i
if count_divisors(lowerCamelCase_ ) > 500:
break
return t_num
if __name__ == "__main__":
print(solution())
| 664 |
'''simple docstring'''
import functools
import logging
import os
import sys
import threading
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
__magic_name__ : Tuple =threading.Lock()
__magic_name__ : Optional[logging.Handler] =None
__magic_name__ : List[str] ={
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
}
__magic_name__ : str =logging.WARNING
__magic_name__ : Any =True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '
F'has to be one of: { ", ".join(log_levels.keys() ) }' )
return _default_log_level
def __snake_case ( ):
'''simple docstring'''
return __name__.split("." )[0]
def __snake_case ( ):
'''simple docstring'''
return logging.getLogger(_get_library_name() )
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
__magic_name__ = logging.StreamHandler() # Set sys.stderr as stream.
__magic_name__ = sys.stderr.flush
# Apply our default configuration to the library root logger.
__magic_name__ = _get_library_root_logger()
library_root_logger.addHandler(_default_handler )
library_root_logger.setLevel(_get_default_logging_level() )
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if not _default_handler:
return
__magic_name__ = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler )
library_root_logger.setLevel(logging.NOTSET )
__magic_name__ = None
def __snake_case ( ):
'''simple docstring'''
return log_levels
def __snake_case ( lowerCamelCase_ : Optional[str] = None ):
'''simple docstring'''
if name is None:
__magic_name__ = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def __snake_case ( lowerCamelCase_ : int ):
'''simple docstring'''
_configure_library_root_logger()
_get_library_root_logger().setLevel(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
__magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" )
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ )
if no_advisory_warnings:
return
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : int =warning_advice
@functools.lru_cache(lowerCamelCase_ )
def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ):
'''simple docstring'''
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : Optional[int] =warning_once
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument
__magic_name__ = args[0] if args else None
def __iter__( self : int ) -> Tuple:
return iter(self._iterator )
def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]:
def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument
return
return empty_fn
def __enter__( self : Optional[Any] ) -> Any:
return self
def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict:
return
class UpperCamelCase_ :
"""simple docstring"""
def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]:
if _tqdm_active:
return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase )
else:
return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]:
__magic_name__ = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : str ) -> Any:
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
__magic_name__ : List[Any] =_tqdm_cls()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
return bool(_tqdm_active )
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = True
hf_hub_utils.enable_progress_bars()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = False
hf_hub_utils.disable_progress_bars()
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ):
'''simple docstring'''
if len(lowerCamelCase_ ) < k or k < 0:
raise ValueError("Invalid Input" )
__magic_name__ = __magic_name__ = sum(array[:k] )
for i in range(len(lowerCamelCase_ ) - k ):
__magic_name__ = current_sum - array[i] + array[i + k]
__magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ )
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
__magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)]
__magic_name__ : List[str] =randint(0, 1_10)
print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
| 664 |
'''simple docstring'''
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : str =[
'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST',
'FocalNetForImageClassification',
'FocalNetForMaskedImageModeling',
'FocalNetBackbone',
'FocalNetModel',
'FocalNetPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_focalnet import (
FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST,
FocalNetBackbone,
FocalNetForImageClassification,
FocalNetForMaskedImageModeling,
FocalNetModel,
FocalNetPreTrainedModel,
)
else:
import sys
__magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 | 1 |
'''simple docstring'''
import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch
import pyarrow as pa
import pytest
import requests
from packaging import version
from datasets import config
if config.PY_VERSION < version.parse('3.8'):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str=False ):
'''simple docstring'''
try:
__magic_name__ = os.environ[key]
except KeyError:
# KEY isn't set, default to `default`.
__magic_name__ = default
else:
# KEY is set, convert it to True or False.
try:
__magic_name__ = strtobool(lowerCamelCase_ )
except ValueError:
# More values are supported, but let's keep the message simple.
raise ValueError(F'If set, {key} must be yes or no.' )
return _value
__magic_name__ : Optional[int] =parse_flag_from_env('RUN_SLOW', default=False)
__magic_name__ : Optional[Any] =parse_flag_from_env('RUN_REMOTE', default=False)
__magic_name__ : Union[str, Any] =parse_flag_from_env('RUN_LOCAL', default=True)
__magic_name__ : Optional[Any] =parse_flag_from_env('RUN_PACKAGED', default=True)
# Compression
__magic_name__ : List[str] =pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
__magic_name__ : Optional[Any] =pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
__magic_name__ : str =pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')
# Audio
__magic_name__ : Dict =pytest.mark.skipif(
# On Windows and OS X, soundfile installs sndfile
find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'),
reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ',
)
# Beam
__magic_name__ : Dict =pytest.mark.skipif(
not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'),
reason='test requires apache-beam and a compatible dill version',
)
# Dill-cloudpickle compatibility
__magic_name__ : List[Any] =pytest.mark.skipif(
config.DILL_VERSION <= version.parse('0.3.2'),
reason='test requires dill>0.3.2 for cloudpickle compatibility',
)
# Windows
__magic_name__ : List[str] =pytest.mark.skipif(
sys.platform == 'win32',
reason='test should not be run on Windows',
)
def __snake_case ( lowerCamelCase_ : Tuple ):
'''simple docstring'''
try:
import faiss # noqa
except ImportError:
__magic_name__ = unittest.skip("test requires faiss" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : Dict ):
'''simple docstring'''
try:
import regex # noqa
except ImportError:
__magic_name__ = unittest.skip("test requires regex" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : Dict ):
'''simple docstring'''
try:
import elasticsearch # noqa
except ImportError:
__magic_name__ = unittest.skip("test requires elasticsearch" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
try:
import sqlalchemy # noqa
except ImportError:
__magic_name__ = unittest.skip("test requires sqlalchemy" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : Tuple ):
'''simple docstring'''
if not config.TORCH_AVAILABLE:
__magic_name__ = unittest.skip("test requires PyTorch" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
if not config.TF_AVAILABLE:
__magic_name__ = unittest.skip("test requires TensorFlow" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
if not config.JAX_AVAILABLE:
__magic_name__ = unittest.skip("test requires JAX" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
if not config.PIL_AVAILABLE:
__magic_name__ = unittest.skip("test requires Pillow" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
try:
import transformers # noqa F401
except ImportError:
return unittest.skip("test requires transformers" )(lowerCamelCase_ )
else:
return test_case
def __snake_case ( lowerCamelCase_ : Optional[int] ):
'''simple docstring'''
try:
import tiktoken # noqa F401
except ImportError:
return unittest.skip("test requires tiktoken" )(lowerCamelCase_ )
else:
return test_case
def __snake_case ( lowerCamelCase_ : List[Any] ):
'''simple docstring'''
try:
import spacy # noqa F401
except ImportError:
return unittest.skip("test requires spacy" )(lowerCamelCase_ )
else:
return test_case
def __snake_case ( lowerCamelCase_ : Tuple ):
'''simple docstring'''
def _require_spacy_model(lowerCamelCase_ : List[str] ):
try:
import spacy # noqa F401
spacy.load(lowerCamelCase_ )
except ImportError:
return unittest.skip("test requires spacy" )(lowerCamelCase_ )
except OSError:
return unittest.skip("test requires spacy model '{}'".format(lowerCamelCase_ ) )(lowerCamelCase_ )
else:
return test_case
return _require_spacy_model
def __snake_case ( lowerCamelCase_ : Tuple ):
'''simple docstring'''
try:
import pyspark # noqa F401
except ImportError:
return unittest.skip("test requires pyspark" )(lowerCamelCase_ )
else:
return test_case
def __snake_case ( lowerCamelCase_ : List[str] ):
'''simple docstring'''
try:
import joblibspark # noqa F401
except ImportError:
return unittest.skip("test requires joblibspark" )(lowerCamelCase_ )
else:
return test_case
def __snake_case ( lowerCamelCase_ : Any ):
'''simple docstring'''
if not _run_slow_tests or _run_slow_tests == 0:
__magic_name__ = unittest.skip("test is slow" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
if not _run_local_tests or _run_local_tests == 0:
__magic_name__ = unittest.skip("test is local" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : Tuple ):
'''simple docstring'''
if not _run_packaged_tests or _run_packaged_tests == 0:
__magic_name__ = unittest.skip("test is packaged" )(lowerCamelCase_ )
return test_case
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
if not _run_remote_tests or _run_remote_tests == 0:
__magic_name__ = unittest.skip("test requires remote" )(lowerCamelCase_ )
return test_case
def __snake_case ( *lowerCamelCase_ : Optional[int] ):
'''simple docstring'''
def decorate(cls : Optional[int] ):
for name, fn in cls.__dict__.items():
if callable(lowerCamelCase_ ) and name.startswith("test" ):
for decorator in decorators:
__magic_name__ = decorator(lowerCamelCase_ )
setattr(cls , lowerCamelCase_ , lowerCamelCase_ )
return cls
return decorate
class UpperCamelCase_ ( A ):
"""simple docstring"""
pass
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Optional[int] = 0
UpperCAmelCase__ : Optional[Any] = 1
UpperCAmelCase__ : List[Any] = 2
@contextmanager
def __snake_case ( lowerCamelCase_ : str=OfflineSimulationMode.CONNECTION_FAILS , lowerCamelCase_ : Tuple=1e-16 ):
'''simple docstring'''
__magic_name__ = requests.Session().request
def timeout_request(lowerCamelCase_ : int , lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] , **lowerCamelCase_ : Union[str, Any] ):
# Change the url to an invalid url so that the connection hangs
__magic_name__ = "https://10.255.255.1"
if kwargs.get("timeout" ) is None:
raise RequestWouldHangIndefinitelyError(
F'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.' )
__magic_name__ = timeout
try:
return online_request(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ )
except Exception as e:
# The following changes in the error are just here to make the offline timeout error prettier
__magic_name__ = url
__magic_name__ = e.args[0]
__magic_name__ = (max_retry_error.args[0].replace("10.255.255.1" , F'OfflineMock[{url}]' ),)
__magic_name__ = (max_retry_error,)
raise
def raise_connection_error(lowerCamelCase_ : str , lowerCamelCase_ : Any , **lowerCamelCase_ : Union[str, Any] ):
raise requests.ConnectionError("Offline mode is enabled." , request=lowerCamelCase_ )
if mode is OfflineSimulationMode.CONNECTION_FAILS:
with patch("requests.Session.send" , lowerCamelCase_ ):
yield
elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
# inspired from https://stackoverflow.com/a/904609
with patch("requests.Session.request" , lowerCamelCase_ ):
yield
elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
with patch("datasets.config.HF_DATASETS_OFFLINE" , lowerCamelCase_ ):
yield
else:
raise ValueError("Please use a value from the OfflineSimulationMode enum." )
@contextmanager
def __snake_case ( *lowerCamelCase_ : Union[str, Any] , **lowerCamelCase_ : int ):
'''simple docstring'''
__magic_name__ = str(Path().resolve() )
with tempfile.TemporaryDirectory(*lowerCamelCase_ , **lowerCamelCase_ ) as tmp_dir:
try:
os.chdir(lowerCamelCase_ )
yield
finally:
os.chdir(lowerCamelCase_ )
@contextmanager
def __snake_case ( ):
'''simple docstring'''
import gc
gc.collect()
__magic_name__ = pa.total_allocated_bytes()
yield
assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."
@contextmanager
def __snake_case ( ):
'''simple docstring'''
import gc
gc.collect()
__magic_name__ = pa.total_allocated_bytes()
yield
assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : Tuple ):
'''simple docstring'''
return deepcopy(lowerCamelCase_ ).integers(0 , 100 , 10 ).tolist() == deepcopy(lowerCamelCase_ ).integers(0 , 100 , 10 ).tolist()
def __snake_case ( lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
import decorator
from requests.exceptions import HTTPError
def _wrapper(lowerCamelCase_ : Dict , *lowerCamelCase_ : List[Any] , **lowerCamelCase_ : Any ):
try:
return func(*lowerCamelCase_ , **lowerCamelCase_ )
except HTTPError as err:
if str(lowerCamelCase_ ).startswith("500" ) or str(lowerCamelCase_ ).startswith("502" ):
pytest.xfail(str(lowerCamelCase_ ) )
raise err
return decorator.decorator(_wrapper , lowerCamelCase_ )
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : List[str] , _lowerCamelCase : int , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[Any] ) -> str:
__magic_name__ = returncode
__magic_name__ = stdout
__magic_name__ = stderr
async def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
while True:
__magic_name__ = await stream.readline()
if line:
callback(lowerCamelCase_ )
else:
break
async def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Optional[Any]=None , lowerCamelCase_ : Any=None , lowerCamelCase_ : Union[str, Any]=False , lowerCamelCase_ : Optional[Any]=False ):
'''simple docstring'''
if echo:
print("\nRunning: " , " ".join(lowerCamelCase_ ) )
__magic_name__ = await asyncio.create_subprocess_exec(
cmd[0] , *cmd[1:] , stdin=lowerCamelCase_ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowerCamelCase_ , )
# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
#
# If it starts hanging, will need to switch to the following code. The problem is that no data
# will be seen until it's done and if it hangs for example there will be no debug info.
# out, err = await p.communicate()
# return _RunOutput(p.returncode, out, err)
__magic_name__ = []
__magic_name__ = []
def tee(lowerCamelCase_ : List[str] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[str]="" ):
__magic_name__ = line.decode("utf-8" ).rstrip()
sink.append(lowerCamelCase_ )
if not quiet:
print(lowerCamelCase_ , lowerCamelCase_ , file=lowerCamelCase_ )
# XXX: the timeout doesn't seem to make any difference here
await asyncio.wait(
[
_read_stream(p.stdout , lambda lowerCamelCase_ : tee(lowerCamelCase_ , lowerCamelCase_ , sys.stdout , label="stdout:" ) ),
_read_stream(p.stderr , lambda lowerCamelCase_ : tee(lowerCamelCase_ , lowerCamelCase_ , sys.stderr , label="stderr:" ) ),
] , timeout=lowerCamelCase_ , )
return _RunOutput(await p.wait() , lowerCamelCase_ , lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : int=None , lowerCamelCase_ : Union[str, Any]=180 , lowerCamelCase_ : List[str]=False , lowerCamelCase_ : List[str]=True ):
'''simple docstring'''
__magic_name__ = asyncio.get_event_loop()
__magic_name__ = loop.run_until_complete(
_stream_subprocess(lowerCamelCase_ , env=lowerCamelCase_ , stdin=lowerCamelCase_ , timeout=lowerCamelCase_ , quiet=lowerCamelCase_ , echo=lowerCamelCase_ ) )
__magic_name__ = " ".join(lowerCamelCase_ )
if result.returncode > 0:
__magic_name__ = "\n".join(result.stderr )
raise RuntimeError(
F'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
F'The combined stderr from workers follows:\n{stderr}' )
# check that the subprocess actually did run and produced some output, should the test rely on
# the remote side to do the testing
if not result.stdout and not result.stderr:
raise RuntimeError(F'\'{cmd_str}\' produced no output.' )
return result
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = os.environ.get("PYTEST_XDIST_WORKER" , "gw0" )
__magic_name__ = re.sub(R"^gw" , "" , lowerCamelCase_ , 0 , re.M )
return int(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = 2_9500
__magic_name__ = pytest_xdist_worker_id()
return port + uniq_delta
| 664 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__magic_name__ : Optional[Any] ={
'configuration_longformer': [
'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'LongformerConfig',
'LongformerOnnxConfig',
],
'tokenization_longformer': ['LongformerTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : int =['LongformerTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Dict =[
'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'LongformerForMaskedLM',
'LongformerForMultipleChoice',
'LongformerForQuestionAnswering',
'LongformerForSequenceClassification',
'LongformerForTokenClassification',
'LongformerModel',
'LongformerPreTrainedModel',
'LongformerSelfAttention',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Tuple =[
'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFLongformerForMaskedLM',
'TFLongformerForMultipleChoice',
'TFLongformerForQuestionAnswering',
'TFLongformerForSequenceClassification',
'TFLongformerForTokenClassification',
'TFLongformerModel',
'TFLongformerPreTrainedModel',
'TFLongformerSelfAttention',
]
if TYPE_CHECKING:
from .configuration_longformer import (
LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
LongformerConfig,
LongformerOnnxConfig,
)
from .tokenization_longformer import LongformerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_longformer_fast import LongformerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_longformer import (
LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
LongformerForMaskedLM,
LongformerForMultipleChoice,
LongformerForQuestionAnswering,
LongformerForSequenceClassification,
LongformerForTokenClassification,
LongformerModel,
LongformerPreTrainedModel,
LongformerSelfAttention,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_longformer import (
TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLongformerForMaskedLM,
TFLongformerForMultipleChoice,
TFLongformerForQuestionAnswering,
TFLongformerForSequenceClassification,
TFLongformerForTokenClassification,
TFLongformerModel,
TFLongformerPreTrainedModel,
TFLongformerSelfAttention,
)
else:
import sys
__magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int = 1000 ):
'''simple docstring'''
return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) )
if __name__ == "__main__":
print(solution())
| 664 |
'''simple docstring'''
import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'):
__magic_name__ : str ={
'linear': PIL.Image.Resampling.BILINEAR,
'bilinear': PIL.Image.Resampling.BILINEAR,
'bicubic': PIL.Image.Resampling.BICUBIC,
'lanczos': PIL.Image.Resampling.LANCZOS,
'nearest': PIL.Image.Resampling.NEAREST,
}
else:
__magic_name__ : Tuple ={
'linear': PIL.Image.LINEAR,
'bilinear': PIL.Image.BILINEAR,
'bicubic': PIL.Image.BICUBIC,
'lanczos': PIL.Image.LANCZOS,
'nearest': PIL.Image.NEAREST,
}
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = (images / 2 + 0.5).clamp(0 , 1 )
__magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
__magic_name__ = numpy_to_pil(lowerCamelCase_ )
return images
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
if images.ndim == 3:
__magic_name__ = images[None, ...]
__magic_name__ = (images * 255).round().astype("uint8" )
if images.shape[-1] == 1:
# special case for grayscale (single channel) images
__magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images]
else:
__magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images]
return pil_images
| 664 | 1 |
'''simple docstring'''
import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig
if TYPE_CHECKING:
from ... import PreTrainedTokenizerBase, TensorType
__magic_name__ : List[Any] =logging.get_logger(__name__)
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : List[Any] = '''vision-encoder-decoder'''
UpperCAmelCase__ : Dict = True
def __init__( self : Tuple , **_lowerCamelCase : Dict ) -> Union[str, Any]:
super().__init__(**_lowerCamelCase )
if "encoder" not in kwargs or "decoder" not in kwargs:
raise ValueError(
f'A configuraton of type {self.model_type} cannot be instantiated because '
f'not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}' )
__magic_name__ = kwargs.pop("encoder" )
__magic_name__ = encoder_config.pop("model_type" )
__magic_name__ = kwargs.pop("decoder" )
__magic_name__ = decoder_config.pop("model_type" )
__magic_name__ = AutoConfig.for_model(_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = AutoConfig.for_model(_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = True
@classmethod
def __A ( cls : Dict , _lowerCamelCase : PretrainedConfig , _lowerCamelCase : PretrainedConfig , **_lowerCamelCase : int ) -> PretrainedConfig:
logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config" )
__magic_name__ = True
__magic_name__ = True
return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **_lowerCamelCase )
def __A ( self : List[str] ) -> Dict:
__magic_name__ = copy.deepcopy(self.__dict__ )
__magic_name__ = self.encoder.to_dict()
__magic_name__ = self.decoder.to_dict()
__magic_name__ = self.__class__.model_type
return output
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : int = version.parse('''1.11''' )
@property
def __A ( self : str ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
@property
def __A ( self : Union[str, Any] ) -> float:
return 1e-4
@property
def __A ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict({"last_hidden_state": {0: "batch", 1: "encoder_sequence"}} )
class UpperCamelCase_ ( A ):
"""simple docstring"""
@property
def __A ( self : int ) -> Mapping[str, Mapping[int, str]]:
__magic_name__ = OrderedDict()
__magic_name__ = {0: "batch", 1: "past_decoder_sequence + sequence"}
__magic_name__ = {0: "batch", 1: "past_decoder_sequence + sequence"}
__magic_name__ = {0: "batch", 1: "encoder_sequence"}
return common_inputs
def __A ( self : List[Any] , _lowerCamelCase : "PreTrainedTokenizerBase" , _lowerCamelCase : int = -1 , _lowerCamelCase : int = -1 , _lowerCamelCase : bool = False , _lowerCamelCase : Optional["TensorType"] = None , ) -> Mapping[str, Any]:
import torch
__magic_name__ = OrderedDict()
__magic_name__ = super().generate_dummy_inputs(
_lowerCamelCase , batch_size=_lowerCamelCase , seq_length=_lowerCamelCase , is_pair=_lowerCamelCase , framework=_lowerCamelCase )
__magic_name__ , __magic_name__ = dummy_input["input_ids"].shape
__magic_name__ = (batch, encoder_sequence, self._config.encoder_hidden_size)
__magic_name__ = dummy_input.pop("input_ids" )
__magic_name__ = dummy_input.pop("attention_mask" )
__magic_name__ = torch.zeros(_lowerCamelCase )
return common_inputs
class UpperCamelCase_ ( A ):
"""simple docstring"""
@property
def __A ( self : List[str] ) -> None:
pass
def __A ( self : Optional[int] , _lowerCamelCase : PretrainedConfig ) -> OnnxConfig:
return VisionEncoderDecoderEncoderOnnxConfig(_lowerCamelCase )
def __A ( self : Optional[Any] , _lowerCamelCase : PretrainedConfig , _lowerCamelCase : PretrainedConfig , _lowerCamelCase : str = "default" ) -> OnnxConfig:
__magic_name__ = encoder_config.hidden_size
return VisionEncoderDecoderDecoderOnnxConfig(_lowerCamelCase , _lowerCamelCase )
| 664 |
'''simple docstring'''
from typing import Dict
import numpy as np
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException
if is_tf_available():
import tensorflow as tf
from ..tf_utils import stable_softmax
if is_torch_available():
import torch
__magic_name__ : Optional[Any] =logging.get_logger(__name__)
@add_end_docstrings(
A , r'''
top_k (`int`, defaults to 5):
The number of predictions to return.
targets (`str` or `List[str]`, *optional*):
When passed, the model will limit the scores to the passed targets instead of looking up in the whole
vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
token will be used (with a warning, and that might be slower).
''' , )
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray:
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
elif self.framework == "pt":
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase )
else:
raise ValueError("Unsupported framework" )
return masked_index
def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray:
__magic_name__ = self.get_masked_index(_lowerCamelCase )
__magic_name__ = np.prod(masked_index.shape )
if numel < 1:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , )
def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
for model_input in model_inputs:
self._ensure_exactly_one_mask_token(model_input["input_ids"][0] )
else:
for input_ids in model_inputs["input_ids"]:
self._ensure_exactly_one_mask_token(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]:
if return_tensors is None:
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase )
self.ensure_exactly_one_mask_token(_lowerCamelCase )
return model_inputs
def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]:
__magic_name__ = self.model(**_lowerCamelCase )
__magic_name__ = model_inputs["input_ids"]
return model_outputs
def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict:
# Cap top_k if there are targets
if target_ids is not None and target_ids.shape[0] < top_k:
__magic_name__ = target_ids.shape[0]
__magic_name__ = model_outputs["input_ids"][0]
__magic_name__ = model_outputs["logits"]
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]
__magic_name__ = outputs.numpy()
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 )
if target_ids is not None:
__magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) )
__magic_name__ = tf.expand_dims(_lowerCamelCase , 0 )
__magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase )
__magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy()
else:
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 )
# Fill mask pipeline supports only one ${mask_token} per sample
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = logits.softmax(dim=-1 )
if target_ids is not None:
__magic_name__ = probs[..., target_ids]
__magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase )
__magic_name__ = []
__magic_name__ = values.shape[0] == 1
for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ):
__magic_name__ = []
for v, p in zip(_values , _predictions ):
# Copy is important since we're going to modify this array in place
__magic_name__ = input_ids.numpy().copy()
if target_ids is not None:
__magic_name__ = target_ids[p].tolist()
__magic_name__ = p
# Filter padding out:
__magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )]
# Originally we skip special tokens to give readable output.
# For multi masks though, the other [MASK] would be removed otherwise
# making the output look odd, so we add them back
__magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase )
__magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence}
row.append(_lowerCamelCase )
result.append(_lowerCamelCase )
if single_mask:
return result[0]
return result
def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = [targets]
try:
__magic_name__ = self.tokenizer.get_vocab()
except Exception:
__magic_name__ = {}
__magic_name__ = []
for target in targets:
__magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase )
if id_ is None:
__magic_name__ = self.tokenizer(
_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"]
if len(_lowerCamelCase ) == 0:
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
"We cannot replace it with anything meaningful, ignoring it" )
continue
__magic_name__ = input_ids[0]
# XXX: If users encounter this pass
# it becomes pretty slow, so let's make sure
# The warning enables them to fix the input to
# get faster performance.
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' )
target_ids.append(id_ )
__magic_name__ = list(set(_lowerCamelCase ) )
if len(_lowerCamelCase ) == 0:
raise ValueError("At least one target must be provided when passed." )
__magic_name__ = np.array(_lowerCamelCase )
return target_ids
def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple:
__magic_name__ = {}
if targets is not None:
__magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = target_ids
if top_k is not None:
__magic_name__ = top_k
if self.tokenizer.mask_token_id is None:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." )
return {}, {}, postprocess_params
def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]:
__magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase )
if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1:
return outputs[0]
return outputs
| 664 | 1 |
'''simple docstring'''
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
__magic_name__ : List[Any] =logging.get_logger(__name__)
__magic_name__ : Optional[Any] =list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__magic_name__ : List[str] =tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class UpperCamelCase_ :
"""simple docstring"""
UpperCAmelCase__ : str = field(
default=A , metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(A )} )
UpperCAmelCase__ : str = field(
default=A , metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''} )
UpperCAmelCase__ : int = field(
default=128 , metadata={
'''help''': (
'''The maximum total input sequence length after tokenization. Sequences longer '''
'''than this will be truncated, sequences shorter will be padded.'''
)
} , )
UpperCAmelCase__ : int = field(
default=128 , metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''} , )
UpperCAmelCase__ : int = field(
default=64 , metadata={
'''help''': (
'''The maximum number of tokens for the question. Questions longer than this will '''
'''be truncated to this length.'''
)
} , )
UpperCAmelCase__ : int = field(
default=30 , metadata={
'''help''': (
'''The maximum length of an answer that can be generated. This is needed because the start '''
'''and end predictions are not conditioned on one another.'''
)
} , )
UpperCAmelCase__ : bool = field(
default=A , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} )
UpperCAmelCase__ : bool = field(
default=A , metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''} )
UpperCAmelCase__ : float = field(
default=0.0 , metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''} )
UpperCAmelCase__ : int = field(
default=20 , metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''} )
UpperCAmelCase__ : int = field(
default=0 , metadata={
'''help''': (
'''language id of input for language-specific xlm models (see'''
''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
)
} , )
UpperCAmelCase__ : int = field(default=1 , metadata={'''help''': '''multiple threads for converting example to features'''} )
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Optional[int] = '''train'''
UpperCAmelCase__ : List[Any] = '''dev'''
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : SquadDataTrainingArguments
UpperCAmelCase__ : List[SquadFeatures]
UpperCAmelCase__ : Split
UpperCAmelCase__ : bool
def __init__( self : int , _lowerCamelCase : SquadDataTrainingArguments , _lowerCamelCase : PreTrainedTokenizer , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Union[str, Split] = Split.train , _lowerCamelCase : Optional[bool] = False , _lowerCamelCase : Optional[str] = None , _lowerCamelCase : Optional[str] = "pt" , ) -> Any:
__magic_name__ = args
__magic_name__ = is_language_sensitive
__magic_name__ = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
if isinstance(_lowerCamelCase , _lowerCamelCase ):
try:
__magic_name__ = Split[mode]
except KeyError:
raise KeyError("mode is not a valid split name" )
__magic_name__ = mode
# Load data features from cache or dataset file
__magic_name__ = "v2" if args.version_2_with_negative else "v1"
__magic_name__ = os.path.join(
cache_dir if cache_dir is not None else args.data_dir , f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}' , )
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
__magic_name__ = cached_features_file + ".lock"
with FileLock(_lowerCamelCase ):
if os.path.exists(_lowerCamelCase ) and not args.overwrite_cache:
__magic_name__ = time.time()
__magic_name__ = torch.load(_lowerCamelCase )
# Legacy cache files have only features, while new cache files
# will have dataset and examples also.
__magic_name__ = self.old_features["features"]
__magic_name__ = self.old_features.get("dataset" , _lowerCamelCase )
__magic_name__ = self.old_features.get("examples" , _lowerCamelCase )
logger.info(
f'Loading features from cached file {cached_features_file} [took %.3f s]' , time.time() - start )
if self.dataset is None or self.examples is None:
logger.warning(
f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
" future run" )
else:
if mode == Split.dev:
__magic_name__ = self.processor.get_dev_examples(args.data_dir )
else:
__magic_name__ = self.processor.get_train_examples(args.data_dir )
__magic_name__ , __magic_name__ = squad_convert_examples_to_features(
examples=self.examples , tokenizer=_lowerCamelCase , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=_lowerCamelCase , )
__magic_name__ = time.time()
torch.save(
{"features": self.features, "dataset": self.dataset, "examples": self.examples} , _lowerCamelCase , )
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' )
def __len__( self : Any ) -> Optional[Any]:
return len(self.features )
def __getitem__( self : str , _lowerCamelCase : Optional[Any] ) -> Dict[str, torch.Tensor]:
# Convert to Tensors and build dataset
__magic_name__ = self.features[i]
__magic_name__ = torch.tensor(feature.input_ids , dtype=torch.long )
__magic_name__ = torch.tensor(feature.attention_mask , dtype=torch.long )
__magic_name__ = torch.tensor(feature.token_type_ids , dtype=torch.long )
__magic_name__ = torch.tensor(feature.cls_index , dtype=torch.long )
__magic_name__ = torch.tensor(feature.p_mask , dtype=torch.float )
__magic_name__ = torch.tensor(feature.is_impossible , dtype=torch.float )
__magic_name__ = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
}
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
if self.args.model_type in ["xlnet", "xlm"]:
inputs.update({"cls_index": cls_index, "p_mask": p_mask} )
if self.args.version_2_with_negative:
inputs.update({"is_impossible": is_impossible} )
if self.is_language_sensitive:
inputs.update({"langs": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} )
if self.mode == Split.train:
__magic_name__ = torch.tensor(feature.start_position , dtype=torch.long )
__magic_name__ = torch.tensor(feature.end_position , dtype=torch.long )
inputs.update({"start_positions": start_positions, "end_positions": end_positions} )
return inputs
| 664 |
'''simple docstring'''
from __future__ import annotations
def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ):
'''simple docstring'''
if len(lowerCamelCase_ ) < k or k < 0:
raise ValueError("Invalid Input" )
__magic_name__ = __magic_name__ = sum(array[:k] )
for i in range(len(lowerCamelCase_ ) - k ):
__magic_name__ = current_sum - array[i] + array[i + k]
__magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ )
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
__magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)]
__magic_name__ : List[str] =randint(0, 1_10)
print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
| 664 | 1 |
'''simple docstring'''
import argparse
from collections import defaultdict
def __snake_case ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[int] ):
'''simple docstring'''
__magic_name__ = F'{file}_{class_name}_{test_name}'
done_test[_id] += 1
with open(lowerCamelCase_ , "r" ) as f:
__magic_name__ = f.readlines()
__magic_name__ = F'class {class_name}('
__magic_name__ = F'{4 * " "}def {test_name}('
__magic_name__ = F'{8 * " "}{correct_line.split()[0]}'
__magic_name__ = F'{16 * " "}{correct_line.split()[0]}'
__magic_name__ = False
__magic_name__ = False
__magic_name__ = False
__magic_name__ = False
__magic_name__ = 0
__magic_name__ = 0
__magic_name__ = []
for line in lines:
if line.startswith(lowerCamelCase_ ):
__magic_name__ = True
elif in_class and line.startswith(lowerCamelCase_ ):
__magic_name__ = True
elif in_class and in_func and (line.startswith(lowerCamelCase_ ) or line.startswith(lowerCamelCase_ )):
__magic_name__ = len(line.split(correct_line.split()[0] )[0] )
count += 1
if count == done_test[_id]:
__magic_name__ = True
if in_class and in_func and in_line:
if ")" not in line:
continue
else:
__magic_name__ = True
if in_class and in_func and in_line and insert_line:
new_lines.append(F'{spaces * " "}{correct_line}' )
__magic_name__ = __magic_name__ = __magic_name__ = __magic_name__ = False
else:
new_lines.append(lowerCamelCase_ )
with open(lowerCamelCase_ , "w" ) as f:
for line in new_lines:
f.write(lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : Tuple , lowerCamelCase_ : str=None ):
'''simple docstring'''
if fail is not None:
with open(lowerCamelCase_ , "r" ) as f:
__magic_name__ = {l.strip() for l in f.readlines()}
else:
__magic_name__ = None
with open(lowerCamelCase_ , "r" ) as f:
__magic_name__ = f.readlines()
__magic_name__ = defaultdict(lowerCamelCase_ )
for line in correct_lines:
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = line.split(";" )
if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures:
overwrite_file(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : Union[str, Any] =argparse.ArgumentParser()
parser.add_argument('--correct_filename', help='filename of tests with expected result')
parser.add_argument('--fail_filename', help='filename of test failures', type=str, default=None)
__magic_name__ : List[str] =parser.parse_args()
main(args.correct_filename, args.fail_filename)
| 664 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__magic_name__ : int =logging.get_logger(__name__)
__magic_name__ : List[Any] ={}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : int = '''llama'''
UpperCAmelCase__ : Any = ['''past_key_values''']
def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any:
__magic_name__ = vocab_size
__magic_name__ = max_position_embeddings
__magic_name__ = hidden_size
__magic_name__ = intermediate_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
__magic_name__ = num_attention_heads
__magic_name__ = num_key_value_heads
__magic_name__ = hidden_act
__magic_name__ = initializer_range
__magic_name__ = rms_norm_eps
__magic_name__ = pretraining_tp
__magic_name__ = use_cache
__magic_name__ = rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , )
def __A ( self : Union[str, Any] ) -> List[Any]:
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2:
raise ValueError(
"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
f'got {self.rope_scaling}' )
__magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase )
__magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' )
if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0:
raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
| 664 | 1 |
'''simple docstring'''
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel
from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@property
def __A ( self : Any ) -> Any:
torch.manual_seed(0 )
__magic_name__ = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , )
return model
@property
def __A ( self : List[Any] ) -> List[Any]:
torch.manual_seed(0 )
__magic_name__ = VQModel(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=3 , )
return model
@property
def __A ( self : Union[str, Any] ) -> Any:
torch.manual_seed(0 )
__magic_name__ = 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=10_00 , )
return CLIPTextModel(_lowerCamelCase )
def __A ( self : Optional[Any] ) -> int:
__magic_name__ = self.dummy_uncond_unet
__magic_name__ = DDIMScheduler()
__magic_name__ = self.dummy_vq_model
__magic_name__ = LDMPipeline(unet=_lowerCamelCase , vqvae=_lowerCamelCase , scheduler=_lowerCamelCase )
ldm.to(_lowerCamelCase )
ldm.set_progress_bar_config(disable=_lowerCamelCase )
__magic_name__ = torch.manual_seed(0 )
__magic_name__ = ldm(generator=_lowerCamelCase , num_inference_steps=2 , output_type="numpy" ).images
__magic_name__ = torch.manual_seed(0 )
__magic_name__ = ldm(generator=_lowerCamelCase , num_inference_steps=2 , output_type="numpy" , return_dict=_lowerCamelCase )[0]
__magic_name__ = image[0, -3:, -3:, -1]
__magic_name__ = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
__magic_name__ = np.array([0.8_512, 0.818, 0.6_411, 0.6_808, 0.4_465, 0.5_618, 0.46, 0.6_231, 0.5_172] )
__magic_name__ = 1e-2 if torch_device != "mps" else 3e-2
assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance
@slow
@require_torch
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Dict:
__magic_name__ = LDMPipeline.from_pretrained("CompVis/ldm-celebahq-256" )
ldm.to(_lowerCamelCase )
ldm.set_progress_bar_config(disable=_lowerCamelCase )
__magic_name__ = torch.manual_seed(0 )
__magic_name__ = ldm(generator=_lowerCamelCase , num_inference_steps=5 , output_type="numpy" ).images
__magic_name__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 2_56, 2_56, 3)
__magic_name__ = np.array([0.4_399, 0.44_975, 0.46_825, 0.474, 0.4_359, 0.4_581, 0.45_095, 0.4_341, 0.4_447] )
__magic_name__ = 1e-2 if torch_device != "mps" else 3e-2
assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
| 664 |
'''simple docstring'''
__magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1
def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or volume < 0:
raise ValueError("Invalid inputs. Enter positive value." )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume
def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or pressure < 0:
raise ValueError("Invalid inputs. Enter positive value." )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure
if __name__ == "__main__":
from doctest import testmod
testmod()
| 664 | 1 |
'''simple docstring'''
import argparse
import ast
import logging
import os
import sys
import pandas as pd
import torch
from tqdm import tqdm
from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging
sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip
__magic_name__ : Any =logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
transformers_logging.set_verbosity_info()
def __snake_case ( lowerCamelCase_ : Tuple ):
'''simple docstring'''
if "token" in model_name_or_path:
return "rag_token"
if "sequence" in model_name_or_path:
return "rag_sequence"
if "bart" in model_name_or_path:
return "bart"
return None
def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
return max(metric_fn(lowerCamelCase_ , lowerCamelCase_ ) for gt in ground_truths )
def __snake_case ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str , lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = [line.strip() for line in open(lowerCamelCase_ , "r" ).readlines()]
__magic_name__ = []
if args.gold_data_mode == "qa":
__magic_name__ = pd.read_csv(lowerCamelCase_ , sep="\t" , header=lowerCamelCase_ )
for answer_list in data[1]:
__magic_name__ = ast.literal_eval(lowerCamelCase_ )
answers.append(lowerCamelCase_ )
else:
__magic_name__ = [line.strip() for line in open(lowerCamelCase_ , "r" ).readlines()]
__magic_name__ = [[reference] for reference in references]
__magic_name__ = __magic_name__ = __magic_name__ = 0
for prediction, ground_truths in zip(lowerCamelCase_ , lowerCamelCase_ ):
total += 1
em += metric_max_over_ground_truths(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
fa += metric_max_over_ground_truths(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = 100.0 * em / total
__magic_name__ = 100.0 * fa / total
logger.info(F'F1: {fa:.2f}' )
logger.info(F'EM: {em:.2f}' )
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[str] ):
'''simple docstring'''
__magic_name__ = args.k
__magic_name__ = [line.strip() for line in open(lowerCamelCase_ , "r" ).readlines()]
__magic_name__ = [line.strip() for line in open(lowerCamelCase_ , "r" ).readlines()]
__magic_name__ = __magic_name__ = 0
for hypo, reference in zip(lowerCamelCase_ , lowerCamelCase_ ):
__magic_name__ = set(hypo.split("\t" )[:k] )
__magic_name__ = set(reference.split("\t" ) )
total += 1
em += len(hypo_provenance & ref_provenance ) / k
__magic_name__ = 100.0 * em / total
logger.info(F'Precision@{k}: {em: .2f}' )
def __snake_case ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
def strip_title(lowerCamelCase_ : Optional[int] ):
if title.startswith("\"" ):
__magic_name__ = title[1:]
if title.endswith("\"" ):
__magic_name__ = title[:-1]
return title
__magic_name__ = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
lowerCamelCase_ , return_tensors="pt" , padding=lowerCamelCase_ , truncation=lowerCamelCase_ , )["input_ids"].to(args.device )
__magic_name__ = rag_model.rag.question_encoder(lowerCamelCase_ )
__magic_name__ = question_enc_outputs[0]
__magic_name__ = rag_model.retriever(
lowerCamelCase_ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="pt" , )
__magic_name__ = rag_model.retriever.index.get_doc_dicts(result.doc_ids )
__magic_name__ = []
for docs in all_docs:
__magic_name__ = [strip_title(lowerCamelCase_ ) for title in docs["title"]]
provenance_strings.append("\t".join(lowerCamelCase_ ) )
return provenance_strings
def __snake_case ( lowerCamelCase_ : Tuple , lowerCamelCase_ : List[str] , lowerCamelCase_ : int ):
'''simple docstring'''
with torch.no_grad():
__magic_name__ = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
lowerCamelCase_ , return_tensors="pt" , padding=lowerCamelCase_ , truncation=lowerCamelCase_ )
__magic_name__ = inputs_dict.input_ids.to(args.device )
__magic_name__ = inputs_dict.attention_mask.to(args.device )
__magic_name__ = rag_model.generate( # rag_model overwrites generate
lowerCamelCase_ , attention_mask=lowerCamelCase_ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCamelCase_ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , )
__magic_name__ = rag_model.retriever.generator_tokenizer.batch_decode(lowerCamelCase_ , skip_special_tokens=lowerCamelCase_ )
if args.print_predictions:
for q, a in zip(lowerCamelCase_ , lowerCamelCase_ ):
logger.info("Q: {} - A: {}".format(lowerCamelCase_ , lowerCamelCase_ ) )
return answers
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = argparse.ArgumentParser()
parser.add_argument(
"--model_type" , choices=["rag_sequence", "rag_token", "bart"] , type=lowerCamelCase_ , help=(
"RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the"
" model_name_or_path"
) , )
parser.add_argument(
"--index_name" , default=lowerCamelCase_ , choices=["exact", "compressed", "legacy"] , type=lowerCamelCase_ , help="RAG model retriever type" , )
parser.add_argument(
"--index_path" , default=lowerCamelCase_ , type=lowerCamelCase_ , help="Path to the retrieval index" , )
parser.add_argument("--n_docs" , default=5 , type=lowerCamelCase_ , help="Number of retrieved docs" )
parser.add_argument(
"--model_name_or_path" , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help="Path to pretrained checkpoints or model identifier from huggingface.co/models" , )
parser.add_argument(
"--eval_mode" , choices=["e2e", "retrieval"] , default="e2e" , type=lowerCamelCase_ , help=(
"Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates"
" precision@k."
) , )
parser.add_argument("--k" , default=1 , type=lowerCamelCase_ , help="k for the precision@k calculation" )
parser.add_argument(
"--evaluation_set" , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help="Path to a file containing evaluation samples" , )
parser.add_argument(
"--gold_data_path" , default=lowerCamelCase_ , type=lowerCamelCase_ , required=lowerCamelCase_ , help="Path to a tab-separated file with gold samples" , )
parser.add_argument(
"--gold_data_mode" , default="qa" , type=lowerCamelCase_ , choices=["qa", "ans"] , help=(
"Format of the gold data file"
"qa - a single line in the following format: question [tab] answer_list"
"ans - a single line of the gold file contains the expected answer string"
) , )
parser.add_argument(
"--predictions_path" , type=lowerCamelCase_ , default="predictions.txt" , help="Name of the predictions file, to be stored in the checkpoints directory" , )
parser.add_argument(
"--eval_all_checkpoints" , action="store_true" , help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number" , )
parser.add_argument(
"--eval_batch_size" , default=8 , type=lowerCamelCase_ , help="Batch size per GPU/CPU for evaluation." , )
parser.add_argument(
"--recalculate" , help="Recalculate predictions even if the prediction file exists" , action="store_true" , )
parser.add_argument(
"--num_beams" , default=4 , type=lowerCamelCase_ , help="Number of beams to be used when generating answers" , )
parser.add_argument("--min_length" , default=1 , type=lowerCamelCase_ , help="Min length of the generated answers" )
parser.add_argument("--max_length" , default=50 , type=lowerCamelCase_ , help="Max length of the generated answers" )
parser.add_argument(
"--print_predictions" , action="store_true" , help="If True, prints predictions while evaluating." , )
parser.add_argument(
"--print_docs" , action="store_true" , help="If True, prints docs retried while generating." , )
__magic_name__ = parser.parse_args()
__magic_name__ = torch.device("cuda" if torch.cuda.is_available() else "cpu" )
return args
def __snake_case ( lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = {}
if args.model_type is None:
__magic_name__ = infer_model_type(args.model_name_or_path )
assert args.model_type is not None
if args.model_type.startswith("rag" ):
__magic_name__ = RagTokenForGeneration if args.model_type == "rag_token" else RagSequenceForGeneration
__magic_name__ = args.n_docs
if args.index_name is not None:
__magic_name__ = args.index_name
if args.index_path is not None:
__magic_name__ = args.index_path
else:
__magic_name__ = BartForConditionalGeneration
__magic_name__ = (
[f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()]
if args.eval_all_checkpoints
else [args.model_name_or_path]
)
logger.info("Evaluate the following checkpoints: %s" , lowerCamelCase_ )
__magic_name__ = get_scores if args.eval_mode == "e2e" else get_precision_at_k
__magic_name__ = evaluate_batch_eae if args.eval_mode == "e2e" else evaluate_batch_retrieval
for checkpoint in checkpoints:
if os.path.exists(args.predictions_path ) and (not args.recalculate):
logger.info("Calculating metrics based on an existing predictions file: {}".format(args.predictions_path ) )
score_fn(lowerCamelCase_ , args.predictions_path , args.gold_data_path )
continue
logger.info("***** Running evaluation for {} *****".format(lowerCamelCase_ ) )
logger.info(" Batch size = %d" , args.eval_batch_size )
logger.info(" Predictions will be stored under {}".format(args.predictions_path ) )
if args.model_type.startswith("rag" ):
__magic_name__ = RagRetriever.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ = model_class.from_pretrained(lowerCamelCase_ , retriever=lowerCamelCase_ , **lowerCamelCase_ )
model.retriever.init_retrieval()
else:
__magic_name__ = model_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ )
model.to(args.device )
with open(args.evaluation_set , "r" ) as eval_file, open(args.predictions_path , "w" ) as preds_file:
__magic_name__ = []
for line in tqdm(lowerCamelCase_ ):
questions.append(line.strip() )
if len(lowerCamelCase_ ) == args.eval_batch_size:
__magic_name__ = evaluate_batch_fn(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
preds_file.write("\n".join(lowerCamelCase_ ) + "\n" )
preds_file.flush()
__magic_name__ = []
if len(lowerCamelCase_ ) > 0:
__magic_name__ = evaluate_batch_fn(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
preds_file.write("\n".join(lowerCamelCase_ ) )
preds_file.flush()
score_fn(lowerCamelCase_ , args.predictions_path , args.gold_data_path )
if __name__ == "__main__":
__magic_name__ : Union[str, Any] =get_args()
main(args)
| 664 |
'''simple docstring'''
import logging
import os
from typing import List, TextIO, Union
from conllu import parse_incr
from utils_ner import InputExample, Split, TokenClassificationTask
__magic_name__ : List[Any] =logging.getLogger(__name__)
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]:
# in NER datasets, the last column is usually reserved for NER label
__magic_name__ = label_idx
def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = mode.value
__magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' )
__magic_name__ = 1
__magic_name__ = []
with open(_lowerCamelCase , encoding="utf-8" ) as f:
__magic_name__ = []
__magic_name__ = []
for line in f:
if line.startswith("-DOCSTART-" ) or line == "" or line == "\n":
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
guid_index += 1
__magic_name__ = []
__magic_name__ = []
else:
__magic_name__ = line.split(" " )
words.append(splits[0] )
if len(_lowerCamelCase ) > 1:
labels.append(splits[self.label_idx].replace("\n" , "" ) )
else:
# Examples could have no label for mode = "test"
labels.append("O" )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
return examples
def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]:
__magic_name__ = 0
for line in test_input_reader:
if line.startswith("-DOCSTART-" ) or line == "" or line == "\n":
writer.write(_lowerCamelCase )
if not preds_list[example_id]:
example_id += 1
elif preds_list[example_id]:
__magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n"
writer.write(_lowerCamelCase )
else:
logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] )
def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
__magic_name__ = f.read().splitlines()
if "O" not in labels:
__magic_name__ = ["O"] + labels
return labels
else:
return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : int ) -> str:
# in CONLL2003 dataset chunk column is second-to-last
super().__init__(label_idx=-2 )
def __A ( self : int , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
__magic_name__ = f.read().splitlines()
if "O" not in labels:
__magic_name__ = ["O"] + labels
return labels
else:
return [
"O",
"B-ADVP",
"B-INTJ",
"B-LST",
"B-PRT",
"B-NP",
"B-SBAR",
"B-VP",
"B-ADJP",
"B-CONJP",
"B-PP",
"I-ADVP",
"I-INTJ",
"I-LST",
"I-PRT",
"I-NP",
"I-SBAR",
"I-VP",
"I-ADJP",
"I-CONJP",
"I-PP",
]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = mode.value
__magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' )
__magic_name__ = 1
__magic_name__ = []
with open(_lowerCamelCase , encoding="utf-8" ) as f:
for sentence in parse_incr(_lowerCamelCase ):
__magic_name__ = []
__magic_name__ = []
for token in sentence:
words.append(token["form"] )
labels.append(token["upos"] )
assert len(_lowerCamelCase ) == len(_lowerCamelCase )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
guid_index += 1
return examples
def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any:
__magic_name__ = 0
for sentence in parse_incr(_lowerCamelCase ):
__magic_name__ = preds_list[example_id]
__magic_name__ = ""
for token in sentence:
out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) '
out += "\n"
writer.write(_lowerCamelCase )
example_id += 1
def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
return f.read().splitlines()
else:
return [
"ADJ",
"ADP",
"ADV",
"AUX",
"CCONJ",
"DET",
"INTJ",
"NOUN",
"NUM",
"PART",
"PRON",
"PROPN",
"PUNCT",
"SCONJ",
"SYM",
"VERB",
"X",
]
| 664 | 1 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__magic_name__ : Optional[Any] =logging.get_logger(__name__)
__magic_name__ : List[Any] ={
'uclanlp/visualbert-vqa': 'https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json',
'uclanlp/visualbert-vqa-pre': 'https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json',
'uclanlp/visualbert-vqa-coco-pre': (
'https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json'
),
'uclanlp/visualbert-vcr': 'https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json',
'uclanlp/visualbert-vcr-pre': 'https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json',
'uclanlp/visualbert-vcr-coco-pre': (
'https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json'
),
'uclanlp/visualbert-nlvr2': 'https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json',
'uclanlp/visualbert-nlvr2-pre': 'https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json',
'uclanlp/visualbert-nlvr2-coco-pre': (
'https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json'
)
# See all VisualBERT models at https://huggingface.co/models?filter=visual_bert
}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = '''visual_bert'''
def __init__( self : str , _lowerCamelCase : List[Any]=3_05_22 , _lowerCamelCase : int=7_68 , _lowerCamelCase : int=5_12 , _lowerCamelCase : int=12 , _lowerCamelCase : List[Any]=12 , _lowerCamelCase : Any=30_72 , _lowerCamelCase : Any="gelu" , _lowerCamelCase : List[Any]=0.1 , _lowerCamelCase : Optional[Any]=0.1 , _lowerCamelCase : List[Any]=5_12 , _lowerCamelCase : Optional[int]=2 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Optional[int]=1e-12 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : int=True , _lowerCamelCase : str=1 , _lowerCamelCase : List[Any]=0 , _lowerCamelCase : Tuple=2 , **_lowerCamelCase : int , ) -> str:
super().__init__(pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = vocab_size
__magic_name__ = max_position_embeddings
__magic_name__ = hidden_size
__magic_name__ = visual_embedding_dim
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
__magic_name__ = intermediate_size
__magic_name__ = hidden_act
__magic_name__ = hidden_dropout_prob
__magic_name__ = attention_probs_dropout_prob
__magic_name__ = initializer_range
__magic_name__ = type_vocab_size
__magic_name__ = layer_norm_eps
__magic_name__ = bypass_transformer
__magic_name__ = special_visual_initialize
| 664 |
'''simple docstring'''
from __future__ import annotations
from typing import Any
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None:
__magic_name__ , __magic_name__ = row, column
__magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )]
def __str__( self : Optional[Any] ) -> str:
__magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n'
# Make string identifier
__magic_name__ = 0
for row_vector in self.array:
for obj in row_vector:
__magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) )
__magic_name__ = f'%{max_element_length}s'
# Make string and return
def single_line(_lowerCamelCase : list[float] ) -> str:
nonlocal string_format_identifier
__magic_name__ = "["
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector )
line += "]"
return line
s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array )
return s
def __repr__( self : Optional[int] ) -> str:
return str(self )
def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool:
if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2):
return False
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
return False
else:
return True
def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any:
assert self.validate_indicies(_lowerCamelCase )
return self.array[loc[0]][loc[1]]
def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None:
assert self.validate_indicies(_lowerCamelCase )
__magic_name__ = value
def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix:
assert isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == another.row and self.column == another.column
# Add
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] + another[r, c]
return result
def __neg__( self : int ) -> Matrix:
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = -self[r, c]
return result
def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix:
return self + (-another)
def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix:
if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] * another
return result
elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication
assert self.column == another.row
__magic_name__ = Matrix(self.row , another.column )
for r in range(self.row ):
for c in range(another.column ):
for i in range(self.column ):
result[r, c] += self[r, i] * another[i, c]
return result
else:
__magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})'
raise TypeError(_lowerCamelCase )
def __A ( self : Optional[int] ) -> Matrix:
__magic_name__ = Matrix(self.column , self.row )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c]
return result
def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any:
assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == self.column == u.row == v.row # u, v should be column vector
assert u.column == v.column == 1 # u, v should be column vector
# Calculate
__magic_name__ = v.transpose()
__magic_name__ = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
# Testing
if __name__ == "__main__":
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Matrix(3 , 3 , 0 )
for i in range(3 ):
__magic_name__ = 1
print(F'a^(-1) is {ainv}' )
# u, v
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5
print(F'u is {u}' )
print(F'v is {v}' )
print(F'uv^T is {u * v.transpose()}' )
# Sherman Morrison
print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' )
def __snake_case ( ):
'''simple docstring'''
import doctest
doctest.testmod()
testa()
| 664 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional
from packaging import version
if TYPE_CHECKING:
from ... import PreTrainedTokenizer, TensorType
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging
__magic_name__ : Union[str, Any] =logging.get_logger(__name__)
__magic_name__ : Dict ={
'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json',
'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json',
'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json',
'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json',
'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json',
'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json',
}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : List[Any] = '''bloom'''
UpperCAmelCase__ : List[str] = ['''past_key_values''']
UpperCAmelCase__ : Any = {
'''num_hidden_layers''': '''n_layer''',
'''num_attention_heads''': '''n_head''',
}
def __init__( self : Dict , _lowerCamelCase : str=25_08_80 , _lowerCamelCase : Union[str, Any]=64 , _lowerCamelCase : List[str]=2 , _lowerCamelCase : List[str]=8 , _lowerCamelCase : Tuple=1e-5 , _lowerCamelCase : Optional[int]=0.02 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Optional[int]=1 , _lowerCamelCase : str=2 , _lowerCamelCase : Dict=False , _lowerCamelCase : Any=0.0 , _lowerCamelCase : Tuple=0.0 , _lowerCamelCase : Optional[int]=1 , _lowerCamelCase : Tuple=False , **_lowerCamelCase : Any , ) -> Union[str, Any]:
__magic_name__ = vocab_size
# Backward compatibility with n_embed kwarg
__magic_name__ = kwargs.pop("n_embed" , _lowerCamelCase )
__magic_name__ = hidden_size if n_embed is None else n_embed
__magic_name__ = n_layer
__magic_name__ = n_head
__magic_name__ = layer_norm_epsilon
__magic_name__ = initializer_range
__magic_name__ = use_cache
__magic_name__ = pretraining_tp
__magic_name__ = apply_residual_connection_post_layernorm
__magic_name__ = hidden_dropout
__magic_name__ = attention_dropout
__magic_name__ = bos_token_id
__magic_name__ = eos_token_id
__magic_name__ = slow_but_exact
super().__init__(bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase )
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : List[str] = version.parse('''1.12''' )
def __init__( self : str , _lowerCamelCase : PretrainedConfig , _lowerCamelCase : str = "default" , _lowerCamelCase : List[PatchingSpec] = None , _lowerCamelCase : bool = False , ) -> Optional[Any]:
super().__init__(_lowerCamelCase , task=_lowerCamelCase , patching_specs=_lowerCamelCase , use_past=_lowerCamelCase )
if not getattr(self._config , "pad_token_id" , _lowerCamelCase ):
# TODO: how to do that better?
__magic_name__ = 0
@property
def __A ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]:
__magic_name__ = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} )
if self.use_past:
# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
self.fill_with_past_key_values_(_lowerCamelCase , direction="inputs" , inverted_values_shape=_lowerCamelCase )
__magic_name__ = {0: "batch", 1: "past_sequence + sequence"}
else:
__magic_name__ = {0: "batch", 1: "sequence"}
return common_inputs
@property
def __A ( self : List[str] ) -> int:
return self._config.n_layer
@property
def __A ( self : int ) -> int:
return self._config.n_head
@property
def __A ( self : str ) -> float:
return 1e-3
def __A ( self : List[str] , _lowerCamelCase : "PreTrainedTokenizer" , _lowerCamelCase : int = -1 , _lowerCamelCase : int = -1 , _lowerCamelCase : bool = False , _lowerCamelCase : Optional["TensorType"] = None , ) -> Mapping[str, Any]:
__magic_name__ = super(_lowerCamelCase , self ).generate_dummy_inputs(
_lowerCamelCase , batch_size=_lowerCamelCase , seq_length=_lowerCamelCase , is_pair=_lowerCamelCase , framework=_lowerCamelCase )
# We need to order the input in the way they appears in the forward()
__magic_name__ = OrderedDict({"input_ids": common_inputs["input_ids"]} )
# Need to add the past_keys
if self.use_past:
if not is_torch_available():
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." )
else:
import torch
__magic_name__ , __magic_name__ = common_inputs["input_ids"].shape
# Not using the same length for past_key_values
__magic_name__ = seqlen + 2
__magic_name__ = self._config.hidden_size // self.num_attention_heads
__magic_name__ = (
batch * self.num_attention_heads,
head_dim,
past_key_values_length,
)
__magic_name__ = (
batch * self.num_attention_heads,
past_key_values_length,
head_dim,
)
__magic_name__ = [
(torch.zeros(_lowerCamelCase ), torch.zeros(_lowerCamelCase )) for _ in range(self.num_layers )
]
__magic_name__ = common_inputs["attention_mask"]
if self.use_past:
__magic_name__ = ordered_inputs["attention_mask"].dtype
__magic_name__ = torch.cat(
[ordered_inputs["attention_mask"], torch.ones(_lowerCamelCase , _lowerCamelCase , dtype=_lowerCamelCase )] , dim=1 )
return ordered_inputs
@property
def __A ( self : Optional[Any] ) -> int:
return 13
| 664 |
'''simple docstring'''
import argparse
import logging
from collections import namedtuple
import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer # The authors' implementation
from transformers import BertTokenizer
logging.basicConfig(level=logging.INFO)
__magic_name__ : List[Any] =logging.getLogger(__name__)
__magic_name__ : int ='Hello world! cécé herlolip'
__magic_name__ : List[Any] =namedtuple(
'BertAbsConfig',
[
'temp_dir',
'large',
'use_bert_emb',
'finetune_bert',
'encoder',
'share_emb',
'max_pos',
'enc_layers',
'enc_hidden_size',
'enc_heads',
'enc_ff_size',
'enc_dropout',
'dec_layers',
'dec_hidden_size',
'dec_heads',
'dec_ff_size',
'dec_dropout',
],
)
def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ):
'''simple docstring'''
__magic_name__ = BertAbsConfig(
temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , )
__magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage )
__magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ )
original.eval()
__magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) )
new_model.eval()
# -------------------
# Convert the weights
# -------------------
logging.info("convert the model" )
new_model.bert.load_state_dict(original.bert.state_dict() )
new_model.decoder.load_state_dict(original.decoder.state_dict() )
new_model.generator.load_state_dict(original.generator.state_dict() )
# ----------------------------------
# Make sure the outpus are identical
# ----------------------------------
logging.info("Make sure that the models' outputs are identical" )
__magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" )
# prepare the model inputs
__magic_name__ = tokenizer.encode("This is sample éàalj'-." )
encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
__magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." )
decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
# failsafe to make sure the weights reset does not affect the
# loaded weights.
assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0
# forward pass
__magic_name__ = encoder_input_ids
__magic_name__ = decoder_input_ids
__magic_name__ = __magic_name__ = None
__magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = None
# The original model does not apply the geneator layer immediatly but rather in
# the beam search (where it combines softmax + linear layer). Since we already
# apply the softmax in our generation process we only apply the linear layer here.
# We make sure that the outputs of the full stack are identical
__magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = original.generator(lowerCamelCase_ )
__magic_name__ = new_model(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = new_model.generator(lowerCamelCase_ )
__magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if are_identical:
logging.info("all weights are equal up to 1e-3" )
else:
raise ValueError("the weights are different. The new model is likely different from the original one." )
# The model has been saved with torch.save(model) and this is bound to the exact
# directory structure. We save the state_dict instead.
logging.info("saving the model's state dictionary" )
torch.save(
new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" )
if __name__ == "__main__":
__magic_name__ : Dict =argparse.ArgumentParser()
parser.add_argument(
'--bertabs_checkpoint_path',
default=None,
type=str,
required=True,
help='Path the official PyTorch dump.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
required=True,
help='Path to the output PyTorch model.',
)
__magic_name__ : Any =parser.parse_args()
convert_bertabs_checkpoints(
args.bertabs_checkpoint_path,
args.pytorch_dump_folder_path,
)
| 664 | 1 |
'''simple docstring'''
import os
import unittest
from huggingface_hub.utils import are_progress_bars_disabled
import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : str ) -> str:
__magic_name__ = logging.get_logger()
# the current default level is logging.WARNING
__magic_name__ = logging.get_verbosity()
logging.set_verbosity_error()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() )
logging.set_verbosity_warning()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() )
logging.set_verbosity_info()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() )
logging.set_verbosity_debug()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() )
# restore to the original level
logging.set_verbosity(_lowerCamelCase )
def __A ( self : Dict ) -> Dict:
__magic_name__ = logging.get_verbosity()
__magic_name__ = logging.get_logger("transformers.models.bart.tokenization_bart" )
__magic_name__ = "Testing 1, 2, 3"
# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
if level_origin <= logging.WARNING:
with CaptureLogger(_lowerCamelCase ) as cl:
logger.warning(_lowerCamelCase )
self.assertEqual(cl.out , msg + "\n" )
# this is setting the level for all of `transformers.*` loggers
logging.set_verbosity_error()
# should not be able to log warnings
with CaptureLogger(_lowerCamelCase ) as cl:
logger.warning(_lowerCamelCase )
self.assertEqual(cl.out , "" )
# should be able to log warnings again
logging.set_verbosity_warning()
with CaptureLogger(_lowerCamelCase ) as cl:
logger.warning(_lowerCamelCase )
self.assertEqual(cl.out , msg + "\n" )
# restore to the original level
logging.set_verbosity(_lowerCamelCase )
@mockenv(TRANSFORMERS_VERBOSITY="error" )
def __A ( self : str ) -> List[str]:
# reset for the env var to take effect, next time some logger call is made
transformers.utils.logging._reset_library_root_logger()
# this action activates the env var
__magic_name__ = logging.get_logger("transformers.models.bart.tokenization_bart" )
__magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , _lowerCamelCase )
__magic_name__ = logging.log_levels[env_level_str]
__magic_name__ = logging.get_verbosity()
self.assertEqual(
_lowerCamelCase , _lowerCamelCase , f'TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}' , )
# restore to the original level
__magic_name__ = ""
transformers.utils.logging._reset_library_root_logger()
@mockenv(TRANSFORMERS_VERBOSITY="super-error" )
def __A ( self : Optional[int] ) -> List[Any]:
# reset for the env var to take effect, next time some logger call is made
transformers.utils.logging._reset_library_root_logger()
__magic_name__ = logging.logging.getLogger()
with CaptureLogger(_lowerCamelCase ) as cl:
# this action activates the env var
logging.get_logger("transformers.models.bart.tokenization_bart" )
self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out )
# no need to restore as nothing was changed
def __A ( self : List[Any] ) -> str:
# testing `logger.warning_advice()`
transformers.utils.logging._reset_library_root_logger()
__magic_name__ = logging.get_logger("transformers.models.bart.tokenization_bart" )
__magic_name__ = "Testing 1, 2, 3"
with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ):
# nothing should be logged as env var disables this method
with CaptureLogger(_lowerCamelCase ) as cl:
logger.warning_advice(_lowerCamelCase )
self.assertEqual(cl.out , "" )
with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ):
# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
with CaptureLogger(_lowerCamelCase ) as cl:
logger.warning_advice(_lowerCamelCase )
self.assertEqual(cl.out , msg + "\n" )
def __snake_case ( ):
'''simple docstring'''
disable_progress_bar()
assert are_progress_bars_disabled()
enable_progress_bar()
assert not are_progress_bars_disabled()
| 664 |
'''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.generation import DisjunctiveConstraint
@require_torch
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : List[str] ) -> str:
# For consistency across different places the DisjunctiveConstraint is called,
# dc.token_ids is a list of integers. It is also initialized only by integers.
__magic_name__ = [[1, 2, 4], [1, 2, 3, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] )
def __A ( self : List[Any] ) -> str:
# We can't have constraints that are complete subsets of another. This leads to a preverse
# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
__magic_name__ = [[1, 2], [1, 2, 3, 4]]
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(_lowerCamelCase ) # fails here
def __A ( self : List[Any] ) -> int:
__magic_name__ = [[1, 2, 3], [1, 2, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 )
__magic_name__ = stepped is True and completed is True and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 3] )
def __A ( self : Any ) -> Union[str, Any]:
__magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2, 4] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 4, 5] )
dc.reset()
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 3 )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 2 )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.remaining() == 0 )
self.assertTrue(dc.current_seq == [1, 2, 5] )
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
import matplotlib.pyplot as plt # type: ignore
import numpy
# initial triangle of Koch snowflake
__magic_name__ : Optional[Any] =numpy.array([0, 0])
__magic_name__ : List[str] =numpy.array([0.5, 0.8_6_6_0_2_5_4])
__magic_name__ : str =numpy.array([1, 0])
__magic_name__ : Tuple =[VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
def __snake_case ( lowerCamelCase_ : list[numpy.ndarray] , lowerCamelCase_ : int ):
'''simple docstring'''
__magic_name__ = initial_vectors
for _ in range(lowerCamelCase_ ):
__magic_name__ = iteration_step(lowerCamelCase_ )
return vectors
def __snake_case ( lowerCamelCase_ : list[numpy.ndarray] ):
'''simple docstring'''
__magic_name__ = []
for i, start_vector in enumerate(vectors[:-1] ):
__magic_name__ = vectors[i + 1]
new_vectors.append(lowerCamelCase_ )
__magic_name__ = end_vector - start_vector
new_vectors.append(start_vector + difference_vector / 3 )
new_vectors.append(
start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) )
new_vectors.append(start_vector + difference_vector * 2 / 3 )
new_vectors.append(vectors[-1] )
return new_vectors
def __snake_case ( lowerCamelCase_ : numpy.ndarray , lowerCamelCase_ : float ):
'''simple docstring'''
__magic_name__ = numpy.radians(lowerCamelCase_ )
__magic_name__ , __magic_name__ = numpy.cos(lowerCamelCase_ ), numpy.sin(lowerCamelCase_ )
__magic_name__ = numpy.array(((c, -s), (s, c)) )
return numpy.dot(lowerCamelCase_ , lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : list[numpy.ndarray] ):
'''simple docstring'''
__magic_name__ = plt.gca()
axes.set_aspect("equal" )
# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
# y-coordinates as inputs, which are constructed from the vector-list using
# zip()
__magic_name__ , __magic_name__ = zip(*lowerCamelCase_ )
plt.plot(lowerCamelCase_ , lowerCamelCase_ )
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
__magic_name__ : Tuple =iterate(INITIAL_VECTORS, 5)
plot(processed_vectors)
| 664 |
'''simple docstring'''
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
__magic_name__ : Dict ={
'return_dict': False,
'output_hidden_states': True,
'output_attentions': True,
'torchscript': True,
'torch_dtype': 'float16',
'use_bfloat16': True,
'tf_legacy_loss': True,
'pruned_heads': {'a': 1},
'tie_word_embeddings': False,
'is_decoder': True,
'cross_attention_hidden_size': 1_28,
'add_cross_attention': True,
'tie_encoder_decoder': True,
'max_length': 50,
'min_length': 3,
'do_sample': True,
'early_stopping': True,
'num_beams': 3,
'num_beam_groups': 3,
'diversity_penalty': 0.5,
'temperature': 2.0,
'top_k': 10,
'top_p': 0.7,
'typical_p': 0.2,
'repetition_penalty': 0.8,
'length_penalty': 0.8,
'no_repeat_ngram_size': 5,
'encoder_no_repeat_ngram_size': 5,
'bad_words_ids': [1, 2, 3],
'num_return_sequences': 3,
'chunk_size_feed_forward': 5,
'output_scores': True,
'return_dict_in_generate': True,
'forced_bos_token_id': 2,
'forced_eos_token_id': 3,
'remove_invalid_values': True,
'architectures': ['BertModel'],
'finetuning_task': 'translation',
'id2label': {0: 'label'},
'label2id': {'label': '0'},
'tokenizer_class': 'BertTokenizerFast',
'prefix': 'prefix',
'bos_token_id': 6,
'pad_token_id': 7,
'eos_token_id': 8,
'sep_token_id': 9,
'decoder_start_token_id': 10,
'exponential_decay_length_penalty': (5, 1.0_1),
'suppress_tokens': [0, 1],
'begin_suppress_tokens': 2,
'task_specific_params': {'translation': 'some_params'},
'problem_type': 'regression',
}
@is_staging_test
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def __A ( cls : Any ) -> Union[str, Any]:
__magic_name__ = TOKEN
HfFolder.save_token(_lowerCamelCase )
@classmethod
def __A ( cls : Any ) -> Tuple:
try:
delete_repo(token=cls._token , repo_id="test-config" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-config-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-config" )
except HTTPError:
pass
def __A ( self : Optional[Any] ) -> Dict:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("test-config" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="test-config" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : str ) -> Optional[int]:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-config-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
_lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : Optional[int] ) -> Union[str, Any]:
CustomConfig.register_for_auto_class()
__magic_name__ = CustomConfig(attribute=42 )
config.push_to_hub("test-dynamic-config" , use_auth_token=self._token )
# This has added the proper auto_map field to the config
self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} )
__magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase )
# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
self.assertEqual(new_config.__class__.__name__ , "CustomConfig" )
self.assertEqual(new_config.attribute , 42 )
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Optional[Any]:
__magic_name__ = GPTaConfig()
# attempt to modify each of int/float/bool/str config records and verify they were updated
__magic_name__ = c.n_embd + 1 # int
__magic_name__ = c.resid_pdrop + 1.0 # float
__magic_name__ = not c.scale_attn_weights # bool
__magic_name__ = c.summary_type + "foo" # str
c.update_from_string(
f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' )
self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" )
self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" )
self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" )
self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" )
def __A ( self : List[Any] ) -> Union[str, Any]:
__magic_name__ = PretrainedConfig()
__magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to addin config_common_kwargs above.
self.assertListEqual(
_lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] )
__magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )]
if len(_lowerCamelCase ) > 0:
raise ValueError(
"The following keys are set with the default values in"
" `test_configuration_common.config_common_kwargs` pick another value for them:"
f' {", ".join(_lowerCamelCase )}.' )
def __A ( self : List[Any] ) -> List[Any]:
with self.assertRaises(_lowerCamelCase ):
# config is in subfolder, the following should not work without specifying the subfolder
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" )
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" )
self.assertIsNotNone(_lowerCamelCase )
def __A ( self : Tuple ) -> int:
# A mock response for an HTTP head request to emulate server down
__magic_name__ = mock.Mock()
__magic_name__ = 5_00
__magic_name__ = {}
__magic_name__ = HTTPError
__magic_name__ = {}
# Download this model to make sure it's in the cache.
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head:
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
def __A ( self : Union[str, Any] ) -> Dict:
# This test is for deprecated behavior and can be removed in v5
__magic_name__ = BertConfig.from_pretrained(
"https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" )
def __A ( self : Dict ) -> Optional[int]:
__magic_name__ = AutoConfig.from_pretrained("bert-base-cased" )
__magic_name__ = ["config.4.0.0.json"]
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(_lowerCamelCase )
__magic_name__ = 2
json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) )
# This should pick the new configuration file as the version of Transformers is > 4.0.0
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
__magic_name__ = ["config.42.0.0.json"]
__magic_name__ = 7_68
configuration.save_pretrained(_lowerCamelCase )
shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) )
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 7_68 )
def __A ( self : Optional[int] ) -> str:
# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
__magic_name__ = "hf-internal-testing/test-two-configs"
import transformers as new_transformers
__magic_name__ = "v4.0.0"
__magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained(
_lowerCamelCase , return_unused_kwargs=_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(_lowerCamelCase , {} )
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
__magic_name__ = "v3.0.0"
__magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(old_configuration.hidden_size , 7_68 )
| 664 | 1 |
'''simple docstring'''
import inspect
import unittest
from transformers import ViTMSNConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ViTMSNForImageClassification, ViTMSNModel
from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Optional[int] , _lowerCamelCase : Any , _lowerCamelCase : Any=13 , _lowerCamelCase : List[Any]=30 , _lowerCamelCase : List[str]=2 , _lowerCamelCase : List[str]=3 , _lowerCamelCase : Any=True , _lowerCamelCase : Optional[Any]=True , _lowerCamelCase : Optional[Any]=32 , _lowerCamelCase : Any=5 , _lowerCamelCase : Union[str, Any]=4 , _lowerCamelCase : Dict=37 , _lowerCamelCase : Union[str, Any]="gelu" , _lowerCamelCase : Any=0.1 , _lowerCamelCase : Dict=0.1 , _lowerCamelCase : Tuple=10 , _lowerCamelCase : Optional[int]=0.02 , _lowerCamelCase : Optional[Any]=None , ) -> List[str]:
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = image_size
__magic_name__ = patch_size
__magic_name__ = num_channels
__magic_name__ = is_training
__magic_name__ = use_labels
__magic_name__ = hidden_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
__magic_name__ = intermediate_size
__magic_name__ = hidden_act
__magic_name__ = hidden_dropout_prob
__magic_name__ = attention_probs_dropout_prob
__magic_name__ = type_sequence_label_size
__magic_name__ = initializer_range
__magic_name__ = scope
# in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
__magic_name__ = (image_size // patch_size) ** 2
__magic_name__ = num_patches + 1
def __A ( self : Dict ) -> Optional[Any]:
__magic_name__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__magic_name__ = self.get_config()
return config, pixel_values, labels
def __A ( self : int ) -> Optional[int]:
return ViTMSNConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , 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 , initializer_range=self.initializer_range , )
def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Dict , _lowerCamelCase : str ) -> Optional[int]:
__magic_name__ = ViTMSNModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = model(_lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __A ( self : Dict , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : str ) -> Any:
__magic_name__ = self.type_sequence_label_size
__magic_name__ = ViTMSNForImageClassification(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = model(_lowerCamelCase , labels=_lowerCamelCase )
print("Pixel and labels shape: {pixel_values.shape}, {labels.shape}" )
print("Labels: {labels}" )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
__magic_name__ = 1
__magic_name__ = ViTMSNForImageClassification(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__magic_name__ = model(_lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def __A ( self : Any ) -> Optional[int]:
__magic_name__ = self.prepare_config_and_inputs()
__magic_name__ , __magic_name__ , __magic_name__ = config_and_inputs
__magic_name__ = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class UpperCamelCase_ ( A , A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : int = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
UpperCAmelCase__ : List[str] = (
{'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification}
if is_torch_available()
else {}
)
UpperCAmelCase__ : Dict = False
UpperCAmelCase__ : str = False
UpperCAmelCase__ : Optional[int] = False
UpperCAmelCase__ : Any = False
def __A ( self : Dict ) -> Optional[int]:
__magic_name__ = ViTMSNModelTester(self )
__magic_name__ = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 )
def __A ( self : int ) -> Any:
self.config_tester.run_common_tests()
@unittest.skip(reason="ViTMSN does not use inputs_embeds" )
def __A ( self : List[str] ) -> Optional[int]:
pass
def __A ( self : Union[str, Any] ) -> Tuple:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__magic_name__ = model_class(_lowerCamelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
__magic_name__ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) )
def __A ( self : Union[str, Any] ) -> str:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__magic_name__ = model_class(_lowerCamelCase )
__magic_name__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__magic_name__ = [*signature.parameters.keys()]
__magic_name__ = ["pixel_values"]
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
def __A ( self : Optional[Any] ) -> Any:
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCamelCase )
def __A ( self : str ) -> Union[str, Any]:
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase )
@slow
def __A ( self : str ) -> Any:
for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__magic_name__ = ViTMSNModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self : Tuple ) -> Dict:
return ViTImageProcessor.from_pretrained("facebook/vit-msn-small" ) if is_vision_available() else None
@slow
def __A ( self : Union[str, Any] ) -> str:
torch.manual_seed(2 )
__magic_name__ = ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-small" ).to(_lowerCamelCase )
__magic_name__ = self.default_image_processor
__magic_name__ = prepare_img()
__magic_name__ = image_processor(images=_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase )
# forward pass
with torch.no_grad():
__magic_name__ = model(**_lowerCamelCase )
# verify the logits
__magic_name__ = torch.Size((1, 10_00) )
self.assertEqual(outputs.logits.shape , _lowerCamelCase )
__magic_name__ = torch.tensor([-0.0_803, -0.4_454, -0.2_375] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
| 664 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision
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 DPTImageProcessor
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict:
__magic_name__ = size if size is not None else {"height": 18, "width": 18}
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = num_channels
__magic_name__ = image_size
__magic_name__ = min_resolution
__magic_name__ = max_resolution
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = do_normalize
__magic_name__ = image_mean
__magic_name__ = image_std
def __A ( self : int ) -> List[str]:
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
@require_torch
@require_vision
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None
def __A ( self : Dict ) -> Any:
__magic_name__ = DPTImageProcessingTester(self )
@property
def __A ( self : str ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : Tuple ) -> List[str]:
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) )
self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "size" ) )
def __A ( self : List[str] ) -> List[Any]:
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"height": 18, "width": 18} )
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {"height": 42, "width": 42} )
def __A ( self : Union[str, Any] ) -> List[str]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Dict ) -> Optional[Any]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Optional[int] ) -> Dict:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
from typing import Any
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None:
__magic_name__ , __magic_name__ = row, column
__magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )]
def __str__( self : Optional[Any] ) -> str:
__magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n'
# Make string identifier
__magic_name__ = 0
for row_vector in self.array:
for obj in row_vector:
__magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) )
__magic_name__ = f'%{max_element_length}s'
# Make string and return
def single_line(_lowerCamelCase : list[float] ) -> str:
nonlocal string_format_identifier
__magic_name__ = "["
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector )
line += "]"
return line
s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array )
return s
def __repr__( self : Optional[int] ) -> str:
return str(self )
def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool:
if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2):
return False
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
return False
else:
return True
def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any:
assert self.validate_indicies(_lowerCamelCase )
return self.array[loc[0]][loc[1]]
def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None:
assert self.validate_indicies(_lowerCamelCase )
__magic_name__ = value
def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix:
assert isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == another.row and self.column == another.column
# Add
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] + another[r, c]
return result
def __neg__( self : int ) -> Matrix:
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = -self[r, c]
return result
def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix:
return self + (-another)
def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix:
if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] * another
return result
elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication
assert self.column == another.row
__magic_name__ = Matrix(self.row , another.column )
for r in range(self.row ):
for c in range(another.column ):
for i in range(self.column ):
result[r, c] += self[r, i] * another[i, c]
return result
else:
__magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})'
raise TypeError(_lowerCamelCase )
def __A ( self : Optional[int] ) -> Matrix:
__magic_name__ = Matrix(self.column , self.row )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c]
return result
def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any:
assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == self.column == u.row == v.row # u, v should be column vector
assert u.column == v.column == 1 # u, v should be column vector
# Calculate
__magic_name__ = v.transpose()
__magic_name__ = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
# Testing
if __name__ == "__main__":
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Matrix(3 , 3 , 0 )
for i in range(3 ):
__magic_name__ = 1
print(F'a^(-1) is {ainv}' )
# u, v
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5
print(F'u is {u}' )
print(F'v is {v}' )
print(F'uv^T is {u * v.transpose()}' )
# Sherman Morrison
print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' )
def __snake_case ( ):
'''simple docstring'''
import doctest
doctest.testmod()
testa()
| 664 |
'''simple docstring'''
import numpy
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None:
__magic_name__ = input_array
# Random initial weights are assigned where first argument is the
# number of nodes in previous layer and second argument is the
# number of nodes in the next layer.
# Random initial weights are assigned.
# self.input_array.shape[1] is used to represent number of nodes in input layer.
# First hidden layer consists of 4 nodes.
__magic_name__ = numpy.random.rand(
self.input_array.shape[1] , 4 )
# Random initial values for the first hidden layer.
# First hidden layer has 4 nodes.
# Second hidden layer has 3 nodes.
__magic_name__ = numpy.random.rand(
4 , 3 )
# Random initial values for the second hidden layer.
# Second hidden layer has 3 nodes.
# Output layer has 1 node.
__magic_name__ = numpy.random.rand(3 , 1 )
# Real output values provided.
__magic_name__ = output_array
# Predicted output values by the neural network.
# Predicted_output array initially consists of zeroes.
__magic_name__ = numpy.zeros(output_array.shape )
def __A ( self : int ) -> numpy.ndarray:
__magic_name__ = sigmoid(
numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) )
# layer_between_first_hidden_layer_and_second_hidden_layer is the layer
# connecting the first hidden set of nodes with the second hidden set of nodes.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
# layer_between_second_hidden_layer_and_output is the layer connecting
# second hidden layer with the output node.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return self.layer_between_second_hidden_layer_and_output
def __A ( self : Dict ) -> None:
__magic_name__ = numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , )
__magic_name__ = numpy.dot(
self.layer_between_input_and_first_hidden_layer.T , numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , )
__magic_name__ = numpy.dot(
self.input_array.T , numpy.dot(
numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , )
* sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , )
self.input_layer_and_first_hidden_layer_weights += (
updated_input_layer_and_first_hidden_layer_weights
)
self.first_hidden_layer_and_second_hidden_layer_weights += (
updated_first_hidden_layer_and_second_hidden_layer_weights
)
self.second_hidden_layer_and_output_layer_weights += (
updated_second_hidden_layer_and_output_layer_weights
)
def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None:
for iteration in range(1 , iterations + 1 ):
__magic_name__ = self.feedforward()
self.back_propagation()
if give_loss:
__magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) )
print(f'Iteration {iteration} Loss: {loss}' )
def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int:
__magic_name__ = input_arr
__magic_name__ = sigmoid(
numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return int(self.layer_between_second_hidden_layer_and_output > 0.6 )
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return 1 / (1 + numpy.exp(-value ))
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return (value) * (1 - (value))
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = numpy.array(
(
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
) , dtype=numpy.floataa , )
# True output values for the given input values.
__magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa )
# Calling neural network class.
__magic_name__ = TwoHiddenLayerNeuralNetwork(
input_array=lowerCamelCase_ , output_array=lowerCamelCase_ )
# Calling training function.
# Set give_loss to True if you want to see loss in every iteration.
neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ )
return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) )
if __name__ == "__main__":
example()
| 664 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__magic_name__ : List[Any] ={
'configuration_autoformer': [
'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'AutoformerConfig',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Tuple =[
'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'AutoformerForPrediction',
'AutoformerModel',
'AutoformerPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_autoformer import (
AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
AutoformerConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_autoformer import (
AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
AutoformerForPrediction,
AutoformerModel,
AutoformerPreTrainedModel,
)
else:
import sys
__magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 |
'''simple docstring'''
import torch
from transformers import AutoModel
class UpperCamelCase_ ( torch.nn.Module ):
"""simple docstring"""
def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]:
super(_lowerCamelCase , self ).__init__()
__magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase )
__magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 )
__magic_name__ = torch.nn.Softmax(dim=1 )
def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]:
return self.bert(**_lowerCamelCase ).last_hidden_state
def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict:
return token_embeddings.sum(2 , keepdim=_lowerCamelCase )
def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]:
return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]:
__magic_name__ = W_supports["sizes"].tolist()
__magic_name__ = W_supports["start_token_id"].item()
__magic_name__ = W_supports["end_token_id"].item()
del W_supports["sizes"]
del W_supports["start_token_id"]
del W_supports["end_token_id"]
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = None
__magic_name__ = None
__magic_name__ = W_supports["input_ids"] == start_token_id
__magic_name__ = W_supports["input_ids"] == end_token_id
for i, size in enumerate(_lowerCamelCase ):
if i == 0:
__magic_name__ = 0
else:
__magic_name__ = support_sizes[i - 1]
__magic_name__ = S[s : s + size][start_token_masks[s : s + size]]
__magic_name__ = S[s : s + size][end_token_masks[s : s + size]]
__magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 )
__magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 )
if p_starts is not None:
__magic_name__ = torch.vstack((p_starts, p_start) )
__magic_name__ = torch.vstack((p_ends, p_end) )
else:
__magic_name__ = p_start
__magic_name__ = p_end
return p_starts, p_ends
| 664 | 1 |
'''simple docstring'''
import argparse
import torch
from torch import nn
from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration
def __snake_case ( lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = [
"encoder.version",
"decoder.version",
"model.encoder.version",
"model.decoder.version",
"decoder.output_projection.weight",
"_float_tensor",
"encoder.embed_positions._float_tensor",
"decoder.embed_positions._float_tensor",
]
for k in ignore_keys:
state_dict.pop(lowerCamelCase_ , lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = list(s_dict.keys() )
for key in keys:
if "transformer_layers" in key:
__magic_name__ = s_dict.pop(lowerCamelCase_ )
elif "subsample" in key:
__magic_name__ = s_dict.pop(lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : Optional[int] ):
'''simple docstring'''
__magic_name__ , __magic_name__ = emb.weight.shape
__magic_name__ = nn.Linear(lowerCamelCase_ , lowerCamelCase_ , bias=lowerCamelCase_ )
__magic_name__ = emb.weight.data
return lin_layer
def __snake_case ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = torch.load(lowerCamelCase_ , map_location="cpu" )
__magic_name__ = mam_aaa["args"]
__magic_name__ = mam_aaa["model"]
__magic_name__ = state_dict["decoder.output_projection.weight"]
remove_ignore_keys_(lowerCamelCase_ )
rename_keys(lowerCamelCase_ )
__magic_name__ = state_dict["decoder.embed_tokens.weight"].shape[0]
__magic_name__ = args.share_decoder_input_output_embed
__magic_name__ = [int(lowerCamelCase_ ) for i in args.conv_kernel_sizes.split("," )]
__magic_name__ = SpeechaTextConfig(
vocab_size=lowerCamelCase_ , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="relu" , num_conv_layers=len(lowerCamelCase_ ) , conv_channels=args.conv_channels , conv_kernel_sizes=lowerCamelCase_ , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=lowerCamelCase_ , num_beams=5 , max_length=200 , use_cache=lowerCamelCase_ , decoder_start_token_id=2 , early_stopping=lowerCamelCase_ , )
__magic_name__ = SpeechaTextForConditionalGeneration(lowerCamelCase_ )
__magic_name__ , __magic_name__ = model.model.load_state_dict(lowerCamelCase_ , strict=lowerCamelCase_ )
if len(lowerCamelCase_ ) > 0 and not set(lowerCamelCase_ ) <= {
"encoder.embed_positions.weights",
"decoder.embed_positions.weights",
}:
raise ValueError(
"Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,"
F' but all the following weights are missing {missing}' )
if tie_embeds:
__magic_name__ = make_linear_from_emb(model.model.decoder.embed_tokens )
else:
__magic_name__ = lm_head_weights
model.save_pretrained(lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : Tuple =argparse.ArgumentParser()
# Required parameters
parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.')
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
__magic_name__ : Tuple =parser.parse_args()
convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
| 664 |
'''simple docstring'''
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401
deprecate(
'stable diffusion controlnet',
'0.22.0',
'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.',
standard_warn=False,
stacklevel=3,
)
| 664 | 1 |
'''simple docstring'''
import tempfile
import unittest
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from transformers.testing_utils import (
is_torch_available,
require_optimum,
require_torch,
slow,
)
if is_torch_available():
import torch
@require_torch
@require_optimum
@slow
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Union[str, Any] ) -> List[Any]:
__magic_name__ = "hf-internal-testing/tiny-random-t5"
__magic_name__ = AutoTokenizer.from_pretrained(_lowerCamelCase )
__magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase )
__magic_name__ = tokenizer("This is me" , return_tensors="pt" )
__magic_name__ = model.to_bettertransformer()
self.assertTrue(any("BetterTransformer" in mod.__class__.__name__ for _, mod in model.named_modules() ) )
__magic_name__ = model.generate(**_lowerCamelCase )
__magic_name__ = model.reverse_bettertransformer()
self.assertFalse(any("BetterTransformer" in mod.__class__.__name__ for _, mod in model.named_modules() ) )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(_lowerCamelCase )
__magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase )
self.assertFalse(
any("BetterTransformer" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) )
__magic_name__ = model_reloaded.generate(**_lowerCamelCase )
self.assertTrue(torch.allclose(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : str ) -> List[str]:
__magic_name__ = "hf-internal-testing/tiny-random-t5"
__magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase )
__magic_name__ = model.to_bettertransformer()
with tempfile.TemporaryDirectory() as tmpdirname:
with self.assertRaises(_lowerCamelCase ):
model.save_pretrained(_lowerCamelCase )
__magic_name__ = model.reverse_bettertransformer()
model.save_pretrained(_lowerCamelCase )
| 664 |
'''simple docstring'''
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ )
__magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ )
__magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ )
__magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"]
if config.model_type == "t5":
__magic_name__ = "SelfAttention"
if config.model_type == "longt5" and config.encoder_attention_type == "local":
__magic_name__ = "LocalSelfAttention"
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = "TransientGlobalSelfAttention"
else:
raise ValueError(
"Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"
" attribute with a value from ['local', 'transient-global]." )
# Encoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
if split_mlp_wi:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_global_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = tax_mlp_layer_norm
__magic_name__ = flax_model_encoder_layer_block
# Only for layer 0:
__magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_global_rel_embedding
# Assigning
__magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"]
__magic_name__ = tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
"scale"
]
# Encoder-Decoder-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]
__magic_name__ = tax_enc_dec_attention_module["key"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["out"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["query"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
# MLP
if split_mlp_wi:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_pre_attention_layer_norm
__magic_name__ = tax_enc_dec_attention_key
__magic_name__ = tax_enc_dec_attention_out
__magic_name__ = tax_enc_dec_attention_query
__magic_name__ = tax_enc_dec_attention_value
__magic_name__ = tax_cross_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = txa_mlp_layer_norm
__magic_name__ = flax_model_decoder_layer_block
# Decoder Normalization
__magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"]
__magic_name__ = txa_decoder_norm
# Only for layer 0:
__magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_decoder_rel_embedding
# Token Embeddings
__magic_name__ = tax_model["target"]["token_embedder"]["embedding"]
__magic_name__ = txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
__magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"]
flax_model.save_pretrained(lowerCamelCase_ )
print("T5X Model was sucessfully converted!" )
if __name__ == "__main__":
__magic_name__ : Optional[Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.'
)
parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.')
parser.add_argument(
'--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.'
)
__magic_name__ : Optional[int] =parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps
from ..pipeline_params import (
IMAGE_TO_IMAGE_IMAGE_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class UpperCamelCase_ ( A , A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Optional[Any] = CycleDiffusionPipeline
UpperCAmelCase__ : List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
'''negative_prompt''',
'''height''',
'''width''',
'''negative_prompt_embeds''',
}
UpperCAmelCase__ : List[str] = PipelineTesterMixin.required_optional_params - {'''latents'''}
UpperCAmelCase__ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''} )
UpperCAmelCase__ : Optional[int] = IMAGE_TO_IMAGE_IMAGE_PARAMS
UpperCAmelCase__ : Optional[Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS
def __A ( self : List[Any] ) -> List[Any]:
torch.manual_seed(0 )
__magic_name__ = 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 , )
__magic_name__ = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , num_train_timesteps=10_00 , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , )
torch.manual_seed(0 )
__magic_name__ = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , )
torch.manual_seed(0 )
__magic_name__ = 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=10_00 , )
__magic_name__ = CLIPTextModel(_lowerCamelCase )
__magic_name__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
__magic_name__ = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"safety_checker": None,
"feature_extractor": None,
}
return components
def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Tuple=0 ) -> List[Any]:
__magic_name__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase )
__magic_name__ = image / 2 + 0.5
if str(_lowerCamelCase ).startswith("mps" ):
__magic_name__ = torch.manual_seed(_lowerCamelCase )
else:
__magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase )
__magic_name__ = {
"prompt": "An astronaut riding an elephant",
"source_prompt": "An astronaut riding a horse",
"image": image,
"generator": generator,
"num_inference_steps": 2,
"eta": 0.1,
"strength": 0.8,
"guidance_scale": 3,
"source_guidance_scale": 1,
"output_type": "numpy",
}
return inputs
def __A ( self : List[str] ) -> Optional[Any]:
__magic_name__ = "cpu" # ensure determinism for the device-dependent torch.Generator
__magic_name__ = self.get_dummy_components()
__magic_name__ = CycleDiffusionPipeline(**_lowerCamelCase )
__magic_name__ = pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
__magic_name__ = self.get_dummy_inputs(_lowerCamelCase )
__magic_name__ = pipe(**_lowerCamelCase )
__magic_name__ = output.images
__magic_name__ = images[0, -3:, -3:, -1]
assert images.shape == (1, 32, 32, 3)
__magic_name__ = np.array([0.4_459, 0.4_943, 0.4_544, 0.6_643, 0.5_474, 0.4_327, 0.5_701, 0.5_959, 0.5_179] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
@unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" )
def __A ( self : Tuple ) -> List[Any]:
__magic_name__ = self.get_dummy_components()
for name, module in components.items():
if hasattr(_lowerCamelCase , "half" ):
__magic_name__ = module.half()
__magic_name__ = CycleDiffusionPipeline(**_lowerCamelCase )
__magic_name__ = pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
__magic_name__ = self.get_dummy_inputs(_lowerCamelCase )
__magic_name__ = pipe(**_lowerCamelCase )
__magic_name__ = output.images
__magic_name__ = images[0, -3:, -3:, -1]
assert images.shape == (1, 32, 32, 3)
__magic_name__ = np.array([0.3_506, 0.4_543, 0.446, 0.4_575, 0.5_195, 0.4_155, 0.5_273, 0.518, 0.4_116] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
@skip_mps
def __A ( self : str ) -> int:
return super().test_save_load_local()
@unittest.skip("non-deterministic pipeline" )
def __A ( self : Union[str, Any] ) -> List[str]:
return super().test_inference_batch_single_identical()
@skip_mps
def __A ( self : List[str] ) -> List[str]:
return super().test_dict_tuple_outputs_equivalent()
@skip_mps
def __A ( self : Union[str, Any] ) -> int:
return super().test_save_load_optional_components()
@skip_mps
def __A ( self : Tuple ) -> List[str]:
return super().test_attention_slicing_forward_pass()
@slow
@require_torch_gpu
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : str ) -> Optional[int]:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __A ( self : List[str] ) -> List[Any]:
__magic_name__ = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/cycle-diffusion/black_colored_car.png" )
__magic_name__ = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy" )
__magic_name__ = init_image.resize((5_12, 5_12) )
__magic_name__ = "CompVis/stable-diffusion-v1-4"
__magic_name__ = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder="scheduler" )
__magic_name__ = CycleDiffusionPipeline.from_pretrained(
_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase , torch_dtype=torch.floataa , revision="fp16" )
pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
pipe.enable_attention_slicing()
__magic_name__ = "A black colored car"
__magic_name__ = "A blue colored car"
__magic_name__ = torch.manual_seed(0 )
__magic_name__ = pipe(
prompt=_lowerCamelCase , source_prompt=_lowerCamelCase , image=_lowerCamelCase , num_inference_steps=1_00 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowerCamelCase , output_type="np" , )
__magic_name__ = output.images
# the values aren't exactly equal, but the images look the same visually
assert np.abs(image - expected_image ).max() < 5e-1
def __A ( self : List[str] ) -> Union[str, Any]:
__magic_name__ = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/cycle-diffusion/black_colored_car.png" )
__magic_name__ = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy" )
__magic_name__ = init_image.resize((5_12, 5_12) )
__magic_name__ = "CompVis/stable-diffusion-v1-4"
__magic_name__ = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder="scheduler" )
__magic_name__ = CycleDiffusionPipeline.from_pretrained(_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase )
pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
pipe.enable_attention_slicing()
__magic_name__ = "A black colored car"
__magic_name__ = "A blue colored car"
__magic_name__ = torch.manual_seed(0 )
__magic_name__ = pipe(
prompt=_lowerCamelCase , source_prompt=_lowerCamelCase , image=_lowerCamelCase , num_inference_steps=1_00 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowerCamelCase , output_type="np" , )
__magic_name__ = output.images
assert np.abs(image - expected_image ).max() < 2e-2
| 664 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class UpperCamelCase_ ( unittest.TestCase , A ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Any:
__magic_name__ = load_tool("text-to-speech" )
self.tool.setup()
def __A ( self : Union[str, Any] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
def __A ( self : List[str] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
| 664 | 1 |
'''simple docstring'''
import json
from typing import List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mvp import MvpTokenizer
__magic_name__ : int =logging.get_logger(__name__)
__magic_name__ : Tuple ={'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}
# See all MVP models at https://huggingface.co/models?filter=mvp
__magic_name__ : List[Any] ={
'vocab_file': {
'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json',
},
'added_tokens.json': {
'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json',
},
'merges_file': {
'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt',
},
'tokenizer_file': {
'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json',
},
}
__magic_name__ : Optional[int] ={
'RUCAIBox/mvp': 10_24,
}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : List[str] = VOCAB_FILES_NAMES
UpperCAmelCase__ : Any = PRETRAINED_VOCAB_FILES_MAP
UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCAmelCase__ : List[Any] = ['''input_ids''', '''attention_mask''']
UpperCAmelCase__ : int = MvpTokenizer
def __init__( self : List[Any] , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : int=None , _lowerCamelCase : List[str]=None , _lowerCamelCase : Union[str, Any]="replace" , _lowerCamelCase : Dict="<s>" , _lowerCamelCase : List[Any]="</s>" , _lowerCamelCase : Optional[Any]="</s>" , _lowerCamelCase : Union[str, Any]="<s>" , _lowerCamelCase : Dict="<unk>" , _lowerCamelCase : str="<pad>" , _lowerCamelCase : Union[str, Any]="<mask>" , _lowerCamelCase : Union[str, Any]=False , _lowerCamelCase : List[Any]=True , **_lowerCamelCase : Optional[int] , ) -> Dict:
super().__init__(
_lowerCamelCase , _lowerCamelCase , tokenizer_file=_lowerCamelCase , errors=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , add_prefix_space=_lowerCamelCase , trim_offsets=_lowerCamelCase , **_lowerCamelCase , )
__magic_name__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("add_prefix_space" , _lowerCamelCase ) != add_prefix_space:
__magic_name__ = getattr(_lowerCamelCase , pre_tok_state.pop("type" ) )
__magic_name__ = add_prefix_space
__magic_name__ = pre_tok_class(**_lowerCamelCase )
__magic_name__ = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
__magic_name__ = "post_processor"
__magic_name__ = getattr(self.backend_tokenizer , _lowerCamelCase , _lowerCamelCase )
if tokenizer_component_instance:
__magic_name__ = json.loads(tokenizer_component_instance.__getstate__() )
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
__magic_name__ = tuple(state["sep"] )
if "cls" in state:
__magic_name__ = tuple(state["cls"] )
__magic_name__ = False
if state.get("add_prefix_space" , _lowerCamelCase ) != add_prefix_space:
__magic_name__ = add_prefix_space
__magic_name__ = True
if state.get("trim_offsets" , _lowerCamelCase ) != trim_offsets:
__magic_name__ = trim_offsets
__magic_name__ = True
if changes_to_apply:
__magic_name__ = getattr(_lowerCamelCase , state.pop("type" ) )
__magic_name__ = component_class(**_lowerCamelCase )
setattr(self.backend_tokenizer , _lowerCamelCase , _lowerCamelCase )
@property
def __A ( self : List[str] ) -> str:
if self._mask_token is None:
if self.verbose:
logger.error("Using mask_token, but it is not set yet." )
return None
return str(self._mask_token )
@mask_token.setter
def __A ( self : Union[str, Any] , _lowerCamelCase : List[str] ) -> Optional[Any]:
__magic_name__ = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else value
__magic_name__ = value
def __A ( self : Any , *_lowerCamelCase : Union[str, Any] , **_lowerCamelCase : Optional[int] ) -> BatchEncoding:
__magic_name__ = kwargs.get("is_split_into_words" , _lowerCamelCase )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
"to use it with pretokenized inputs." )
return super()._batch_encode_plus(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Tuple , *_lowerCamelCase : str , **_lowerCamelCase : Union[str, Any] ) -> BatchEncoding:
__magic_name__ = kwargs.get("is_split_into_words" , _lowerCamelCase )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
"to use it with pretokenized inputs." )
return super()._encode_plus(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ) -> Tuple[str]:
__magic_name__ = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase )
return tuple(_lowerCamelCase )
def __A ( self : Optional[Any] , _lowerCamelCase : List[str] , _lowerCamelCase : Dict=None ) -> int:
__magic_name__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def __A ( self : Union[str, Any] , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None ) -> List[int]:
__magic_name__ = [self.sep_token_id]
__magic_name__ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 664 |
'''simple docstring'''
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
__magic_name__ : Dict =re.compile('[^A-Za-z_0-9]')
# parameters used in DuplicationIndex
__magic_name__ : int =10
__magic_name__ : Union[str, Any] =2_56
def __snake_case ( lowerCamelCase_ : List[str] ):
'''simple docstring'''
if len(lowerCamelCase_ ) < MIN_NUM_TOKENS:
return None
__magic_name__ = MinHash(num_perm=lowerCamelCase_ )
for token in set(lowerCamelCase_ ):
min_hash.update(token.encode() )
return min_hash
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0}
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *,
_lowerCamelCase : float = 0.85 , ) -> Optional[Any]:
__magic_name__ = duplication_jaccard_threshold
__magic_name__ = NUM_PERM
__magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm )
__magic_name__ = defaultdict(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None:
__magic_name__ = self._index.query(_lowerCamelCase )
if code_key in self._index.keys:
print(f'Duplicate key {code_key}' )
return
self._index.insert(_lowerCamelCase , _lowerCamelCase )
if len(_lowerCamelCase ) > 0:
for base_duplicate in close_duplicates:
if base_duplicate in self._duplicate_clusters:
self._duplicate_clusters[base_duplicate].add(_lowerCamelCase )
break
else:
self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase )
def __A ( self : Union[str, Any] ) -> List[List[Dict]]:
__magic_name__ = []
for base, duplicates in self._duplicate_clusters.items():
__magic_name__ = [base] + list(_lowerCamelCase )
# reformat the cluster to be a list of dict
__magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster]
duplicate_clusters.append(_lowerCamelCase )
return duplicate_clusters
def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None:
__magic_name__ = self.get_duplicate_clusters()
with open(_lowerCamelCase , "w" ) as f:
json.dump(_lowerCamelCase , _lowerCamelCase )
def __snake_case ( lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ , __magic_name__ = element
__magic_name__ = 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 __snake_case ( lowerCamelCase_ : Type[Dataset] ):
'''simple docstring'''
with mp.Pool() as pool:
for data in pool.imap_unordered(
_compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ):
if data is not None:
yield data
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ):
'''simple docstring'''
__magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ )
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ):
di.add(lowerCamelCase_ , lowerCamelCase_ )
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
return di.get_duplicate_clusters()
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = get_tokens(lowerCamelCase_ )
__magic_name__ = get_tokens(lowerCamelCase_ )
return len(tokensa & tokensa ) / len(tokensa | tokensa )
__magic_name__ : List[str] =None
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = []
for elementa in cluster:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
for elementa in extremes:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold:
elementa["copies"] += 1
break
else:
__magic_name__ = 1
extremes.append(lowerCamelCase_ )
return extremes
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
global _shared_dataset
__magic_name__ = dataset
__magic_name__ = []
__magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ )
with mp.Pool() as pool:
for extremes in tqdm(
pool.imap_unordered(
lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ):
extremes_list.append(lowerCamelCase_ )
return extremes_list
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ):
'''simple docstring'''
__magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster}
__magic_name__ = {}
__magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
for extremes in extremes_clusters:
for element in extremes:
__magic_name__ = element
__magic_name__ = duplicate_indices - set(extreme_dict.keys() )
__magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ )
# update duplicate_clusters
for cluster in duplicate_clusters:
for element in cluster:
__magic_name__ = element["base_index"] in extreme_dict
if element["is_extreme"]:
__magic_name__ = extreme_dict[element["base_index"]]["copies"]
print(F'Original dataset size: {len(lowerCamelCase_ )}' )
print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' )
print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Filtered dataset size: {len(lowerCamelCase_ )}' )
return ds_filter, duplicate_clusters
| 664 | 1 |
'''simple docstring'''
import pickle
import unittest
import torch
from accelerate import Accelerator
from accelerate.state import AcceleratorState
from accelerate.test_utils import require_cpu
@require_cpu
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Tuple ) -> Tuple:
__magic_name__ = torch.nn.Linear(10 , 10 )
__magic_name__ = torch.optim.SGD(model.parameters() , 0.1 )
__magic_name__ = Accelerator()
__magic_name__ = accelerator.prepare(_lowerCamelCase )
try:
pickle.loads(pickle.dumps(_lowerCamelCase ) )
except Exception as e:
self.fail(f'Accelerated optimizer pickling failed with {e}' )
AcceleratorState._reset_state()
| 664 |
'''simple docstring'''
import argparse
import os
import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn
from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
if version.parse(nlp.__version__) != version.parse('0.8.3'):
raise Exception('requires gluonnlp == 0.8.3')
if version.parse(mx.__version__) != version.parse('1.5.0'):
raise Exception('requires mxnet == 1.5.0')
logging.set_verbosity_info()
__magic_name__ : Optional[int] =logging.get_logger(__name__)
__magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!'
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = {
"attention_cell": "multi_head",
"num_layers": 4,
"units": 1024,
"hidden_size": 768,
"max_length": 512,
"num_heads": 8,
"scaled": True,
"dropout": 0.1,
"use_residual": True,
"embed_size": 1024,
"embed_dropout": 0.1,
"word_embed": None,
"layer_norm_eps": 1e-5,
"token_type_vocab_size": 2,
}
__magic_name__ = bort_4_8_768_1024_hparams
# Let's construct the original Bort model here
# Taken from official BERT implementation, see:
# https://github.com/alexa/bort/blob/master/bort/bort.py
__magic_name__ = BERTEncoder(
attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , )
# Vocab information needs to be fetched first
# It's the same as RoBERTa, so RobertaTokenizer can be used later
__magic_name__ = "openwebtext_ccnews_stories_books_cased"
# Specify download folder to Gluonnlp's vocab
__magic_name__ = os.path.join(get_home_dir() , "models" )
__magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ )
__magic_name__ = nlp.model.BERTModel(
lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , )
original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ )
__magic_name__ = original_bort._collect_params_with_prefix()
# Build our config 🤗
__magic_name__ = {
"architectures": ["BertForMaskedLM"],
"attention_probs_dropout_prob": predefined_args["dropout"],
"hidden_act": "gelu",
"hidden_dropout_prob": predefined_args["dropout"],
"hidden_size": predefined_args["embed_size"],
"initializer_range": 0.02,
"intermediate_size": predefined_args["hidden_size"],
"layer_norm_eps": predefined_args["layer_norm_eps"],
"max_position_embeddings": predefined_args["max_length"],
"model_type": "bort",
"num_attention_heads": predefined_args["num_heads"],
"num_hidden_layers": predefined_args["num_layers"],
"pad_token_id": 1, # 2 = BERT, 1 = RoBERTa
"type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa
"vocab_size": len(lowerCamelCase_ ),
}
__magic_name__ = BertConfig.from_dict(lowerCamelCase_ )
__magic_name__ = BertForMaskedLM(lowerCamelCase_ )
hf_bort_model.eval()
# Parameter mapping table (Gluonnlp to Transformers)
# * denotes layer index
#
# | Gluon Parameter | Transformers Parameter
# | -------------------------------------------------------------- | ----------------------
# | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias`
# | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight`
# | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight`
# | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
# | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight`
# | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight`
# | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias`
# | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight`
# Helper function to convert MXNET Arrays to PyTorch
def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter:
return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) )
# Check param shapes and map new HF param back
def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ):
__magic_name__ = hf_param.shape
__magic_name__ = to_torch(params[gluon_param] )
__magic_name__ = gluon_param.shape
assert (
shape_hf == shape_gluon
), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers'
return gluon_param
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" )
# Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
__magic_name__ = torch.zeros_like(
hf_bort_model.bert.embeddings.token_type_embeddings.weight.data )
for i in range(hf_bort_config.num_hidden_layers ):
__magic_name__ = hf_bort_model.bert.encoder.layer[i]
# self attention
__magic_name__ = layer.attention.self
__magic_name__ = check_and_map_params(
self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' )
__magic_name__ = check_and_map_params(
self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' )
__magic_name__ = check_and_map_params(
self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' )
__magic_name__ = check_and_map_params(
self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' )
__magic_name__ = check_and_map_params(
self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' )
__magic_name__ = check_and_map_params(
self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' )
# self attention output
__magic_name__ = layer.attention.output
__magic_name__ = check_and_map_params(
self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' )
__magic_name__ = check_and_map_params(
self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' )
# intermediate
__magic_name__ = layer.intermediate
__magic_name__ = check_and_map_params(
intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' )
__magic_name__ = check_and_map_params(
intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' )
# output
__magic_name__ = layer.output
__magic_name__ = check_and_map_params(
bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' )
__magic_name__ = check_and_map_params(
bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' )
# Save space and energy 🎄
hf_bort_model.half()
# Compare output of both models
__magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" )
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"]
# Get gluon output
__magic_name__ = mx.nd.array([input_ids] )
__magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] )
# Get Transformer output (save and reload model again)
hf_bort_model.save_pretrained(lowerCamelCase_ )
__magic_name__ = BertModel.from_pretrained(lowerCamelCase_ )
hf_bort_model.eval()
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" )
__magic_name__ = hf_bort_model(**lowerCamelCase_ )[0]
__magic_name__ = output_gluon[0].asnumpy()
__magic_name__ = output_hf[0].detach().numpy()
__magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item()
__magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if success:
print("✔️ Both model do output the same tensors" )
else:
print("❌ Both model do **NOT** output the same tensors" )
print("Absolute difference is:" , lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : int =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
__magic_name__ : Optional[Any] =parser.parse_args()
convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__magic_name__ : str =logging.get_logger(__name__)
__magic_name__ : Tuple ={
'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json',
'umberto-commoncrawl-cased-v1': (
'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json'
),
'umberto-wikipedia-uncased-v1': (
'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json'
),
}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Any = '''camembert'''
def __init__( self : Dict , _lowerCamelCase : Any=3_05_22 , _lowerCamelCase : Union[str, Any]=7_68 , _lowerCamelCase : Tuple=12 , _lowerCamelCase : List[Any]=12 , _lowerCamelCase : List[str]=30_72 , _lowerCamelCase : int="gelu" , _lowerCamelCase : Any=0.1 , _lowerCamelCase : Dict=0.1 , _lowerCamelCase : Tuple=5_12 , _lowerCamelCase : Union[str, Any]=2 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : int=1e-12 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : int=0 , _lowerCamelCase : Tuple=2 , _lowerCamelCase : Tuple="absolute" , _lowerCamelCase : str=True , _lowerCamelCase : Union[str, Any]=None , **_lowerCamelCase : Dict , ) -> List[Any]:
super().__init__(pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = vocab_size
__magic_name__ = hidden_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
__magic_name__ = hidden_act
__magic_name__ = intermediate_size
__magic_name__ = hidden_dropout_prob
__magic_name__ = attention_probs_dropout_prob
__magic_name__ = max_position_embeddings
__magic_name__ = type_vocab_size
__magic_name__ = initializer_range
__magic_name__ = layer_norm_eps
__magic_name__ = position_embedding_type
__magic_name__ = use_cache
__magic_name__ = classifier_dropout
class UpperCamelCase_ ( A ):
"""simple docstring"""
@property
def __A ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
__magic_name__ = {0: "batch", 1: "choice", 2: "sequence"}
else:
__magic_name__ = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] )
| 664 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ):
'''simple docstring'''
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive" )
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) )
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1" ) )
for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 | 1 |
'''simple docstring'''
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ )
__magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ )
__magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ )
__magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"]
if config.model_type == "t5":
__magic_name__ = "SelfAttention"
if config.model_type == "longt5" and config.encoder_attention_type == "local":
__magic_name__ = "LocalSelfAttention"
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = "TransientGlobalSelfAttention"
else:
raise ValueError(
"Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"
" attribute with a value from ['local', 'transient-global]." )
# Encoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
if split_mlp_wi:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_global_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = tax_mlp_layer_norm
__magic_name__ = flax_model_encoder_layer_block
# Only for layer 0:
__magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_global_rel_embedding
# Assigning
__magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"]
__magic_name__ = tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
"scale"
]
# Encoder-Decoder-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]
__magic_name__ = tax_enc_dec_attention_module["key"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["out"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["query"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
# MLP
if split_mlp_wi:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_pre_attention_layer_norm
__magic_name__ = tax_enc_dec_attention_key
__magic_name__ = tax_enc_dec_attention_out
__magic_name__ = tax_enc_dec_attention_query
__magic_name__ = tax_enc_dec_attention_value
__magic_name__ = tax_cross_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = txa_mlp_layer_norm
__magic_name__ = flax_model_decoder_layer_block
# Decoder Normalization
__magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"]
__magic_name__ = txa_decoder_norm
# Only for layer 0:
__magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_decoder_rel_embedding
# Token Embeddings
__magic_name__ = tax_model["target"]["token_embedder"]["embedding"]
__magic_name__ = txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
__magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"]
flax_model.save_pretrained(lowerCamelCase_ )
print("T5X Model was sucessfully converted!" )
if __name__ == "__main__":
__magic_name__ : Optional[Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.'
)
parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.')
parser.add_argument(
'--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.'
)
__magic_name__ : Optional[int] =parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 664 |
'''simple docstring'''
import functools
import logging
import os
import sys
import threading
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
__magic_name__ : Tuple =threading.Lock()
__magic_name__ : Optional[logging.Handler] =None
__magic_name__ : List[str] ={
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
}
__magic_name__ : str =logging.WARNING
__magic_name__ : Any =True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '
F'has to be one of: { ", ".join(log_levels.keys() ) }' )
return _default_log_level
def __snake_case ( ):
'''simple docstring'''
return __name__.split("." )[0]
def __snake_case ( ):
'''simple docstring'''
return logging.getLogger(_get_library_name() )
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
__magic_name__ = logging.StreamHandler() # Set sys.stderr as stream.
__magic_name__ = sys.stderr.flush
# Apply our default configuration to the library root logger.
__magic_name__ = _get_library_root_logger()
library_root_logger.addHandler(_default_handler )
library_root_logger.setLevel(_get_default_logging_level() )
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
global _default_handler
with _lock:
if not _default_handler:
return
__magic_name__ = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler )
library_root_logger.setLevel(logging.NOTSET )
__magic_name__ = None
def __snake_case ( ):
'''simple docstring'''
return log_levels
def __snake_case ( lowerCamelCase_ : Optional[str] = None ):
'''simple docstring'''
if name is None:
__magic_name__ = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def __snake_case ( lowerCamelCase_ : int ):
'''simple docstring'''
_configure_library_root_logger()
_get_library_root_logger().setLevel(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
return set_verbosity(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(lowerCamelCase_ )
def __snake_case ( lowerCamelCase_ : logging.Handler ):
'''simple docstring'''
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = False
def __snake_case ( ):
'''simple docstring'''
_configure_library_root_logger()
__magic_name__ = True
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
__magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" )
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(lowerCamelCase_ )
def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ):
'''simple docstring'''
__magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ )
if no_advisory_warnings:
return
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : int =warning_advice
@functools.lru_cache(lowerCamelCase_ )
def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ):
'''simple docstring'''
self.warning(*lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ : Optional[int] =warning_once
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument
__magic_name__ = args[0] if args else None
def __iter__( self : int ) -> Tuple:
return iter(self._iterator )
def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]:
def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument
return
return empty_fn
def __enter__( self : Optional[Any] ) -> Any:
return self
def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict:
return
class UpperCamelCase_ :
"""simple docstring"""
def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]:
if _tqdm_active:
return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase )
else:
return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]:
__magic_name__ = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase )
def __A ( self : str ) -> Any:
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
__magic_name__ : List[Any] =_tqdm_cls()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
return bool(_tqdm_active )
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = True
hf_hub_utils.enable_progress_bars()
def __snake_case ( ):
'''simple docstring'''
global _tqdm_active
__magic_name__ = False
hf_hub_utils.disable_progress_bars()
| 664 | 1 |
'''simple docstring'''
import unittest
from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
@require_sentencepiece
@slow # see https://github.com/huggingface/transformers/issues/11457
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Any = BarthezTokenizer
UpperCAmelCase__ : Dict = BarthezTokenizerFast
UpperCAmelCase__ : List[Any] = True
UpperCAmelCase__ : List[str] = True
def __A ( self : Optional[int] ) -> Optional[int]:
super().setUp()
__magic_name__ = BarthezTokenizerFast.from_pretrained("moussaKam/mbarthez" )
tokenizer.save_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname , legacy_format=_lowerCamelCase )
__magic_name__ = tokenizer
def __A ( self : Dict ) -> List[str]:
__magic_name__ = "<pad>"
__magic_name__ = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase )
def __A ( self : List[Any] ) -> int:
__magic_name__ = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<s>" )
self.assertEqual(vocab_keys[1] , "<pad>" )
self.assertEqual(vocab_keys[-1] , "<mask>" )
self.assertEqual(len(_lowerCamelCase ) , 10_11_22 )
def __A ( self : Optional[Any] ) -> str:
self.assertEqual(self.get_tokenizer().vocab_size , 10_11_22 )
@require_torch
def __A ( self : Dict ) -> Any:
__magic_name__ = ["A long paragraph for summarization.", "Another paragraph for summarization."]
__magic_name__ = [0, 57, 30_18, 7_03_07, 91, 2]
__magic_name__ = self.tokenizer(
_lowerCamelCase , max_length=len(_lowerCamelCase ) , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors="pt" )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual((2, 6) , batch.input_ids.shape )
self.assertEqual((2, 6) , batch.attention_mask.shape )
__magic_name__ = batch.input_ids.tolist()[0]
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
def __A ( self : List[str] ) -> Optional[int]:
if not self.test_rust_tokenizer:
return
__magic_name__ = self.get_tokenizer()
__magic_name__ = self.get_rust_tokenizer()
__magic_name__ = "I was born in 92000, and this is falsé."
__magic_name__ = tokenizer.tokenize(_lowerCamelCase )
__magic_name__ = rust_tokenizer.tokenize(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
__magic_name__ = rust_tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = self.get_rust_tokenizer()
__magic_name__ = tokenizer.encode(_lowerCamelCase )
__magic_name__ = rust_tokenizer.encode(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
@slow
def __A ( self : List[str] ) -> List[str]:
# fmt: off
__magic_name__ = {"input_ids": [[0, 4_90, 1_43_28, 45_07, 3_54, 47, 4_36_69, 95, 25, 7_81_17, 2_02_15, 1_97_79, 1_90, 22, 4_00, 4, 3_53_43, 8_03_10, 6_03, 86, 2_49_37, 1_05, 3_34_38, 9_47_62, 1_96, 3_96_42, 7, 15, 1_59_33, 1_73, 2, 1, 1, 1, 1, 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, 1_05_34, 87, 25, 66, 33_58, 1_96, 5_52_89, 8, 8_29_61, 81, 22_04, 7_52_03, 7, 15, 7_63, 1_29_56, 2_16, 1_78, 1_43_28, 95_95, 13_77, 6_96_93, 7, 4_48, 7_10_21, 1_96, 1_81_06, 14_37, 1_39_74, 1_08, 90_83, 4, 4_93_15, 7, 39, 86, 13_26, 27_93, 4_63_33, 4, 4_48, 1_96, 7_45_88, 7, 4_93_15, 7, 39, 21, 8_22, 3_84_70, 74, 21, 6_67_23, 6_24_80, 8, 2_20_50, 5, 2]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501
# fmt: on
# moussaKam/mbarthez is a french model. So we also use french texts.
__magic_name__ = [
"Le transformeur est un modèle d'apprentissage profond introduit en 2017, "
"utilisé principalement dans le domaine du traitement automatique des langues (TAL).",
"À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus "
"pour gérer des données séquentielles, telles que le langage naturel, pour des tâches "
"telles que la traduction et la synthèse de texte.",
]
self.tokenizer_integration_test_util(
expected_encoding=_lowerCamelCase , model_name="moussaKam/mbarthez" , revision="c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6" , sequences=_lowerCamelCase , )
| 664 |
'''simple docstring'''
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : str =[
'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST',
'FocalNetForImageClassification',
'FocalNetForMaskedImageModeling',
'FocalNetBackbone',
'FocalNetModel',
'FocalNetPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_focalnet import (
FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST,
FocalNetBackbone,
FocalNetForImageClassification,
FocalNetForMaskedImageModeling,
FocalNetModel,
FocalNetPreTrainedModel,
)
else:
import sys
__magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ):
'''simple docstring'''
return "\n".join(
F'{number} * {i} = {number * i}' for i in range(1 , number_of_terms + 1 ) )
if __name__ == "__main__":
print(multiplication_table(number=5, number_of_terms=10))
| 664 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__magic_name__ : Optional[Any] ={
'configuration_longformer': [
'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'LongformerConfig',
'LongformerOnnxConfig',
],
'tokenization_longformer': ['LongformerTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : int =['LongformerTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Dict =[
'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'LongformerForMaskedLM',
'LongformerForMultipleChoice',
'LongformerForQuestionAnswering',
'LongformerForSequenceClassification',
'LongformerForTokenClassification',
'LongformerModel',
'LongformerPreTrainedModel',
'LongformerSelfAttention',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Tuple =[
'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFLongformerForMaskedLM',
'TFLongformerForMultipleChoice',
'TFLongformerForQuestionAnswering',
'TFLongformerForSequenceClassification',
'TFLongformerForTokenClassification',
'TFLongformerModel',
'TFLongformerPreTrainedModel',
'TFLongformerSelfAttention',
]
if TYPE_CHECKING:
from .configuration_longformer import (
LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
LongformerConfig,
LongformerOnnxConfig,
)
from .tokenization_longformer import LongformerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_longformer_fast import LongformerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_longformer import (
LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
LongformerForMaskedLM,
LongformerForMultipleChoice,
LongformerForQuestionAnswering,
LongformerForSequenceClassification,
LongformerForTokenClassification,
LongformerModel,
LongformerPreTrainedModel,
LongformerSelfAttention,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_longformer import (
TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLongformerForMaskedLM,
TFLongformerForMultipleChoice,
TFLongformerForQuestionAnswering,
TFLongformerForSequenceClassification,
TFLongformerForTokenClassification,
TFLongformerModel,
TFLongformerPreTrainedModel,
TFLongformerSelfAttention,
)
else:
import sys
__magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 | 1 |
'''simple docstring'''
import unittest
import numpy as np
from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax.numpy as jnp
from transformers.models.albert.modeling_flax_albert import (
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForPreTraining,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertModel,
)
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : Optional[Any] , _lowerCamelCase : int , _lowerCamelCase : Tuple=13 , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Dict=True , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=True , _lowerCamelCase : Dict=True , _lowerCamelCase : Any=99 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : Optional[Any]=5 , _lowerCamelCase : Optional[Any]=4 , _lowerCamelCase : Union[str, Any]=37 , _lowerCamelCase : List[str]="gelu" , _lowerCamelCase : Union[str, Any]=0.1 , _lowerCamelCase : List[Any]=0.1 , _lowerCamelCase : int=5_12 , _lowerCamelCase : List[str]=16 , _lowerCamelCase : int=2 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Optional[Any]=4 , ) -> Any:
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = seq_length
__magic_name__ = is_training
__magic_name__ = use_attention_mask
__magic_name__ = use_token_type_ids
__magic_name__ = use_labels
__magic_name__ = vocab_size
__magic_name__ = hidden_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
__magic_name__ = intermediate_size
__magic_name__ = hidden_act
__magic_name__ = hidden_dropout_prob
__magic_name__ = attention_probs_dropout_prob
__magic_name__ = max_position_embeddings
__magic_name__ = type_vocab_size
__magic_name__ = type_sequence_label_size
__magic_name__ = initializer_range
__magic_name__ = num_choices
def __A ( self : Dict ) -> Any:
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = None
if self.use_attention_mask:
__magic_name__ = random_attention_mask([self.batch_size, self.seq_length] )
__magic_name__ = None
if self.use_token_type_ids:
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__magic_name__ = AlbertConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def __A ( self : Dict ) -> Union[str, Any]:
__magic_name__ = self.prepare_config_and_inputs()
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = config_and_inputs
__magic_name__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
return config, inputs_dict
@require_flax
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = (
(
FlaxAlbertModel,
FlaxAlbertForPreTraining,
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def __A ( self : int ) -> int:
__magic_name__ = FlaxAlbertModelTester(self )
@slow
def __A ( self : Tuple ) -> Optional[int]:
for model_class_name in self.all_model_classes:
__magic_name__ = model_class_name.from_pretrained("albert-base-v2" )
__magic_name__ = model(np.ones((1, 1) ) )
self.assertIsNotNone(_lowerCamelCase )
@require_flax
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@slow
def __A ( self : Union[str, Any] ) -> Union[str, Any]:
__magic_name__ = FlaxAlbertModel.from_pretrained("albert-base-v2" )
__magic_name__ = np.array([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] )
__magic_name__ = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
__magic_name__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0]
__magic_name__ = (1, 11, 7_68)
self.assertEqual(output.shape , _lowerCamelCase )
__magic_name__ = np.array(
[[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] )
self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , _lowerCamelCase , atol=1e-4 ) )
| 664 |
'''simple docstring'''
import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'):
__magic_name__ : str ={
'linear': PIL.Image.Resampling.BILINEAR,
'bilinear': PIL.Image.Resampling.BILINEAR,
'bicubic': PIL.Image.Resampling.BICUBIC,
'lanczos': PIL.Image.Resampling.LANCZOS,
'nearest': PIL.Image.Resampling.NEAREST,
}
else:
__magic_name__ : Tuple ={
'linear': PIL.Image.LINEAR,
'bilinear': PIL.Image.BILINEAR,
'bicubic': PIL.Image.BICUBIC,
'lanczos': PIL.Image.LANCZOS,
'nearest': PIL.Image.NEAREST,
}
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = (images / 2 + 0.5).clamp(0 , 1 )
__magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
__magic_name__ = numpy_to_pil(lowerCamelCase_ )
return images
def __snake_case ( lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
if images.ndim == 3:
__magic_name__ = images[None, ...]
__magic_name__ = (images * 255).round().astype("uint8" )
if images.shape[-1] == 1:
# special case for grayscale (single channel) images
__magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images]
else:
__magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images]
return pil_images
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int ):
'''simple docstring'''
if num <= 0:
raise ValueError("Input must be a positive integer" )
__magic_name__ = [True] * (num + 1)
__magic_name__ = 2
while p * p <= num:
if primes[p]:
for i in range(p * p , num + 1 , lowerCamelCase_ ):
__magic_name__ = False
p += 1
return [prime for prime in range(2 , num + 1 ) if primes[prime]]
if __name__ == "__main__":
import doctest
doctest.testmod()
__magic_name__ : Dict =int(input('Enter a positive integer: ').strip())
print(prime_sieve_eratosthenes(user_num))
| 664 |
'''simple docstring'''
from typing import Dict
import numpy as np
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException
if is_tf_available():
import tensorflow as tf
from ..tf_utils import stable_softmax
if is_torch_available():
import torch
__magic_name__ : Optional[Any] =logging.get_logger(__name__)
@add_end_docstrings(
A , r'''
top_k (`int`, defaults to 5):
The number of predictions to return.
targets (`str` or `List[str]`, *optional*):
When passed, the model will limit the scores to the passed targets instead of looking up in the whole
vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
token will be used (with a warning, and that might be slower).
''' , )
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray:
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
elif self.framework == "pt":
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase )
else:
raise ValueError("Unsupported framework" )
return masked_index
def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray:
__magic_name__ = self.get_masked_index(_lowerCamelCase )
__magic_name__ = np.prod(masked_index.shape )
if numel < 1:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , )
def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
for model_input in model_inputs:
self._ensure_exactly_one_mask_token(model_input["input_ids"][0] )
else:
for input_ids in model_inputs["input_ids"]:
self._ensure_exactly_one_mask_token(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]:
if return_tensors is None:
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase )
self.ensure_exactly_one_mask_token(_lowerCamelCase )
return model_inputs
def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]:
__magic_name__ = self.model(**_lowerCamelCase )
__magic_name__ = model_inputs["input_ids"]
return model_outputs
def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict:
# Cap top_k if there are targets
if target_ids is not None and target_ids.shape[0] < top_k:
__magic_name__ = target_ids.shape[0]
__magic_name__ = model_outputs["input_ids"][0]
__magic_name__ = model_outputs["logits"]
if self.framework == "tf":
__magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]
__magic_name__ = outputs.numpy()
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 )
if target_ids is not None:
__magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) )
__magic_name__ = tf.expand_dims(_lowerCamelCase , 0 )
__magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase )
__magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy()
else:
__magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 )
# Fill mask pipeline supports only one ${mask_token} per sample
__magic_name__ = outputs[0, masked_index, :]
__magic_name__ = logits.softmax(dim=-1 )
if target_ids is not None:
__magic_name__ = probs[..., target_ids]
__magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase )
__magic_name__ = []
__magic_name__ = values.shape[0] == 1
for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ):
__magic_name__ = []
for v, p in zip(_values , _predictions ):
# Copy is important since we're going to modify this array in place
__magic_name__ = input_ids.numpy().copy()
if target_ids is not None:
__magic_name__ = target_ids[p].tolist()
__magic_name__ = p
# Filter padding out:
__magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )]
# Originally we skip special tokens to give readable output.
# For multi masks though, the other [MASK] would be removed otherwise
# making the output look odd, so we add them back
__magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase )
__magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence}
row.append(_lowerCamelCase )
result.append(_lowerCamelCase )
if single_mask:
return result[0]
return result
def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = [targets]
try:
__magic_name__ = self.tokenizer.get_vocab()
except Exception:
__magic_name__ = {}
__magic_name__ = []
for target in targets:
__magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase )
if id_ is None:
__magic_name__ = self.tokenizer(
_lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"]
if len(_lowerCamelCase ) == 0:
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
"We cannot replace it with anything meaningful, ignoring it" )
continue
__magic_name__ = input_ids[0]
# XXX: If users encounter this pass
# it becomes pretty slow, so let's make sure
# The warning enables them to fix the input to
# get faster performance.
logger.warning(
f'The specified target token `{target}` does not exist in the model vocabulary. '
f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' )
target_ids.append(id_ )
__magic_name__ = list(set(_lowerCamelCase ) )
if len(_lowerCamelCase ) == 0:
raise ValueError("At least one target must be provided when passed." )
__magic_name__ = np.array(_lowerCamelCase )
return target_ids
def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple:
__magic_name__ = {}
if targets is not None:
__magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase )
__magic_name__ = target_ids
if top_k is not None:
__magic_name__ = top_k
if self.tokenizer.mask_token_id is None:
raise PipelineException(
"fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." )
return {}, {}, postprocess_params
def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]:
__magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase )
if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1:
return outputs[0]
return outputs
| 664 | 1 |
'''simple docstring'''
import numpy
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None:
__magic_name__ = input_array
# Random initial weights are assigned where first argument is the
# number of nodes in previous layer and second argument is the
# number of nodes in the next layer.
# Random initial weights are assigned.
# self.input_array.shape[1] is used to represent number of nodes in input layer.
# First hidden layer consists of 4 nodes.
__magic_name__ = numpy.random.rand(
self.input_array.shape[1] , 4 )
# Random initial values for the first hidden layer.
# First hidden layer has 4 nodes.
# Second hidden layer has 3 nodes.
__magic_name__ = numpy.random.rand(
4 , 3 )
# Random initial values for the second hidden layer.
# Second hidden layer has 3 nodes.
# Output layer has 1 node.
__magic_name__ = numpy.random.rand(3 , 1 )
# Real output values provided.
__magic_name__ = output_array
# Predicted output values by the neural network.
# Predicted_output array initially consists of zeroes.
__magic_name__ = numpy.zeros(output_array.shape )
def __A ( self : int ) -> numpy.ndarray:
__magic_name__ = sigmoid(
numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) )
# layer_between_first_hidden_layer_and_second_hidden_layer is the layer
# connecting the first hidden set of nodes with the second hidden set of nodes.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
# layer_between_second_hidden_layer_and_output is the layer connecting
# second hidden layer with the output node.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return self.layer_between_second_hidden_layer_and_output
def __A ( self : Dict ) -> None:
__magic_name__ = numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , )
__magic_name__ = numpy.dot(
self.layer_between_input_and_first_hidden_layer.T , numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , )
__magic_name__ = numpy.dot(
self.input_array.T , numpy.dot(
numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , )
* sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , )
self.input_layer_and_first_hidden_layer_weights += (
updated_input_layer_and_first_hidden_layer_weights
)
self.first_hidden_layer_and_second_hidden_layer_weights += (
updated_first_hidden_layer_and_second_hidden_layer_weights
)
self.second_hidden_layer_and_output_layer_weights += (
updated_second_hidden_layer_and_output_layer_weights
)
def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None:
for iteration in range(1 , iterations + 1 ):
__magic_name__ = self.feedforward()
self.back_propagation()
if give_loss:
__magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) )
print(f'Iteration {iteration} Loss: {loss}' )
def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int:
__magic_name__ = input_arr
__magic_name__ = sigmoid(
numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return int(self.layer_between_second_hidden_layer_and_output > 0.6 )
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return 1 / (1 + numpy.exp(-value ))
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return (value) * (1 - (value))
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = numpy.array(
(
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
) , dtype=numpy.floataa , )
# True output values for the given input values.
__magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa )
# Calling neural network class.
__magic_name__ = TwoHiddenLayerNeuralNetwork(
input_array=lowerCamelCase_ , output_array=lowerCamelCase_ )
# Calling training function.
# Set give_loss to True if you want to see loss in every iteration.
neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ )
return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) )
if __name__ == "__main__":
example()
| 664 |
'''simple docstring'''
from __future__ import annotations
def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ):
'''simple docstring'''
if len(lowerCamelCase_ ) < k or k < 0:
raise ValueError("Invalid Input" )
__magic_name__ = __magic_name__ = sum(array[:k] )
for i in range(len(lowerCamelCase_ ) - k ):
__magic_name__ = current_sum - array[i] + array[i + k]
__magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ )
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
__magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)]
__magic_name__ : List[str] =randint(0, 1_10)
print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
| 664 | 1 |
'''simple docstring'''
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline
else:
from .camera import create_pan_cameras
from .pipeline_shap_e import ShapEPipeline
from .pipeline_shap_e_img2img import ShapEImgaImgPipeline
from .renderer import (
BoundingBoxVolume,
ImportanceRaySampler,
MLPNeRFModelOutput,
MLPNeRSTFModel,
ShapEParamsProjModel,
ShapERenderer,
StratifiedRaySampler,
VoidNeRFModel,
)
| 664 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__magic_name__ : int =logging.get_logger(__name__)
__magic_name__ : List[Any] ={}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : int = '''llama'''
UpperCAmelCase__ : Any = ['''past_key_values''']
def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any:
__magic_name__ = vocab_size
__magic_name__ = max_position_embeddings
__magic_name__ = hidden_size
__magic_name__ = intermediate_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
__magic_name__ = num_attention_heads
__magic_name__ = num_key_value_heads
__magic_name__ = hidden_act
__magic_name__ = initializer_range
__magic_name__ = rms_norm_eps
__magic_name__ = pretraining_tp
__magic_name__ = use_cache
__magic_name__ = rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , )
def __A ( self : Union[str, Any] ) -> List[Any]:
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2:
raise ValueError(
"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
f'got {self.rope_scaling}' )
__magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase )
__magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' )
if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0:
raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
from bisect import bisect_left
from functools import total_ordering
from heapq import merge
@total_ordering
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __lt__( self : Any , _lowerCamelCase : Union[str, Any] ) -> List[Any]:
return self[-1] < other[-1]
def __eq__( self : int , _lowerCamelCase : Tuple ) -> Optional[Any]:
return self[-1] == other[-1]
def __snake_case ( lowerCamelCase_ : list ):
'''simple docstring'''
__magic_name__ = []
# sort into stacks
for element in collection:
__magic_name__ = Stack([element] )
__magic_name__ = bisect_left(lowerCamelCase_ , lowerCamelCase_ )
if i != len(lowerCamelCase_ ):
stacks[i].append(lowerCamelCase_ )
else:
stacks.append(lowerCamelCase_ )
# use a heap-based merge to merge stack efficiently
__magic_name__ = merge(*(reversed(lowerCamelCase_ ) for stack in stacks) )
return collection
if __name__ == "__main__":
__magic_name__ : Optional[int] =input('Enter numbers separated by a comma:\n').strip()
__magic_name__ : Union[str, Any] =[int(item) for item in user_input.split(',')]
print(patience_sort(unsorted))
| 664 |
'''simple docstring'''
__magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1
def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or volume < 0:
raise ValueError("Invalid inputs. Enter positive value." )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume
def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or pressure < 0:
raise ValueError("Invalid inputs. Enter positive value." )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure
if __name__ == "__main__":
from doctest import testmod
testmod()
| 664 | 1 |
'''simple docstring'''
from __future__ import annotations
import json
import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent
__magic_name__ : List[Any] ={'UserAgent': UserAgent().random}
def __snake_case ( lowerCamelCase_ : Tuple ):
'''simple docstring'''
__magic_name__ = script.contents[0]
__magic_name__ = json.loads(data[data.find("{\"config\"" ) : -1] )
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Any , _lowerCamelCase : str ) -> Optional[int]:
__magic_name__ = f'https://www.instagram.com/{username}/'
__magic_name__ = self.get_json()
def __A ( self : Any ) -> dict:
__magic_name__ = requests.get(self.url , headers=_lowerCamelCase ).text
__magic_name__ = BeautifulSoup(_lowerCamelCase , "html.parser" ).find_all("script" )
try:
return extract_user_profile(scripts[4] )
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3] )
def __repr__( self : Dict ) -> str:
return f'{self.__class__.__name__}(\'{self.username}\')'
def __str__( self : Dict ) -> str:
return f'{self.fullname} ({self.username}) is {self.biography}'
@property
def __A ( self : int ) -> str:
return self.user_data["username"]
@property
def __A ( self : Any ) -> str:
return self.user_data["full_name"]
@property
def __A ( self : Any ) -> str:
return self.user_data["biography"]
@property
def __A ( self : Dict ) -> str:
return self.user_data["business_email"]
@property
def __A ( self : List[str] ) -> str:
return self.user_data["external_url"]
@property
def __A ( self : List[Any] ) -> int:
return self.user_data["edge_followed_by"]["count"]
@property
def __A ( self : Optional[Any] ) -> int:
return self.user_data["edge_follow"]["count"]
@property
def __A ( self : List[Any] ) -> int:
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def __A ( self : Optional[int] ) -> str:
return self.user_data["profile_pic_url_hd"]
@property
def __A ( self : Union[str, Any] ) -> bool:
return self.user_data["is_verified"]
@property
def __A ( self : Optional[Any] ) -> bool:
return self.user_data["is_private"]
def __snake_case ( lowerCamelCase_ : str = "github" ):
'''simple docstring'''
import os
if os.environ.get("CI" ):
return # test failing on GitHub Actions
__magic_name__ = InstagramUser(lowerCamelCase_ )
assert instagram_user.user_data
assert isinstance(instagram_user.user_data , lowerCamelCase_ )
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 12_0000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "support@github.com"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram." )
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
__magic_name__ : int =InstagramUser('github')
print(instagram_user)
print(F'''{instagram_user.number_of_posts = }''')
print(F'''{instagram_user.number_of_followers = }''')
print(F'''{instagram_user.number_of_followings = }''')
print(F'''{instagram_user.email = }''')
print(F'''{instagram_user.website = }''')
print(F'''{instagram_user.profile_picture_url = }''')
print(F'''{instagram_user.is_verified = }''')
print(F'''{instagram_user.is_private = }''')
| 664 |
'''simple docstring'''
import logging
import os
from typing import List, TextIO, Union
from conllu import parse_incr
from utils_ner import InputExample, Split, TokenClassificationTask
__magic_name__ : List[Any] =logging.getLogger(__name__)
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]:
# in NER datasets, the last column is usually reserved for NER label
__magic_name__ = label_idx
def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = mode.value
__magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' )
__magic_name__ = 1
__magic_name__ = []
with open(_lowerCamelCase , encoding="utf-8" ) as f:
__magic_name__ = []
__magic_name__ = []
for line in f:
if line.startswith("-DOCSTART-" ) or line == "" or line == "\n":
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
guid_index += 1
__magic_name__ = []
__magic_name__ = []
else:
__magic_name__ = line.split(" " )
words.append(splits[0] )
if len(_lowerCamelCase ) > 1:
labels.append(splits[self.label_idx].replace("\n" , "" ) )
else:
# Examples could have no label for mode = "test"
labels.append("O" )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
return examples
def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]:
__magic_name__ = 0
for line in test_input_reader:
if line.startswith("-DOCSTART-" ) or line == "" or line == "\n":
writer.write(_lowerCamelCase )
if not preds_list[example_id]:
example_id += 1
elif preds_list[example_id]:
__magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n"
writer.write(_lowerCamelCase )
else:
logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] )
def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
__magic_name__ = f.read().splitlines()
if "O" not in labels:
__magic_name__ = ["O"] + labels
return labels
else:
return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __init__( self : int ) -> str:
# in CONLL2003 dataset chunk column is second-to-last
super().__init__(label_idx=-2 )
def __A ( self : int , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
__magic_name__ = f.read().splitlines()
if "O" not in labels:
__magic_name__ = ["O"] + labels
return labels
else:
return [
"O",
"B-ADVP",
"B-INTJ",
"B-LST",
"B-PRT",
"B-NP",
"B-SBAR",
"B-VP",
"B-ADJP",
"B-CONJP",
"B-PP",
"I-ADVP",
"I-INTJ",
"I-LST",
"I-PRT",
"I-NP",
"I-SBAR",
"I-VP",
"I-ADJP",
"I-CONJP",
"I-PP",
]
class UpperCamelCase_ ( A ):
"""simple docstring"""
def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = mode.value
__magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' )
__magic_name__ = 1
__magic_name__ = []
with open(_lowerCamelCase , encoding="utf-8" ) as f:
for sentence in parse_incr(_lowerCamelCase ):
__magic_name__ = []
__magic_name__ = []
for token in sentence:
words.append(token["form"] )
labels.append(token["upos"] )
assert len(_lowerCamelCase ) == len(_lowerCamelCase )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) )
guid_index += 1
return examples
def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any:
__magic_name__ = 0
for sentence in parse_incr(_lowerCamelCase ):
__magic_name__ = preds_list[example_id]
__magic_name__ = ""
for token in sentence:
out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) '
out += "\n"
writer.write(_lowerCamelCase )
example_id += 1
def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]:
if path:
with open(_lowerCamelCase , "r" ) as f:
return f.read().splitlines()
else:
return [
"ADJ",
"ADP",
"ADV",
"AUX",
"CCONJ",
"DET",
"INTJ",
"NOUN",
"NUM",
"PART",
"PRON",
"PROPN",
"PUNCT",
"SCONJ",
"SYM",
"VERB",
"X",
]
| 664 | 1 |
'''simple docstring'''
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pathlib import Path
import torch
from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter
__magic_name__ : List[Any] ='Create a default config file for Accelerate with only a few flags set.'
def __snake_case ( lowerCamelCase_ : Any="no" , lowerCamelCase_ : str = default_json_config_file , lowerCamelCase_ : bool = False ):
'''simple docstring'''
__magic_name__ = Path(lowerCamelCase_ )
path.parent.mkdir(parents=lowerCamelCase_ , exist_ok=lowerCamelCase_ )
if path.exists():
print(
F'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.' )
return False
__magic_name__ = mixed_precision.lower()
if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
raise ValueError(
F'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}' )
__magic_name__ = {
"compute_environment": "LOCAL_MACHINE",
"mixed_precision": mixed_precision,
}
if torch.cuda.is_available():
__magic_name__ = torch.cuda.device_count()
__magic_name__ = num_gpus
__magic_name__ = False
if num_gpus > 1:
__magic_name__ = "MULTI_GPU"
else:
__magic_name__ = "NO"
elif is_xpu_available() and use_xpu:
__magic_name__ = torch.xpu.device_count()
__magic_name__ = num_xpus
__magic_name__ = False
if num_xpus > 1:
__magic_name__ = "MULTI_XPU"
else:
__magic_name__ = "NO"
elif is_npu_available():
__magic_name__ = torch.npu.device_count()
__magic_name__ = num_npus
__magic_name__ = False
if num_npus > 1:
__magic_name__ = "MULTI_NPU"
else:
__magic_name__ = "NO"
else:
__magic_name__ = 0
__magic_name__ = True
__magic_name__ = 1
__magic_name__ = "NO"
__magic_name__ = ClusterConfig(**lowerCamelCase_ )
config.to_json_file(lowerCamelCase_ )
return path
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int ):
'''simple docstring'''
__magic_name__ = parser.add_parser("default" , parents=lowerCamelCase_ , help=lowerCamelCase_ , formatter_class=lowerCamelCase_ )
parser.add_argument(
"--config_file" , default=lowerCamelCase_ , help=(
"The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
"location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
"such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
"with 'huggingface'."
) , dest="save_location" , )
parser.add_argument(
"--mixed_precision" , choices=["no", "fp16", "bf16"] , type=lowerCamelCase_ , help="Whether or not to use mixed precision training. "
"Choose between FP16 and BF16 (bfloat16) training. "
"BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later." , default="no" , )
parser.set_defaults(func=lowerCamelCase_ )
return parser
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = write_basic_config(args.mixed_precision , args.save_location )
if config_file:
print(F'accelerate configuration saved at {config_file}' )
| 664 |
'''simple docstring'''
from __future__ import annotations
from typing import Any
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None:
__magic_name__ , __magic_name__ = row, column
__magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )]
def __str__( self : Optional[Any] ) -> str:
__magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n'
# Make string identifier
__magic_name__ = 0
for row_vector in self.array:
for obj in row_vector:
__magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) )
__magic_name__ = f'%{max_element_length}s'
# Make string and return
def single_line(_lowerCamelCase : list[float] ) -> str:
nonlocal string_format_identifier
__magic_name__ = "["
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector )
line += "]"
return line
s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array )
return s
def __repr__( self : Optional[int] ) -> str:
return str(self )
def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool:
if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2):
return False
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
return False
else:
return True
def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any:
assert self.validate_indicies(_lowerCamelCase )
return self.array[loc[0]][loc[1]]
def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None:
assert self.validate_indicies(_lowerCamelCase )
__magic_name__ = value
def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix:
assert isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == another.row and self.column == another.column
# Add
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] + another[r, c]
return result
def __neg__( self : int ) -> Matrix:
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = -self[r, c]
return result
def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix:
return self + (-another)
def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix:
if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication
__magic_name__ = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c] * another
return result
elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication
assert self.column == another.row
__magic_name__ = Matrix(self.row , another.column )
for r in range(self.row ):
for c in range(another.column ):
for i in range(self.column ):
result[r, c] += self[r, i] * another[i, c]
return result
else:
__magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})'
raise TypeError(_lowerCamelCase )
def __A ( self : Optional[int] ) -> Matrix:
__magic_name__ = Matrix(self.column , self.row )
for r in range(self.row ):
for c in range(self.column ):
__magic_name__ = self[r, c]
return result
def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any:
assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase )
assert self.row == self.column == u.row == v.row # u, v should be column vector
assert u.column == v.column == 1 # u, v should be column vector
# Calculate
__magic_name__ = v.transpose()
__magic_name__ = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
# Testing
if __name__ == "__main__":
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Matrix(3 , 3 , 0 )
for i in range(3 ):
__magic_name__ = 1
print(F'a^(-1) is {ainv}' )
# u, v
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3
__magic_name__ = Matrix(3 , 1 , 0 )
__magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5
print(F'u is {u}' )
print(F'v is {v}' )
print(F'uv^T is {u * v.transpose()}' )
# Sherman Morrison
print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' )
def __snake_case ( ):
'''simple docstring'''
import doctest
doctest.testmod()
testa()
| 664 | 1 |
'''simple docstring'''
from ....configuration_utils import PretrainedConfig
from ....utils import logging
__magic_name__ : List[str] =logging.get_logger(__name__)
__magic_name__ : Tuple ={
'Visual-Attention-Network/van-base': (
'https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json'
),
}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : List[str] = '''van'''
def __init__( self : Optional[int] , _lowerCamelCase : Tuple=2_24 , _lowerCamelCase : List[Any]=3 , _lowerCamelCase : Dict=[7, 3, 3, 3] , _lowerCamelCase : Optional[Any]=[4, 2, 2, 2] , _lowerCamelCase : int=[64, 1_28, 3_20, 5_12] , _lowerCamelCase : Tuple=[3, 3, 12, 3] , _lowerCamelCase : str=[8, 8, 4, 4] , _lowerCamelCase : Any="gelu" , _lowerCamelCase : Tuple=0.02 , _lowerCamelCase : List[str]=1e-6 , _lowerCamelCase : List[Any]=1e-2 , _lowerCamelCase : List[Any]=0.0 , _lowerCamelCase : List[Any]=0.0 , **_lowerCamelCase : Union[str, Any] , ) -> Tuple:
super().__init__(**_lowerCamelCase )
__magic_name__ = image_size
__magic_name__ = num_channels
__magic_name__ = patch_sizes
__magic_name__ = strides
__magic_name__ = hidden_sizes
__magic_name__ = depths
__magic_name__ = mlp_ratios
__magic_name__ = hidden_act
__magic_name__ = initializer_range
__magic_name__ = layer_norm_eps
__magic_name__ = layer_scale_init_value
__magic_name__ = drop_path_rate
__magic_name__ = dropout_rate
| 664 |
'''simple docstring'''
import argparse
import logging
from collections import namedtuple
import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer # The authors' implementation
from transformers import BertTokenizer
logging.basicConfig(level=logging.INFO)
__magic_name__ : List[Any] =logging.getLogger(__name__)
__magic_name__ : int ='Hello world! cécé herlolip'
__magic_name__ : List[Any] =namedtuple(
'BertAbsConfig',
[
'temp_dir',
'large',
'use_bert_emb',
'finetune_bert',
'encoder',
'share_emb',
'max_pos',
'enc_layers',
'enc_hidden_size',
'enc_heads',
'enc_ff_size',
'enc_dropout',
'dec_layers',
'dec_hidden_size',
'dec_heads',
'dec_ff_size',
'dec_dropout',
],
)
def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ):
'''simple docstring'''
__magic_name__ = BertAbsConfig(
temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , )
__magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage )
__magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ )
original.eval()
__magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) )
new_model.eval()
# -------------------
# Convert the weights
# -------------------
logging.info("convert the model" )
new_model.bert.load_state_dict(original.bert.state_dict() )
new_model.decoder.load_state_dict(original.decoder.state_dict() )
new_model.generator.load_state_dict(original.generator.state_dict() )
# ----------------------------------
# Make sure the outpus are identical
# ----------------------------------
logging.info("Make sure that the models' outputs are identical" )
__magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" )
# prepare the model inputs
__magic_name__ = tokenizer.encode("This is sample éàalj'-." )
encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
__magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." )
decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) )
__magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 )
# failsafe to make sure the weights reset does not affect the
# loaded weights.
assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0
# forward pass
__magic_name__ = encoder_input_ids
__magic_name__ = decoder_input_ids
__magic_name__ = __magic_name__ = None
__magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = __magic_name__ = None
__magic_name__ = None
# The original model does not apply the geneator layer immediatly but rather in
# the beam search (where it combines softmax + linear layer). Since we already
# apply the softmax in our generation process we only apply the linear layer here.
# We make sure that the outputs of the full stack are identical
__magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = original.generator(lowerCamelCase_ )
__magic_name__ = new_model(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0]
__magic_name__ = new_model.generator(lowerCamelCase_ )
__magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) )
__magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if are_identical:
logging.info("all weights are equal up to 1e-3" )
else:
raise ValueError("the weights are different. The new model is likely different from the original one." )
# The model has been saved with torch.save(model) and this is bound to the exact
# directory structure. We save the state_dict instead.
logging.info("saving the model's state dictionary" )
torch.save(
new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" )
if __name__ == "__main__":
__magic_name__ : Dict =argparse.ArgumentParser()
parser.add_argument(
'--bertabs_checkpoint_path',
default=None,
type=str,
required=True,
help='Path the official PyTorch dump.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
required=True,
help='Path to the output PyTorch model.',
)
__magic_name__ : Any =parser.parse_args()
convert_bertabs_checkpoints(
args.bertabs_checkpoint_path,
args.pytorch_dump_folder_path,
)
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int ):
'''simple docstring'''
if number > 0:
raise ValueError("input must be a negative integer" )
__magic_name__ = len(bin(lowerCamelCase_ )[3:] )
__magic_name__ = bin(abs(lowerCamelCase_ ) - (1 << binary_number_length) )[3:]
__magic_name__ = (
(
"1"
+ "0" * (binary_number_length - len(lowerCamelCase_ ))
+ twos_complement_number
)
if number < 0
else "0"
)
return "0b" + twos_complement_number
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 |
'''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.generation import DisjunctiveConstraint
@require_torch
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : List[str] ) -> str:
# For consistency across different places the DisjunctiveConstraint is called,
# dc.token_ids is a list of integers. It is also initialized only by integers.
__magic_name__ = [[1, 2, 4], [1, 2, 3, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) )
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] )
def __A ( self : List[Any] ) -> str:
# We can't have constraints that are complete subsets of another. This leads to a preverse
# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
__magic_name__ = [[1, 2], [1, 2, 3, 4]]
with self.assertRaises(_lowerCamelCase ):
DisjunctiveConstraint(_lowerCamelCase ) # fails here
def __A ( self : List[Any] ) -> int:
__magic_name__ = [[1, 2, 3], [1, 2, 4]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
__magic_name__ = stepped is True and completed is False and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 )
__magic_name__ = stepped is True and completed is True and reset is False
self.assertTrue(_lowerCamelCase )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 3] )
def __A ( self : Any ) -> Union[str, Any]:
__magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]
__magic_name__ = DisjunctiveConstraint(_lowerCamelCase )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2, 4] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 4, 5] )
dc.reset()
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 3 )
self.assertTrue(dc.current_seq == [1] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 2 )
self.assertTrue(dc.current_seq == [1, 2] )
__magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.remaining() == 0 )
self.assertTrue(dc.current_seq == [1, 2, 5] )
| 664 | 1 |
'''simple docstring'''
import inspect
import unittest
import warnings
from transformers import DeiTConfig
from transformers.models.auto import get_values
from transformers.testing_utils import (
require_accelerate,
require_torch,
require_torch_gpu,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import (
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
MODEL_MAPPING,
DeiTForImageClassification,
DeiTForImageClassificationWithTeacher,
DeiTForMaskedImageModeling,
DeiTModel,
)
from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DeiTImageProcessor
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : List[str] , _lowerCamelCase : Tuple , _lowerCamelCase : str=13 , _lowerCamelCase : Dict=30 , _lowerCamelCase : Tuple=2 , _lowerCamelCase : str=3 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : int=5 , _lowerCamelCase : Tuple=4 , _lowerCamelCase : str=37 , _lowerCamelCase : Union[str, Any]="gelu" , _lowerCamelCase : Dict=0.1 , _lowerCamelCase : Optional[int]=0.1 , _lowerCamelCase : Dict=10 , _lowerCamelCase : List[str]=0.02 , _lowerCamelCase : List[str]=3 , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : str=2 , ) -> Optional[Any]:
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = image_size
__magic_name__ = patch_size
__magic_name__ = num_channels
__magic_name__ = is_training
__magic_name__ = use_labels
__magic_name__ = hidden_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
__magic_name__ = intermediate_size
__magic_name__ = hidden_act
__magic_name__ = hidden_dropout_prob
__magic_name__ = attention_probs_dropout_prob
__magic_name__ = type_sequence_label_size
__magic_name__ = initializer_range
__magic_name__ = scope
__magic_name__ = encoder_stride
# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
__magic_name__ = (image_size // patch_size) ** 2
__magic_name__ = num_patches + 2
def __A ( self : str ) -> List[str]:
__magic_name__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__magic_name__ = self.get_config()
return config, pixel_values, labels
def __A ( self : Tuple ) -> Dict:
return DeiTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , 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 , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : List[Any] ) -> List[str]:
__magic_name__ = DeiTModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = model(_lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __A ( self : List[str] , _lowerCamelCase : Dict , _lowerCamelCase : Any , _lowerCamelCase : Optional[int] ) -> Tuple:
__magic_name__ = DeiTForMaskedImageModeling(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = model(_lowerCamelCase )
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
__magic_name__ = 1
__magic_name__ = DeiTForMaskedImageModeling(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__magic_name__ = model(_lowerCamelCase )
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def __A ( self : Optional[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Dict , _lowerCamelCase : Dict ) -> str:
__magic_name__ = self.type_sequence_label_size
__magic_name__ = DeiTForImageClassification(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = model(_lowerCamelCase , labels=_lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
__magic_name__ = 1
__magic_name__ = DeiTForImageClassification(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__magic_name__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__magic_name__ = model(_lowerCamelCase , labels=_lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def __A ( self : List[str] ) -> Optional[int]:
__magic_name__ = self.prepare_config_and_inputs()
(
(
__magic_name__
) , (
__magic_name__
) , (
__magic_name__
) ,
) = config_and_inputs
__magic_name__ = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class UpperCamelCase_ ( A , A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Optional[int] = (
(
DeiTModel,
DeiTForImageClassification,
DeiTForImageClassificationWithTeacher,
DeiTForMaskedImageModeling,
)
if is_torch_available()
else ()
)
UpperCAmelCase__ : List[str] = (
{
'''feature-extraction''': DeiTModel,
'''image-classification''': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
}
if is_torch_available()
else {}
)
UpperCAmelCase__ : str = False
UpperCAmelCase__ : str = False
UpperCAmelCase__ : int = False
def __A ( self : Union[str, Any] ) -> Optional[Any]:
__magic_name__ = DeiTModelTester(self )
__magic_name__ = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 )
def __A ( self : Union[str, Any] ) -> Tuple:
self.config_tester.run_common_tests()
@unittest.skip(reason="DeiT does not use inputs_embeds" )
def __A ( self : Optional[Any] ) -> Optional[int]:
pass
def __A ( self : Tuple ) -> Any:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__magic_name__ = model_class(_lowerCamelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
__magic_name__ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) )
def __A ( self : Dict ) -> int:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__magic_name__ = model_class(_lowerCamelCase )
__magic_name__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__magic_name__ = [*signature.parameters.keys()]
__magic_name__ = ["pixel_values"]
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
def __A ( self : Tuple ) -> Any:
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCamelCase )
def __A ( self : Tuple ) -> Union[str, Any]:
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase )
def __A ( self : str ) -> str:
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase )
def __A ( self : List[str] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : List[Any]=False ) -> int:
__magic_name__ = super()._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase )
if return_labels:
if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
del inputs_dict["labels"]
return inputs_dict
def __A ( self : Union[str, Any] ) -> List[str]:
if not self.model_tester.is_training:
return
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
__magic_name__ = True
for model_class in self.all_model_classes:
# DeiTForImageClassificationWithTeacher supports inference-only
if (
model_class in get_values(_lowerCamelCase )
or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
):
continue
__magic_name__ = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__magic_name__ = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase )
__magic_name__ = model(**_lowerCamelCase ).loss
loss.backward()
def __A ( self : Any ) -> Dict:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
if not self.model_tester.is_training:
return
__magic_name__ = False
__magic_name__ = True
for model_class in self.all_model_classes:
if model_class in get_values(_lowerCamelCase ) or not model_class.supports_gradient_checkpointing:
continue
# DeiTForImageClassificationWithTeacher supports inference-only
if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
continue
__magic_name__ = model_class(_lowerCamelCase )
model.gradient_checkpointing_enable()
model.to(_lowerCamelCase )
model.train()
__magic_name__ = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase )
__magic_name__ = model(**_lowerCamelCase ).loss
loss.backward()
def __A ( self : Tuple ) -> Any:
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
__magic_name__ = [
{"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
{"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
{"title": "regression", "num_labels": 1, "dtype": torch.float},
]
for model_class in self.all_model_classes:
if (
model_class
not in [
*get_values(_lowerCamelCase ),
*get_values(_lowerCamelCase ),
]
or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
):
continue
for problem_type in problem_types:
with self.subTest(msg=f'Testing {model_class} with {problem_type["title"]}' ):
__magic_name__ = problem_type["title"]
__magic_name__ = problem_type["num_labels"]
__magic_name__ = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__magic_name__ = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase )
if problem_type["num_labels"] > 1:
__magic_name__ = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] )
__magic_name__ = inputs["labels"].to(problem_type["dtype"] )
# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
# they have the same size." which is a symptom something in wrong for the regression problem.
# See https://github.com/huggingface/transformers/issues/11780
with warnings.catch_warnings(record=_lowerCamelCase ) as warning_list:
__magic_name__ = model(**_lowerCamelCase ).loss
for w in warning_list:
if "Using a target size that is different to the input size" in str(w.message ):
raise ValueError(
f'Something is going wrong in the regression problem: intercepted {w.message}' )
loss.backward()
@slow
def __A ( self : Any ) -> Any:
for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__magic_name__ = DeiTModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self : int ) -> Union[str, Any]:
return (
DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" )
if is_vision_available()
else None
)
@slow
def __A ( self : List[Any] ) -> Tuple:
__magic_name__ = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to(
_lowerCamelCase )
__magic_name__ = self.default_image_processor
__magic_name__ = prepare_img()
__magic_name__ = image_processor(images=_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase )
# forward pass
with torch.no_grad():
__magic_name__ = model(**_lowerCamelCase )
# verify the logits
__magic_name__ = torch.Size((1, 10_00) )
self.assertEqual(outputs.logits.shape , _lowerCamelCase )
__magic_name__ = torch.tensor([-1.0_266, 0.1_912, -1.2_861] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
@slow
@require_accelerate
@require_torch_gpu
def __A ( self : int ) -> str:
__magic_name__ = DeiTModel.from_pretrained(
"facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" )
__magic_name__ = self.default_image_processor
__magic_name__ = prepare_img()
__magic_name__ = image_processor(images=_lowerCamelCase , return_tensors="pt" )
__magic_name__ = inputs.pixel_values.to(_lowerCamelCase )
# forward pass to make sure inference works in fp16
with torch.no_grad():
__magic_name__ = model(_lowerCamelCase )
| 664 |
'''simple docstring'''
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
__magic_name__ : Dict ={
'return_dict': False,
'output_hidden_states': True,
'output_attentions': True,
'torchscript': True,
'torch_dtype': 'float16',
'use_bfloat16': True,
'tf_legacy_loss': True,
'pruned_heads': {'a': 1},
'tie_word_embeddings': False,
'is_decoder': True,
'cross_attention_hidden_size': 1_28,
'add_cross_attention': True,
'tie_encoder_decoder': True,
'max_length': 50,
'min_length': 3,
'do_sample': True,
'early_stopping': True,
'num_beams': 3,
'num_beam_groups': 3,
'diversity_penalty': 0.5,
'temperature': 2.0,
'top_k': 10,
'top_p': 0.7,
'typical_p': 0.2,
'repetition_penalty': 0.8,
'length_penalty': 0.8,
'no_repeat_ngram_size': 5,
'encoder_no_repeat_ngram_size': 5,
'bad_words_ids': [1, 2, 3],
'num_return_sequences': 3,
'chunk_size_feed_forward': 5,
'output_scores': True,
'return_dict_in_generate': True,
'forced_bos_token_id': 2,
'forced_eos_token_id': 3,
'remove_invalid_values': True,
'architectures': ['BertModel'],
'finetuning_task': 'translation',
'id2label': {0: 'label'},
'label2id': {'label': '0'},
'tokenizer_class': 'BertTokenizerFast',
'prefix': 'prefix',
'bos_token_id': 6,
'pad_token_id': 7,
'eos_token_id': 8,
'sep_token_id': 9,
'decoder_start_token_id': 10,
'exponential_decay_length_penalty': (5, 1.0_1),
'suppress_tokens': [0, 1],
'begin_suppress_tokens': 2,
'task_specific_params': {'translation': 'some_params'},
'problem_type': 'regression',
}
@is_staging_test
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def __A ( cls : Any ) -> Union[str, Any]:
__magic_name__ = TOKEN
HfFolder.save_token(_lowerCamelCase )
@classmethod
def __A ( cls : Any ) -> Tuple:
try:
delete_repo(token=cls._token , repo_id="test-config" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-config-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-config" )
except HTTPError:
pass
def __A ( self : Optional[Any] ) -> Dict:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("test-config" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="test-config" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : str ) -> Optional[int]:
__magic_name__ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 )
config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-config-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
_lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token )
__magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : Optional[int] ) -> Union[str, Any]:
CustomConfig.register_for_auto_class()
__magic_name__ = CustomConfig(attribute=42 )
config.push_to_hub("test-dynamic-config" , use_auth_token=self._token )
# This has added the proper auto_map field to the config
self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} )
__magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase )
# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
self.assertEqual(new_config.__class__.__name__ , "CustomConfig" )
self.assertEqual(new_config.attribute , 42 )
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Optional[Any]:
__magic_name__ = GPTaConfig()
# attempt to modify each of int/float/bool/str config records and verify they were updated
__magic_name__ = c.n_embd + 1 # int
__magic_name__ = c.resid_pdrop + 1.0 # float
__magic_name__ = not c.scale_attn_weights # bool
__magic_name__ = c.summary_type + "foo" # str
c.update_from_string(
f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' )
self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" )
self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" )
self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" )
self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" )
def __A ( self : List[Any] ) -> Union[str, Any]:
__magic_name__ = PretrainedConfig()
__magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to addin config_common_kwargs above.
self.assertListEqual(
_lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] )
__magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )]
if len(_lowerCamelCase ) > 0:
raise ValueError(
"The following keys are set with the default values in"
" `test_configuration_common.config_common_kwargs` pick another value for them:"
f' {", ".join(_lowerCamelCase )}.' )
def __A ( self : List[Any] ) -> List[Any]:
with self.assertRaises(_lowerCamelCase ):
# config is in subfolder, the following should not work without specifying the subfolder
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" )
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" )
self.assertIsNotNone(_lowerCamelCase )
def __A ( self : Tuple ) -> int:
# A mock response for an HTTP head request to emulate server down
__magic_name__ = mock.Mock()
__magic_name__ = 5_00
__magic_name__ = {}
__magic_name__ = HTTPError
__magic_name__ = {}
# Download this model to make sure it's in the cache.
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head:
__magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
def __A ( self : Union[str, Any] ) -> Dict:
# This test is for deprecated behavior and can be removed in v5
__magic_name__ = BertConfig.from_pretrained(
"https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" )
def __A ( self : Dict ) -> Optional[int]:
__magic_name__ = AutoConfig.from_pretrained("bert-base-cased" )
__magic_name__ = ["config.4.0.0.json"]
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(_lowerCamelCase )
__magic_name__ = 2
json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) )
# This should pick the new configuration file as the version of Transformers is > 4.0.0
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
__magic_name__ = ["config.42.0.0.json"]
__magic_name__ = 7_68
configuration.save_pretrained(_lowerCamelCase )
shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) )
__magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 7_68 )
def __A ( self : Optional[int] ) -> str:
# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
__magic_name__ = "hf-internal-testing/test-two-configs"
import transformers as new_transformers
__magic_name__ = "v4.0.0"
__magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained(
_lowerCamelCase , return_unused_kwargs=_lowerCamelCase )
self.assertEqual(new_configuration.hidden_size , 2 )
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(_lowerCamelCase , {} )
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
__magic_name__ = "v3.0.0"
__magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase )
self.assertEqual(old_configuration.hidden_size , 7_68 )
| 664 | 1 |
'''simple docstring'''
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
__magic_name__ : Any =datasets.utils.logging.get_logger(__name__)
@dataclass
class UpperCamelCase_ ( datasets.BuilderConfig ):
"""simple docstring"""
UpperCAmelCase__ : Optional[datasets.Features] = None
UpperCAmelCase__ : str = "utf-8"
UpperCAmelCase__ : Optional[str] = None
UpperCAmelCase__ : Optional[str] = None
UpperCAmelCase__ : bool = True # deprecated
UpperCAmelCase__ : Optional[int] = None # deprecated
UpperCAmelCase__ : int = 10 << 20 # 10MB
UpperCAmelCase__ : Optional[bool] = None
class UpperCamelCase_ ( datasets.ArrowBasedBuilder ):
"""simple docstring"""
UpperCAmelCase__ : str = JsonConfig
def __A ( self : Optional[int] ) -> Optional[int]:
if self.config.block_size is not None:
logger.warning("The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead" )
__magic_name__ = 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 __A ( self : Any , _lowerCamelCase : Tuple ) -> Dict:
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}' )
__magic_name__ = dl_manager.download_and_extract(self.config.data_files )
if isinstance(_lowerCamelCase , (str, list, tuple) ):
__magic_name__ = data_files
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = [files]
__magic_name__ = [dl_manager.iter_files(_lowerCamelCase ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )]
__magic_name__ = []
for split_name, files in data_files.items():
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = [files]
__magic_name__ = [dl_manager.iter_files(_lowerCamelCase ) for file in files]
splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={"files": files} ) )
return splits
def __A ( self : Union[str, Any] , _lowerCamelCase : pa.Table ) -> pa.Table:
if self.config.features is not None:
# adding missing columns
for column_name in set(self.config.features ) - set(pa_table.column_names ):
__magic_name__ = self.config.features.arrow_schema.field(_lowerCamelCase ).type
__magic_name__ = pa_table.append_column(_lowerCamelCase , pa.array([None] * len(_lowerCamelCase ) , type=_lowerCamelCase ) )
# more expensive cast to support nested structures with keys in a different order
# allows str <-> int/float or str to Audio for example
__magic_name__ = table_cast(_lowerCamelCase , self.config.features.arrow_schema )
return pa_table
def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]:
for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ):
# If the file is one json object and if we need to look at the list of items in one specific field
if self.config.field is not None:
with open(_lowerCamelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f:
__magic_name__ = json.load(_lowerCamelCase )
# We keep only the field we are interested in
__magic_name__ = dataset[self.config.field]
# We accept two format: a list of dicts or a dict of lists
if isinstance(_lowerCamelCase , (list, tuple) ):
__magic_name__ = set().union(*[row.keys() for row in dataset] )
__magic_name__ = {col: [row.get(_lowerCamelCase ) for row in dataset] for col in keys}
else:
__magic_name__ = dataset
__magic_name__ = pa.Table.from_pydict(_lowerCamelCase )
yield file_idx, self._cast_table(_lowerCamelCase )
# If the file has one json object per line
else:
with open(_lowerCamelCase , "rb" ) as f:
__magic_name__ = 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
__magic_name__ = max(self.config.chunksize // 32 , 16 << 10 )
__magic_name__ = (
self.config.encoding_errors if self.config.encoding_errors is not None else "strict"
)
while True:
__magic_name__ = f.read(self.config.chunksize )
if not batch:
break
# Finish current line
try:
batch += f.readline()
except (AttributeError, io.UnsupportedOperation):
batch += readline(_lowerCamelCase )
# PyArrow only accepts utf-8 encoded bytes
if self.config.encoding != "utf-8":
__magic_name__ = batch.decode(self.config.encoding , errors=_lowerCamelCase ).encode("utf-8" )
try:
while True:
try:
__magic_name__ = paj.read_json(
io.BytesIO(_lowerCamelCase ) , read_options=paj.ReadOptions(block_size=_lowerCamelCase ) )
break
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
if (
isinstance(_lowerCamelCase , pa.ArrowInvalid )
and "straddling" not in str(_lowerCamelCase )
or block_size > len(_lowerCamelCase )
):
raise
else:
# Increase the block size in case it was too small.
# The block size will be reset for the next file.
logger.debug(
f'Batch of {len(_lowerCamelCase )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.' )
block_size *= 2
except pa.ArrowInvalid as e:
try:
with open(
_lowerCamelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f:
__magic_name__ = json.load(_lowerCamelCase )
except json.JSONDecodeError:
logger.error(f'Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}' )
raise e
# If possible, parse the file as a list of json objects and exit the loop
if isinstance(_lowerCamelCase , _lowerCamelCase ): # list is the only sequence type supported in JSON
try:
__magic_name__ = set().union(*[row.keys() for row in dataset] )
__magic_name__ = {col: [row.get(_lowerCamelCase ) for row in dataset] for col in keys}
__magic_name__ = pa.Table.from_pydict(_lowerCamelCase )
except (pa.ArrowInvalid, AttributeError) as e:
logger.error(f'Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}' )
raise ValueError(f'Not able to read records in the JSON file at {file}.' ) from None
yield file_idx, self._cast_table(_lowerCamelCase )
break
else:
logger.error(f'Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}' )
raise ValueError(
f'Not able to read records in the JSON file at {file}. '
f'You should probably indicate the field of the JSON file containing your records. '
f'This JSON file contain the following fields: {str(list(dataset.keys() ) )}. '
f'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ' ) from None
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase )
batch_idx += 1
| 664 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision
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 DPTImageProcessor
class UpperCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict:
__magic_name__ = size if size is not None else {"height": 18, "width": 18}
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = num_channels
__magic_name__ = image_size
__magic_name__ = min_resolution
__magic_name__ = max_resolution
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = do_normalize
__magic_name__ = image_mean
__magic_name__ = image_std
def __A ( self : int ) -> List[str]:
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
@require_torch
@require_vision
class UpperCamelCase_ ( A , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None
def __A ( self : Dict ) -> Any:
__magic_name__ = DPTImageProcessingTester(self )
@property
def __A ( self : str ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : Tuple ) -> List[str]:
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) )
self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) )
self.assertTrue(hasattr(_lowerCamelCase , "size" ) )
def __A ( self : List[str] ) -> List[Any]:
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"height": 18, "width": 18} )
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {"height": 42, "width": 42} )
def __A ( self : Union[str, Any] ) -> List[str]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Dict ) -> Optional[Any]:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
def __A ( self : Optional[int] ) -> Dict:
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
__magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
| 664 | 1 |
'''simple docstring'''
import io
import math
from typing import Dict, Optional, Union
import numpy as np
from huggingface_hub import hf_hub_download
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
ChannelDimension,
ImageInput,
get_image_size,
infer_channel_dimension_format,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_torch_available, is_vision_available, logging
from ...utils.import_utils import requires_backends
if is_vision_available():
import textwrap
from PIL import Image, ImageDraw, ImageFont
if is_torch_available():
import torch
from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
__magic_name__ : Any =False
__magic_name__ : Optional[int] =logging.get_logger(__name__)
__magic_name__ : Optional[Any] ='ybelkada/fonts'
def __snake_case ( ):
'''simple docstring'''
if is_torch_available() and not is_torch_greater_or_equal_than_1_11:
raise ImportError(
F'You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use '
"Pix2StructImageProcessor. Please upgrade torch." )
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : str ):
'''simple docstring'''
requires_backends(lowerCamelCase_ , ["torch"] )
_check_torch_version()
__magic_name__ = image_tensor.unsqueeze(0 )
__magic_name__ = torch.nn.functional.unfold(lowerCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) )
__magic_name__ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , lowerCamelCase_ , lowerCamelCase_ , -1 )
__magic_name__ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape(
image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , )
return patches.unsqueeze(0 )
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : int = 36 , lowerCamelCase_ : str = "black" , lowerCamelCase_ : str = "white" , lowerCamelCase_ : int = 5 , lowerCamelCase_ : int = 5 , lowerCamelCase_ : int = 5 , lowerCamelCase_ : int = 5 , lowerCamelCase_ : Optional[bytes] = None , lowerCamelCase_ : Optional[str] = None , ):
'''simple docstring'''
requires_backends(lowerCamelCase_ , "vision" )
# Add new lines so that each line is no more than 80 characters.
__magic_name__ = textwrap.TextWrapper(width=80 )
__magic_name__ = wrapper.wrap(text=lowerCamelCase_ )
__magic_name__ = "\n".join(lowerCamelCase_ )
if font_bytes is not None and font_path is None:
__magic_name__ = io.BytesIO(lowerCamelCase_ )
elif font_path is not None:
__magic_name__ = font_path
else:
__magic_name__ = hf_hub_download(lowerCamelCase_ , "Arial.TTF" )
__magic_name__ = ImageFont.truetype(lowerCamelCase_ , encoding="UTF-8" , size=lowerCamelCase_ )
# Use a temporary canvas to determine the width and height in pixels when
# rendering the text.
__magic_name__ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , lowerCamelCase_ ) )
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = temp_draw.textbbox((0, 0) , lowerCamelCase_ , lowerCamelCase_ )
# Create the actual image with a bit of padding around the text.
__magic_name__ = text_width + left_padding + right_padding
__magic_name__ = text_height + top_padding + bottom_padding
__magic_name__ = Image.new("RGB" , (image_width, image_height) , lowerCamelCase_ )
__magic_name__ = ImageDraw.Draw(lowerCamelCase_ )
draw.text(xy=(left_padding, top_padding) , text=lowerCamelCase_ , fill=lowerCamelCase_ , font=lowerCamelCase_ )
return image
def __snake_case ( lowerCamelCase_ : np.ndarray , lowerCamelCase_ : str , **lowerCamelCase_ : str ):
'''simple docstring'''
requires_backends(lowerCamelCase_ , "vision" )
# Convert to PIL image if necessary
__magic_name__ = to_pil_image(lowerCamelCase_ )
__magic_name__ = render_text(lowerCamelCase_ , **lowerCamelCase_ )
__magic_name__ = max(header_image.width , image.width )
__magic_name__ = int(image.height * (new_width / image.width) )
__magic_name__ = int(header_image.height * (new_width / header_image.width) )
__magic_name__ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" )
new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) )
new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) )
# Convert back to the original framework if necessary
__magic_name__ = to_numpy_array(lowerCamelCase_ )
if infer_channel_dimension_format(lowerCamelCase_ ) == ChannelDimension.LAST:
__magic_name__ = to_channel_dimension_format(lowerCamelCase_ , ChannelDimension.LAST )
return new_image
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : List[Any] = ['''flattened_patches''']
def __init__( self : Optional[Any] , _lowerCamelCase : bool = True , _lowerCamelCase : bool = True , _lowerCamelCase : Dict[str, int] = None , _lowerCamelCase : int = 20_48 , _lowerCamelCase : bool = False , **_lowerCamelCase : Tuple , ) -> None:
super().__init__(**_lowerCamelCase )
__magic_name__ = patch_size if patch_size is not None else {"height": 16, "width": 16}
__magic_name__ = do_normalize
__magic_name__ = do_convert_rgb
__magic_name__ = max_patches
__magic_name__ = is_vqa
def __A ( self : int , _lowerCamelCase : np.ndarray , _lowerCamelCase : int , _lowerCamelCase : dict , **_lowerCamelCase : int ) -> np.ndarray:
requires_backends(self.extract_flattened_patches , "torch" )
_check_torch_version()
# convert to torch
__magic_name__ = to_channel_dimension_format(_lowerCamelCase , ChannelDimension.FIRST )
__magic_name__ = torch.from_numpy(_lowerCamelCase )
__magic_name__ , __magic_name__ = patch_size["height"], patch_size["width"]
__magic_name__ , __magic_name__ = get_image_size(_lowerCamelCase )
# maximize scale s.t.
__magic_name__ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) )
__magic_name__ = max(min(math.floor(scale * image_height / patch_height ) , _lowerCamelCase ) , 1 )
__magic_name__ = max(min(math.floor(scale * image_width / patch_width ) , _lowerCamelCase ) , 1 )
__magic_name__ = max(num_feasible_rows * patch_height , 1 )
__magic_name__ = max(num_feasible_cols * patch_width , 1 )
__magic_name__ = torch.nn.functional.interpolate(
image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_lowerCamelCase , antialias=_lowerCamelCase , ).squeeze(0 )
# [1, rows, columns, patch_height * patch_width * image_channels]
__magic_name__ = torch_extract_patches(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
__magic_name__ = patches.shape
__magic_name__ = patches_shape[1]
__magic_name__ = patches_shape[2]
__magic_name__ = patches_shape[3]
# [rows * columns, patch_height * patch_width * image_channels]
__magic_name__ = patches.reshape([rows * columns, depth] )
# [rows * columns, 1]
__magic_name__ = torch.arange(_lowerCamelCase ).reshape([rows, 1] ).repeat(1 , _lowerCamelCase ).reshape([rows * columns, 1] )
__magic_name__ = torch.arange(_lowerCamelCase ).reshape([1, columns] ).repeat(_lowerCamelCase , 1 ).reshape([rows * columns, 1] )
# Offset by 1 so the ids do not contain zeros, which represent padding.
row_ids += 1
col_ids += 1
# Prepare additional patch features.
# [rows * columns, 1]
__magic_name__ = row_ids.to(torch.floataa )
__magic_name__ = col_ids.to(torch.floataa )
# [rows * columns, 2 + patch_height * patch_width * image_channels]
__magic_name__ = torch.cat([row_ids, col_ids, patches] , -1 )
# [max_patches, 2 + patch_height * patch_width * image_channels]
__magic_name__ = torch.nn.functional.pad(_lowerCamelCase , [0, 0, 0, max_patches - (rows * columns)] ).float()
__magic_name__ = to_numpy_array(_lowerCamelCase )
return result
def __A ( self : str , _lowerCamelCase : np.ndarray , _lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase : Optional[int] ) -> np.ndarray:
if image.dtype == np.uinta:
__magic_name__ = image.astype(np.floataa )
# take mean across the whole `image`
__magic_name__ = np.mean(_lowerCamelCase )
__magic_name__ = np.std(_lowerCamelCase )
__magic_name__ = max(_lowerCamelCase , 1.0 / math.sqrt(np.prod(image.shape ) ) )
return normalize(_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase , **_lowerCamelCase )
def __A ( self : Any , _lowerCamelCase : ImageInput , _lowerCamelCase : Optional[str] = None , _lowerCamelCase : bool = None , _lowerCamelCase : Optional[bool] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[Dict[str, int]] = None , _lowerCamelCase : Optional[Union[str, TensorType]] = None , _lowerCamelCase : ChannelDimension = ChannelDimension.FIRST , **_lowerCamelCase : Union[str, Any] , ) -> ImageInput:
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
__magic_name__ = patch_size if patch_size is not None else self.patch_size
__magic_name__ = max_patches if max_patches is not None else self.max_patches
__magic_name__ = self.is_vqa
if kwargs.get("data_format" , _lowerCamelCase ) is not None:
raise ValueError("data_format is not an accepted input as the outputs are " )
__magic_name__ = make_list_of_images(_lowerCamelCase )
if not valid_images(_lowerCamelCase ):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray." )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
__magic_name__ = [convert_to_rgb(_lowerCamelCase ) for image in images]
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(_lowerCamelCase ) for image in images]
if is_vqa:
if header_text is None:
raise ValueError("A header text must be provided for VQA models." )
__magic_name__ = kwargs.pop("font_bytes" , _lowerCamelCase )
__magic_name__ = kwargs.pop("font_path" , _lowerCamelCase )
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__magic_name__ = [header_text] * len(_lowerCamelCase )
__magic_name__ = [
render_header(_lowerCamelCase , header_text[i] , font_bytes=_lowerCamelCase , font_path=_lowerCamelCase )
for i, image in enumerate(_lowerCamelCase )
]
if do_normalize:
__magic_name__ = [self.normalize(image=_lowerCamelCase ) for image in images]
# convert to torch tensor and permute
__magic_name__ = [
self.extract_flattened_patches(image=_lowerCamelCase , max_patches=_lowerCamelCase , patch_size=_lowerCamelCase )
for image in images
]
# create attention mask in numpy
__magic_name__ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images]
__magic_name__ = BatchFeature(
data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_lowerCamelCase )
return encoded_outputs
| 664 |
'''simple docstring'''
import numpy
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None:
__magic_name__ = input_array
# Random initial weights are assigned where first argument is the
# number of nodes in previous layer and second argument is the
# number of nodes in the next layer.
# Random initial weights are assigned.
# self.input_array.shape[1] is used to represent number of nodes in input layer.
# First hidden layer consists of 4 nodes.
__magic_name__ = numpy.random.rand(
self.input_array.shape[1] , 4 )
# Random initial values for the first hidden layer.
# First hidden layer has 4 nodes.
# Second hidden layer has 3 nodes.
__magic_name__ = numpy.random.rand(
4 , 3 )
# Random initial values for the second hidden layer.
# Second hidden layer has 3 nodes.
# Output layer has 1 node.
__magic_name__ = numpy.random.rand(3 , 1 )
# Real output values provided.
__magic_name__ = output_array
# Predicted output values by the neural network.
# Predicted_output array initially consists of zeroes.
__magic_name__ = numpy.zeros(output_array.shape )
def __A ( self : int ) -> numpy.ndarray:
__magic_name__ = sigmoid(
numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) )
# layer_between_first_hidden_layer_and_second_hidden_layer is the layer
# connecting the first hidden set of nodes with the second hidden set of nodes.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
# layer_between_second_hidden_layer_and_output is the layer connecting
# second hidden layer with the output node.
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return self.layer_between_second_hidden_layer_and_output
def __A ( self : Dict ) -> None:
__magic_name__ = numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , )
__magic_name__ = numpy.dot(
self.layer_between_input_and_first_hidden_layer.T , numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , )
__magic_name__ = numpy.dot(
self.input_array.T , numpy.dot(
numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , )
* sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , )
self.input_layer_and_first_hidden_layer_weights += (
updated_input_layer_and_first_hidden_layer_weights
)
self.first_hidden_layer_and_second_hidden_layer_weights += (
updated_first_hidden_layer_and_second_hidden_layer_weights
)
self.second_hidden_layer_and_output_layer_weights += (
updated_second_hidden_layer_and_output_layer_weights
)
def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None:
for iteration in range(1 , iterations + 1 ):
__magic_name__ = self.feedforward()
self.back_propagation()
if give_loss:
__magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) )
print(f'Iteration {iteration} Loss: {loss}' )
def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int:
__magic_name__ = input_arr
__magic_name__ = sigmoid(
numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
__magic_name__ = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return int(self.layer_between_second_hidden_layer_and_output > 0.6 )
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return 1 / (1 + numpy.exp(-value ))
def __snake_case ( lowerCamelCase_ : numpy.ndarray ):
'''simple docstring'''
return (value) * (1 - (value))
def __snake_case ( ):
'''simple docstring'''
__magic_name__ = numpy.array(
(
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
) , dtype=numpy.floataa , )
# True output values for the given input values.
__magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa )
# Calling neural network class.
__magic_name__ = TwoHiddenLayerNeuralNetwork(
input_array=lowerCamelCase_ , output_array=lowerCamelCase_ )
# Calling training function.
# Set give_loss to True if you want to see loss in every iteration.
neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ )
return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) )
if __name__ == "__main__":
example()
| 664 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__magic_name__ : List[str] =logging.get_logger(__name__)
__magic_name__ : str ={
'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/config.json',
'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/config.json',
'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/config.json',
'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/config.json',
'bert-base-multilingual-uncased': 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json',
'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json',
'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/config.json',
'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/config.json',
'bert-large-uncased-whole-word-masking': (
'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json'
),
'bert-large-cased-whole-word-masking': (
'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json'
),
'bert-large-uncased-whole-word-masking-finetuned-squad': (
'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json'
),
'bert-large-cased-whole-word-masking-finetuned-squad': (
'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json'
),
'bert-base-cased-finetuned-mrpc': 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json',
'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json',
'bert-base-german-dbmdz-uncased': 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json',
'cl-tohoku/bert-base-japanese': 'https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json',
'cl-tohoku/bert-base-japanese-whole-word-masking': (
'https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json'
),
'cl-tohoku/bert-base-japanese-char': (
'https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json'
),
'cl-tohoku/bert-base-japanese-char-whole-word-masking': (
'https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json'
),
'TurkuNLP/bert-base-finnish-cased-v1': (
'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json'
),
'TurkuNLP/bert-base-finnish-uncased-v1': (
'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json'
),
'wietsedv/bert-base-dutch-cased': 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json',
# See all BERT models at https://huggingface.co/models?filter=bert
}
class UpperCamelCase_ ( A ):
"""simple docstring"""
UpperCAmelCase__ : Union[str, Any] = '''bert'''
def __init__( self : Optional[int] , _lowerCamelCase : Any=3_05_22 , _lowerCamelCase : Optional[int]=7_68 , _lowerCamelCase : Tuple=12 , _lowerCamelCase : Any=12 , _lowerCamelCase : Any=30_72 , _lowerCamelCase : List[str]="gelu" , _lowerCamelCase : Dict=0.1 , _lowerCamelCase : List[Any]=0.1 , _lowerCamelCase : List[Any]=5_12 , _lowerCamelCase : int=2 , _lowerCamelCase : str=0.02 , _lowerCamelCase : List[str]=1e-12 , _lowerCamelCase : Tuple=0 , _lowerCamelCase : Optional[Any]="absolute" , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Tuple=None , **_lowerCamelCase : Dict , ) -> Dict:
super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
__magic_name__ = vocab_size
__magic_name__ = hidden_size
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
__magic_name__ = hidden_act
__magic_name__ = intermediate_size
__magic_name__ = hidden_dropout_prob
__magic_name__ = attention_probs_dropout_prob
__magic_name__ = max_position_embeddings
__magic_name__ = type_vocab_size
__magic_name__ = initializer_range
__magic_name__ = layer_norm_eps
__magic_name__ = position_embedding_type
__magic_name__ = use_cache
__magic_name__ = classifier_dropout
class UpperCamelCase_ ( A ):
"""simple docstring"""
@property
def __A ( self : str ) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
__magic_name__ = {0: "batch", 1: "choice", 2: "sequence"}
else:
__magic_name__ = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
("token_type_ids", dynamic_axis),
] )
| 664 |
'''simple docstring'''
import torch
from transformers import AutoModel
class UpperCamelCase_ ( torch.nn.Module ):
"""simple docstring"""
def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]:
super(_lowerCamelCase , self ).__init__()
__magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase )
__magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 )
__magic_name__ = torch.nn.Softmax(dim=1 )
def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]:
return self.bert(**_lowerCamelCase ).last_hidden_state
def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict:
return token_embeddings.sum(2 , keepdim=_lowerCamelCase )
def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]:
return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) )
def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]:
__magic_name__ = W_supports["sizes"].tolist()
__magic_name__ = W_supports["start_token_id"].item()
__magic_name__ = W_supports["end_token_id"].item()
del W_supports["sizes"]
del W_supports["start_token_id"]
del W_supports["end_token_id"]
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = self.BERT(**_lowerCamelCase )
__magic_name__ = None
__magic_name__ = None
__magic_name__ = W_supports["input_ids"] == start_token_id
__magic_name__ = W_supports["input_ids"] == end_token_id
for i, size in enumerate(_lowerCamelCase ):
if i == 0:
__magic_name__ = 0
else:
__magic_name__ = support_sizes[i - 1]
__magic_name__ = S[s : s + size][start_token_masks[s : s + size]]
__magic_name__ = S[s : s + size][end_token_masks[s : s + size]]
__magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 )
__magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 )
if p_starts is not None:
__magic_name__ = torch.vstack((p_starts, p_start) )
__magic_name__ = torch.vstack((p_ends, p_end) )
else:
__magic_name__ = p_start
__magic_name__ = p_end
return p_starts, p_ends
| 664 | 1 |
'''simple docstring'''
from torch import nn
class UpperCamelCase_ ( nn.Module ):
"""simple docstring"""
def __init__( self : List[str] , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[Any] ) -> Union[str, Any]:
super().__init__()
__magic_name__ = class_size
__magic_name__ = embed_size
# self.mlp1 = nn.Linear(embed_size, embed_size)
# self.mlp2 = (nn.Linear(embed_size, class_size))
__magic_name__ = nn.Linear(_lowerCamelCase , _lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : List[str] ) -> List[Any]:
# hidden_state = nn.functional.relu(self.mlp1(hidden_state))
# hidden_state = self.mlp2(hidden_state)
__magic_name__ = self.mlp(_lowerCamelCase )
return logits
| 664 |
'''simple docstring'''
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401
deprecate(
'stable diffusion controlnet',
'0.22.0',
'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.',
standard_warn=False,
stacklevel=3,
)
| 664 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__magic_name__ : Dict ={
'configuration_blenderbot': [
'BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP',
'BlenderbotConfig',
'BlenderbotOnnxConfig',
],
'tokenization_blenderbot': ['BlenderbotTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : List[str] =['BlenderbotTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : List[str] =[
'BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST',
'BlenderbotForCausalLM',
'BlenderbotForConditionalGeneration',
'BlenderbotModel',
'BlenderbotPreTrainedModel',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : Union[str, Any] =[
'TFBlenderbotForConditionalGeneration',
'TFBlenderbotModel',
'TFBlenderbotPreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : List[Any] =[
'FlaxBlenderbotForConditionalGeneration',
'FlaxBlenderbotModel',
'FlaxBlenderbotPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_blenderbot import (
BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlenderbotConfig,
BlenderbotOnnxConfig,
)
from .tokenization_blenderbot import BlenderbotTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_blenderbot_fast import BlenderbotTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blenderbot import (
BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST,
BlenderbotForCausalLM,
BlenderbotForConditionalGeneration,
BlenderbotModel,
BlenderbotPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blenderbot import (
TFBlenderbotForConditionalGeneration,
TFBlenderbotModel,
TFBlenderbotPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_blenderbot import (
FlaxBlenderbotForConditionalGeneration,
FlaxBlenderbotModel,
FlaxBlenderbotPreTrainedModel,
)
else:
import sys
__magic_name__ : Tuple =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 |
'''simple docstring'''
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
__magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ )
__magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ )
__magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ )
__magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"]
if config.model_type == "t5":
__magic_name__ = "SelfAttention"
if config.model_type == "longt5" and config.encoder_attention_type == "local":
__magic_name__ = "LocalSelfAttention"
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = "TransientGlobalSelfAttention"
else:
raise ValueError(
"Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"
" attribute with a value from ['local', 'transient-global]." )
# Encoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
if split_mlp_wi:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_global_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = tax_mlp_layer_norm
__magic_name__ = flax_model_encoder_layer_block
# Only for layer 0:
__magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
__magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_encoder_global_rel_embedding
# Assigning
__magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"]
__magic_name__ = tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers ):
__magic_name__ = F'layers_{str(lowerCamelCase_ )}'
# Self-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
"scale"
]
# Encoder-Decoder-Attention
__magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]
__magic_name__ = tax_enc_dec_attention_module["key"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["out"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["query"]["kernel"]
__magic_name__ = tax_enc_dec_attention_module["value"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
# MLP
if split_mlp_wi:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
else:
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
__magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
# Layer Normalization
__magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
# Assigning
__magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"]
__magic_name__ = tax_attention_key
__magic_name__ = tax_attention_out
__magic_name__ = tax_attention_query
__magic_name__ = tax_attention_value
__magic_name__ = tax_pre_attention_layer_norm
__magic_name__ = tax_enc_dec_attention_key
__magic_name__ = tax_enc_dec_attention_out
__magic_name__ = tax_enc_dec_attention_query
__magic_name__ = tax_enc_dec_attention_value
__magic_name__ = tax_cross_layer_norm
if split_mlp_wi:
__magic_name__ = tax_mlp_wi_a
__magic_name__ = tax_mlp_wi_a
else:
__magic_name__ = tax_mlp_wi
__magic_name__ = tax_mlp_wo
__magic_name__ = txa_mlp_layer_norm
__magic_name__ = flax_model_decoder_layer_block
# Decoder Normalization
__magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"]
__magic_name__ = txa_decoder_norm
# Only for layer 0:
__magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
__magic_name__ = tax_decoder_rel_embedding
# Token Embeddings
__magic_name__ = tax_model["target"]["token_embedder"]["embedding"]
__magic_name__ = txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
__magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"]
flax_model.save_pretrained(lowerCamelCase_ )
print("T5X Model was sucessfully converted!" )
if __name__ == "__main__":
__magic_name__ : Optional[Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.'
)
parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.')
parser.add_argument(
'--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.'
)
__magic_name__ : Optional[int] =parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 664 | 1 |
'''simple docstring'''
import glob
import os
import random
from string import ascii_lowercase, digits
import cva
__magic_name__ : Dict =''
__magic_name__ : List[Any] =''
__magic_name__ : Dict =''
__magic_name__ : Tuple =1 # (0 is vertical, 1 is horizontal)
def __snake_case ( ):
'''simple docstring'''
__magic_name__ , __magic_name__ = get_dataset(lowerCamelCase_ , lowerCamelCase_ )
print("Processing..." )
__magic_name__ , __magic_name__ , __magic_name__ = update_image_and_anno(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
for index, image in enumerate(lowerCamelCase_ ):
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
__magic_name__ = random_chars(32 )
__magic_name__ = paths[index].split(os.sep )[-1].rsplit("." , 1 )[0]
__magic_name__ = F'{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}'
cva.imwrite(F'/{file_root}.jpg' , lowerCamelCase_ , [cva.IMWRITE_JPEG_QUALITY, 85] )
print(F'Success {index+1}/{len(lowerCamelCase_ )} with {file_name}' )
__magic_name__ = []
for anno in new_annos[index]:
__magic_name__ = F'{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}'
annos_list.append(lowerCamelCase_ )
with open(F'/{file_root}.txt' , "w" ) as outfile:
outfile.write("\n".join(line for line in annos_list ) )
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = []
__magic_name__ = []
for label_file in glob.glob(os.path.join(lowerCamelCase_ , "*.txt" ) ):
__magic_name__ = label_file.split(os.sep )[-1].rsplit("." , 1 )[0]
with open(lowerCamelCase_ ) as in_file:
__magic_name__ = in_file.readlines()
__magic_name__ = os.path.join(lowerCamelCase_ , F'{label_name}.jpg' )
__magic_name__ = []
for obj_list in obj_lists:
__magic_name__ = obj_list.rstrip("\n" ).split(" " )
boxes.append(
[
int(obj[0] ),
float(obj[1] ),
float(obj[2] ),
float(obj[3] ),
float(obj[4] ),
] )
if not boxes:
continue
img_paths.append(lowerCamelCase_ )
labels.append(lowerCamelCase_ )
return img_paths, labels
def __snake_case ( lowerCamelCase_ : list , lowerCamelCase_ : list , lowerCamelCase_ : int = 1 ):
'''simple docstring'''
__magic_name__ = []
__magic_name__ = []
__magic_name__ = []
for idx in range(len(lowerCamelCase_ ) ):
__magic_name__ = []
__magic_name__ = img_list[idx]
path_list.append(lowerCamelCase_ )
__magic_name__ = anno_list[idx]
__magic_name__ = cva.imread(lowerCamelCase_ )
if flip_type == 1:
__magic_name__ = cva.flip(lowerCamelCase_ , lowerCamelCase_ )
for bbox in img_annos:
__magic_name__ = 1 - bbox[1]
new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] )
elif flip_type == 0:
__magic_name__ = cva.flip(lowerCamelCase_ , lowerCamelCase_ )
for bbox in img_annos:
__magic_name__ = 1 - bbox[2]
new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] )
new_annos_lists.append(lowerCamelCase_ )
new_imgs_list.append(lowerCamelCase_ )
return new_imgs_list, new_annos_lists, path_list
def __snake_case ( lowerCamelCase_ : int = 32 ):
'''simple docstring'''
assert number_char > 1, "The number of character should greater than 1"
__magic_name__ = ascii_lowercase + digits
return "".join(random.choice(lowerCamelCase_ ) for _ in range(lowerCamelCase_ ) )
if __name__ == "__main__":
main()
print('DONE ✅')
| 664 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class UpperCamelCase_ ( unittest.TestCase , A ):
"""simple docstring"""
def __A ( self : Optional[int] ) -> Any:
__magic_name__ = load_tool("text-to-speech" )
self.tool.setup()
def __A ( self : Union[str, Any] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
def __A ( self : List[str] ) -> int:
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
__magic_name__ = self.tool("hey" )
__magic_name__ = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
| 664 | 1 |
'''simple docstring'''
def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ):
'''simple docstring'''
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive" )
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b"
__magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) )
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1" ) )
for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 664 |
'''simple docstring'''
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
__magic_name__ : Dict =re.compile('[^A-Za-z_0-9]')
# parameters used in DuplicationIndex
__magic_name__ : int =10
__magic_name__ : Union[str, Any] =2_56
def __snake_case ( lowerCamelCase_ : List[str] ):
'''simple docstring'''
if len(lowerCamelCase_ ) < MIN_NUM_TOKENS:
return None
__magic_name__ = MinHash(num_perm=lowerCamelCase_ )
for token in set(lowerCamelCase_ ):
min_hash.update(token.encode() )
return min_hash
def __snake_case ( lowerCamelCase_ : str ):
'''simple docstring'''
return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0}
class UpperCamelCase_ :
"""simple docstring"""
def __init__( self : int , *,
_lowerCamelCase : float = 0.85 , ) -> Optional[Any]:
__magic_name__ = duplication_jaccard_threshold
__magic_name__ = NUM_PERM
__magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm )
__magic_name__ = defaultdict(_lowerCamelCase )
def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None:
__magic_name__ = self._index.query(_lowerCamelCase )
if code_key in self._index.keys:
print(f'Duplicate key {code_key}' )
return
self._index.insert(_lowerCamelCase , _lowerCamelCase )
if len(_lowerCamelCase ) > 0:
for base_duplicate in close_duplicates:
if base_duplicate in self._duplicate_clusters:
self._duplicate_clusters[base_duplicate].add(_lowerCamelCase )
break
else:
self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase )
def __A ( self : Union[str, Any] ) -> List[List[Dict]]:
__magic_name__ = []
for base, duplicates in self._duplicate_clusters.items():
__magic_name__ = [base] + list(_lowerCamelCase )
# reformat the cluster to be a list of dict
__magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster]
duplicate_clusters.append(_lowerCamelCase )
return duplicate_clusters
def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None:
__magic_name__ = self.get_duplicate_clusters()
with open(_lowerCamelCase , "w" ) as f:
json.dump(_lowerCamelCase , _lowerCamelCase )
def __snake_case ( lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ , __magic_name__ = element
__magic_name__ = 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 __snake_case ( lowerCamelCase_ : Type[Dataset] ):
'''simple docstring'''
with mp.Pool() as pool:
for data in pool.imap_unordered(
_compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ):
if data is not None:
yield data
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ):
'''simple docstring'''
__magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ )
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ):
di.add(lowerCamelCase_ , lowerCamelCase_ )
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
return di.get_duplicate_clusters()
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = get_tokens(lowerCamelCase_ )
__magic_name__ = get_tokens(lowerCamelCase_ )
return len(tokensa & tokensa ) / len(tokensa | tokensa )
__magic_name__ : List[str] =None
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = []
for elementa in cluster:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
for elementa in extremes:
__magic_name__ = _shared_dataset[elementa["base_index"]]["content"]
if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold:
elementa["copies"] += 1
break
else:
__magic_name__ = 1
extremes.append(lowerCamelCase_ )
return extremes
def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ):
'''simple docstring'''
global _shared_dataset
__magic_name__ = dataset
__magic_name__ = []
__magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ )
with mp.Pool() as pool:
for extremes in tqdm(
pool.imap_unordered(
lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ):
extremes_list.append(lowerCamelCase_ )
return extremes_list
def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ):
'''simple docstring'''
__magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster}
__magic_name__ = {}
__magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
for extremes in extremes_clusters:
for element in extremes:
__magic_name__ = element
__magic_name__ = duplicate_indices - set(extreme_dict.keys() )
__magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ )
# update duplicate_clusters
for cluster in duplicate_clusters:
for element in cluster:
__magic_name__ = element["base_index"] in extreme_dict
if element["is_extreme"]:
__magic_name__ = extreme_dict[element["base_index"]]["copies"]
print(F'Original dataset size: {len(lowerCamelCase_ )}' )
print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' )
print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' )
print(F'Filtered dataset size: {len(lowerCamelCase_ )}' )
return ds_filter, duplicate_clusters
| 664 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ : str =[
'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST',
'FocalNetForImageClassification',
'FocalNetForMaskedImageModeling',
'FocalNetBackbone',
'FocalNetModel',
'FocalNetPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_focalnet import (
FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST,
FocalNetBackbone,
FocalNetForImageClassification,
FocalNetForMaskedImageModeling,
FocalNetModel,
FocalNetPreTrainedModel,
)
else:
import sys
__magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 664 |
'''simple docstring'''
import argparse
import os
import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn
from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
if version.parse(nlp.__version__) != version.parse('0.8.3'):
raise Exception('requires gluonnlp == 0.8.3')
if version.parse(mx.__version__) != version.parse('1.5.0'):
raise Exception('requires mxnet == 1.5.0')
logging.set_verbosity_info()
__magic_name__ : Optional[int] =logging.get_logger(__name__)
__magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!'
def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ):
'''simple docstring'''
__magic_name__ = {
"attention_cell": "multi_head",
"num_layers": 4,
"units": 1024,
"hidden_size": 768,
"max_length": 512,
"num_heads": 8,
"scaled": True,
"dropout": 0.1,
"use_residual": True,
"embed_size": 1024,
"embed_dropout": 0.1,
"word_embed": None,
"layer_norm_eps": 1e-5,
"token_type_vocab_size": 2,
}
__magic_name__ = bort_4_8_768_1024_hparams
# Let's construct the original Bort model here
# Taken from official BERT implementation, see:
# https://github.com/alexa/bort/blob/master/bort/bort.py
__magic_name__ = BERTEncoder(
attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , )
# Vocab information needs to be fetched first
# It's the same as RoBERTa, so RobertaTokenizer can be used later
__magic_name__ = "openwebtext_ccnews_stories_books_cased"
# Specify download folder to Gluonnlp's vocab
__magic_name__ = os.path.join(get_home_dir() , "models" )
__magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ )
__magic_name__ = nlp.model.BERTModel(
lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , )
original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ )
__magic_name__ = original_bort._collect_params_with_prefix()
# Build our config 🤗
__magic_name__ = {
"architectures": ["BertForMaskedLM"],
"attention_probs_dropout_prob": predefined_args["dropout"],
"hidden_act": "gelu",
"hidden_dropout_prob": predefined_args["dropout"],
"hidden_size": predefined_args["embed_size"],
"initializer_range": 0.02,
"intermediate_size": predefined_args["hidden_size"],
"layer_norm_eps": predefined_args["layer_norm_eps"],
"max_position_embeddings": predefined_args["max_length"],
"model_type": "bort",
"num_attention_heads": predefined_args["num_heads"],
"num_hidden_layers": predefined_args["num_layers"],
"pad_token_id": 1, # 2 = BERT, 1 = RoBERTa
"type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa
"vocab_size": len(lowerCamelCase_ ),
}
__magic_name__ = BertConfig.from_dict(lowerCamelCase_ )
__magic_name__ = BertForMaskedLM(lowerCamelCase_ )
hf_bort_model.eval()
# Parameter mapping table (Gluonnlp to Transformers)
# * denotes layer index
#
# | Gluon Parameter | Transformers Parameter
# | -------------------------------------------------------------- | ----------------------
# | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias`
# | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight`
# | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight`
# | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
# | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight`
# | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight`
# | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias`
# | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight`
# Helper function to convert MXNET Arrays to PyTorch
def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter:
return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) )
# Check param shapes and map new HF param back
def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ):
__magic_name__ = hf_param.shape
__magic_name__ = to_torch(params[gluon_param] )
__magic_name__ = gluon_param.shape
assert (
shape_hf == shape_gluon
), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers'
return gluon_param
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" )
__magic_name__ = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" )
# Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
__magic_name__ = torch.zeros_like(
hf_bort_model.bert.embeddings.token_type_embeddings.weight.data )
for i in range(hf_bort_config.num_hidden_layers ):
__magic_name__ = hf_bort_model.bert.encoder.layer[i]
# self attention
__magic_name__ = layer.attention.self
__magic_name__ = check_and_map_params(
self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' )
__magic_name__ = check_and_map_params(
self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' )
__magic_name__ = check_and_map_params(
self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' )
__magic_name__ = check_and_map_params(
self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' )
__magic_name__ = check_and_map_params(
self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' )
__magic_name__ = check_and_map_params(
self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' )
# self attention output
__magic_name__ = layer.attention.output
__magic_name__ = check_and_map_params(
self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' )
__magic_name__ = check_and_map_params(
self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' )
__magic_name__ = check_and_map_params(
self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' )
# intermediate
__magic_name__ = layer.intermediate
__magic_name__ = check_and_map_params(
intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' )
__magic_name__ = check_and_map_params(
intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' )
# output
__magic_name__ = layer.output
__magic_name__ = check_and_map_params(
bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' )
__magic_name__ = check_and_map_params(
bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' )
__magic_name__ = check_and_map_params(
bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' )
# Save space and energy 🎄
hf_bort_model.half()
# Compare output of both models
__magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" )
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"]
# Get gluon output
__magic_name__ = mx.nd.array([input_ids] )
__magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] )
# Get Transformer output (save and reload model again)
hf_bort_model.save_pretrained(lowerCamelCase_ )
__magic_name__ = BertModel.from_pretrained(lowerCamelCase_ )
hf_bort_model.eval()
__magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" )
__magic_name__ = hf_bort_model(**lowerCamelCase_ )[0]
__magic_name__ = output_gluon[0].asnumpy()
__magic_name__ = output_hf[0].detach().numpy()
__magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item()
__magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 )
if success:
print("✔️ Both model do output the same tensors" )
else:
print("❌ Both model do **NOT** output the same tensors" )
print("Absolute difference is:" , lowerCamelCase_ )
if __name__ == "__main__":
__magic_name__ : int =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
__magic_name__ : Optional[Any] =parser.parse_args()
convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
| 664 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.